diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java b/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java index ab708975..caa33bef 100644 --- a/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java +++ b/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java @@ -1,799 +1,799 @@ package edu.cmu.sphinx.util.props; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * A property sheet which defines a collection of properties for a single component in the system. * * @author Holger Brandl */ public class PropertySheet implements Cloneable { public static final String COMP_LOG_LEVEL = "logLevel"; public enum PropertyType { INT, DOUBLE, BOOL, COMP, STRING, COMPLIST } private Map<String, S4PropWrapper> registeredProperties = new HashMap<String, S4PropWrapper>(); private Map<String, Object> propValues = new HashMap<String, Object>(); /** * Maps the names of the component properties to their (possibly unresolved) values. * <p/> * Example: <code>frontend</code> to <code>${myFrontEnd}</code> */ private Map<String, Object> rawProps = new HashMap<String, Object>(); private ConfigurationManager cm; private Configurable owner; private final Class<? extends Configurable> ownerClass; private String instanceName; public PropertySheet(Configurable configurable, String name, RawPropertyData rpd, ConfigurationManager ConfigurationManager) { this(configurable.getClass(), name, ConfigurationManager, rpd); owner = configurable; } public PropertySheet(Class<? extends Configurable> confClass, String name, ConfigurationManager cm, RawPropertyData rpd) { ownerClass = confClass; this.cm = cm; this.instanceName = name; processAnnotations(this, confClass); // now apply all xml properties Map<String, Object> flatProps = rpd.flatten(cm).getProperties(); rawProps = new HashMap<String, Object>(rpd.getProperties()); for (String propName : rawProps.keySet()) propValues.put(propName, flatProps.get(propName)); } /** * Registers a new property which type and default value are defined by the given sphinx property. * * @param propName The name of the property to be registered. * @param property The property annoation masked by a proxy. */ private void registerProperty(String propName, S4PropWrapper property) { if (property == null || propName == null) throw new InternalConfigurationException(getInstanceName(), propName, "property or its value is null"); registeredProperties.put(propName, property); propValues.put(propName, null); rawProps.put(propName, null); } /** Returns the property names <code>name</code> which is still wrapped into the annotation instance. */ public S4PropWrapper getProperty(String name, Class propertyClass) throws PropertyException { if (!propValues.containsKey(name)) throw new InternalConfigurationException(getInstanceName(), name, "Unknown property '" + name + "' ! Make sure that you've annotated it."); S4PropWrapper s4PropWrapper = registeredProperties.get(name); try { propertyClass.cast(s4PropWrapper.getAnnotation()); } catch (ClassCastException e) { throw new InternalConfigurationException(e, getInstanceName(), name, name + " is not an annotated sphinx property of '" + getConfigurableClass().getName() + "' !"); } return s4PropWrapper; } /** * Gets the value associated with this name * * @param name the name * @return the value */ public String getString(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4String.class); S4String s4String = ((S4String) s4PropWrapper.getAnnotation()); if (propValues.get(name) == null) { boolean isDefDefined = !s4String.defaultValue().equals(S4String.NOT_DEFINED); if (s4String.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } // else if(!isDefDefined) // throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, isDefDefined ? s4String.defaultValue() : null); } String propValue = flattenProp(name); //check range List<String> range = Arrays.asList(s4String.range()); if (!range.isEmpty() && !range.contains(propValue)) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } private String flattenProp(String name) { Object value = propValues.get(name); return value instanceof String ? (String) value : (value instanceof GlobalProperty ? (String) ((GlobalProperty) value).getValue() : null); } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public int getInt(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Integer.class); S4Integer s4Integer = (S4Integer) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null) { boolean isDefDefined = !(s4Integer.defaultValue() == S4Integer.NOT_DEFINED); if (s4Integer.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, s4Integer.defaultValue()); } Object propObject = propValues.get(name); Integer propValue = propObject instanceof Integer ? (Integer) propObject : Integer.decode(flattenProp(name)); int[] range = s4Integer.range(); if (range.length != 2) throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)"); if (propValue < range[0] || propValue > range[1]) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public float getFloat(String name) throws PropertyException { return ((Double) getDouble(name)).floatValue(); } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public double getDouble(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Double.class); S4Double s4Double = (S4Double) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null) { boolean isDefDefined = !(s4Double.defaultValue() == S4Double.NOT_DEFINED); if (s4Double.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, s4Double.defaultValue()); } Object propObject = propValues.get(name); Double propValue = propObject instanceof Double ? (Double) propObject : Double.valueOf(flattenProp(name)); double[] range = s4Double.range(); if (range.length != 2) throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)"); if (propValue < range[0] || propValue > range[1]) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public Boolean getBoolean(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Boolean.class); S4Boolean s4Boolean = (S4Boolean) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null && !s4Boolean.isNotDefined()) propValues.put(name, s4Boolean.defaultValue()); Object propValue = propValues.get(name); if (propValue instanceof String) propValue = Boolean.valueOf((String) propValue); return (Boolean) propValue; } /** * Gets a component associated with the given parameter name * * @param name the parameter name * @return the component associated with the name * @throws edu.cmu.sphinx.util.props.PropertyException * if the component does not exist or is of the wrong type. */ public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); Object propVal = propValues.get(name); if (propVal == null || propVal instanceof String || propVal instanceof GlobalProperty) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet(flattenProp(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, make sure that it is set if (defClass.equals(Configurable.class)) { if (s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); } else { return null; } } configurable = ConfigurationManager.getInstance(defClass); if (configurable == null) { throw new InternalConfigurationException(getInstanceName(), name, "instantiation of referenenced Configurable failed"); } } } } catch (ClassNotFoundException e) { - throw new PropertyException(e, getInstanceName(), null, null); + throw new PropertyException(e, getInstanceName(), name, null); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); } /** Returns the class of of a registered component property without instantiating it. */ public Class<? extends Configurable> getComponentClass(String propName) { Class<? extends Configurable> defClass = null; if (propValues.get(propName) != null) try { defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(propName)); } catch (ClassNotFoundException e) { e.printStackTrace(); } else { S4Component comAnno = (S4Component) registeredProperties.get(propName).getAnnotation(); defClass = comAnno.defaultClass(); if (comAnno.mandatory()) defClass = null; } return defClass; } /** * Gets a list of components associated with the given parameter name * * @param name the parameter name * @return the component associated with the name * @throws edu.cmu.sphinx.util.props.PropertyException * if the component does not exist or is of the wrong type. */ public List<? extends Configurable> getComponentList(String name) throws InternalConfigurationException { getProperty(name, S4ComponentList.class); List components = (List) propValues.get(name); assert registeredProperties.get(name).getAnnotation() instanceof S4ComponentList; S4ComponentList annoation = (S4ComponentList) registeredProperties.get(name).getAnnotation(); // no componets names are available and no comp-list was yet loaded // therefore load the default list of components from the annoation if (components == null) { List<Class<? extends Configurable>> defClasses = Arrays.asList(annoation.defaultList()); // if (annoation.mandatory() && defClasses.isEmpty()) // throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); components = new ArrayList(); for (Class<? extends Configurable> defClass : defClasses) { components.add(ConfigurationManager.getInstance(defClass)); } propValues.put(name, components); } if (!components.isEmpty() && !(components.get(0) instanceof Configurable)) { List<Configurable> list = new ArrayList<Configurable>(); for (Object componentName : components) { Configurable configurable = cm.lookup((String) componentName); if (configurable != null) { list.add(configurable); } else if (!annoation.beTolerant()) { throw new InternalConfigurationException(name, (String) componentName, "lookup of list-element '" + componentName + "' failed!"); } } propValues.put(name, list); } return (List<? extends Configurable>) propValues.get(name); } public String getInstanceName() { return instanceName; } public void setInstanceName(String newInstanceName) { this.instanceName = newInstanceName; } /** Returns true if the owner of this property sheet is already instanciated. */ public boolean isInstanciated() { return !(owner == null); } /** * Returns the owner of this property sheet. In most cases this will be the configurable instance which was * instrumented by this property sheet. */ public synchronized Configurable getOwner() { try { if (!isInstanciated()) { // ensure that all mandatory properties are set before instantiating the component Collection<String> undefProps = getUndefinedMandatoryProps(); if (!undefProps.isEmpty()) { throw new InternalConfigurationException(getInstanceName(), undefProps.toString(), "not all mandatory properties are defined"); } owner = ownerClass.newInstance(); owner.newProperties(this); } } catch (IllegalAccessException e) { throw new InternalConfigurationException(e, getInstanceName(), null, "Can't access class " + ownerClass); } catch (InstantiationException e) { throw new InternalConfigurationException(e, getInstanceName(), null, "Can't instantiate class " + ownerClass); } return owner; } /** * Returns the set of all component properties which were tagged as mandatory but which are not set (or no default * value is given). */ public Collection<String> getUndefinedMandatoryProps() { Collection<String> undefProps = new ArrayList<String>(); for (String propName : getRegisteredProperties()) { Proxy anno = registeredProperties.get(propName).getAnnotation(); boolean isMandatory = false; if (anno instanceof S4Component) { isMandatory = ((S4Component) anno).mandatory() && ((S4Component) anno).defaultClass() == null; } else if (anno instanceof S4String) { isMandatory = ((S4String) anno).mandatory() && ((S4String) anno).defaultValue().equals(S4String.NOT_DEFINED); } else if (anno instanceof S4Integer) { isMandatory = ((S4Integer) anno).mandatory() && ((S4Integer) anno).defaultValue() == S4Integer.NOT_DEFINED; } else if (anno instanceof S4Double) { isMandatory = ((S4Double) anno).mandatory() && ((S4Double) anno).defaultValue() == S4Double.NOT_DEFINED; } if (isMandatory && !((rawProps.get(propName) != null) || (propValues.get(propName) != null))) undefProps.add(propName); } return undefProps; } /** Returns the class of the owner configurable of this property sheet. */ public Class<? extends Configurable> getConfigurableClass() { return ownerClass; } /** * Sets the given property to the given name * * @param name the simple property name */ public void setString(String name, String value) throws PropertyException { // ensure that there is such a property if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered string-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4String)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type string"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setInt(String name, int value) throws PropertyException { // ensure that there is such a property if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered int-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Integer)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type int"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setDouble(String name, double value) throws PropertyException { // ensure that there is such a property if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered double-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Double)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type double"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setBoolean(String name, Boolean value) throws PropertyException { if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered boolean-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Boolean)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type boolean"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param cmName the name of the configurable within the configuration manager (required for serialization only) * @param value the value for the property */ public void setComponent(String name, String cmName, Configurable value) throws PropertyException { if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered compontent"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Component)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type component"); applyConfigurationChange(name, cmName, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param valueNames the list of names of the configurables within the configuration manager (required for * serialization only) * @param value the value for the property */ public void setComponentList(String name, List<String> valueNames, List<Configurable> value) throws PropertyException { if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered component-list"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4ComponentList)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type component-list"); rawProps.put(name, valueNames); propValues.put(name, value); applyConfigurationChange(name, valueNames, value); } private void applyConfigurationChange(String propName, Object cmName, Object value) throws PropertyException { rawProps.put(propName, cmName); propValues.put(propName, value != null ? value : cmName); if (getInstanceName() != null) cm.fireConfChanged(getInstanceName(), propName); if (owner != null) owner.newProperties(this); } /** * Sets the raw property to the given name * * @param key the simple property name * @param val the value for the property */ void setRaw(String key, Object val) { rawProps.put(key, val); propValues.put(key, null); } /** * Gets the raw value associated with this name * * @param name the name * @return the value as an object (it could be a String or a String[] depending upon the property type) */ public Object getRaw(String name) { return rawProps.get(name); } /** * Gets the raw value associated with this name, no global symbol replacement is performed. * * @param name the name * @return the value as an object (it could be a String or a String[] depending upon the property type) */ public Object getRawNoReplacement(String name) { return rawProps.get(name); } /** Returns the type of the given property. */ public PropertyType getType(String propName) { Proxy annotation = registeredProperties.get(propName).getAnnotation(); if (annotation instanceof S4Component) return PropertyType.COMP; else if (annotation instanceof S4ComponentList) return PropertyType.COMPLIST; else if (annotation instanceof S4Integer) return PropertyType.INT; else if (annotation instanceof S4Double) return PropertyType.DOUBLE; else if (annotation instanceof S4Boolean) return PropertyType.BOOL; else if (annotation instanceof S4String) return PropertyType.STRING; else throw new RuntimeException("Unknown property type"); } /** * Gets the owning property manager * * @return the property manager */ ConfigurationManager getPropertyManager() { return cm; } /** * Returns a logger to use for this configurable component. The logger can be configured with the property: * 'logLevel' - The default logLevel value is defined (within the xml configuration file by the global property * 'defaultLogLevel' (which defaults to WARNING). * <p/> * implementation note: the logger became configured within the constructor of the parenting configuration manager. * * @return the logger for this component * @throws edu.cmu.sphinx.util.props.PropertyException * if an error occurs */ public Logger getLogger() { Logger logger; String baseName = ConfigurationManagerUtils.getLogPrefix(cm) + ownerClass.getName(); if (instanceName != null) { logger = Logger.getLogger(baseName + "." + instanceName); } else logger = Logger.getLogger(baseName); // if there's a logLevel set for component apply to the logger Object rawLogLevel = rawProps.get(COMP_LOG_LEVEL); if (rawLogLevel != null) logger.setLevel(rawLogLevel instanceof String ? Level.parse((String) rawLogLevel) : (Level) rawLogLevel); return logger; } /** Returns the names of registered properties of this PropertySheet object. */ public Collection<String> getRegisteredProperties() { return Collections.unmodifiableCollection(registeredProperties.keySet()); } public void setCM(ConfigurationManager cm) { this.cm = cm; } /** * Returns true if two property sheet define the same object in terms of configuration. The owner (and the parent * configuration manager) are not expected to be the same. */ public boolean equals(Object obj) { if (obj == null || !(obj instanceof PropertySheet)) return false; PropertySheet ps = (PropertySheet) obj; if (!rawProps.keySet().equals(ps.rawProps.keySet())) return false; // maybe we could test a little bit more here. suggestions? return true; } @Override public String toString() { return getInstanceName() + "; isInstantiated=" + isInstanciated() + "; props=" + rawProps.keySet().toString(); } protected Object clone() throws CloneNotSupportedException { PropertySheet ps = (PropertySheet) super.clone(); ps.registeredProperties = new HashMap<String, S4PropWrapper>(this.registeredProperties); ps.propValues = new HashMap<String, Object>(this.propValues); ps.rawProps = new HashMap<String, Object>(this.rawProps); // make deep copy of raw-lists for (String regProp : ps.getRegisteredProperties()) { if (getType(regProp).equals(PropertyType.COMPLIST)) { ps.rawProps.put(regProp, new ArrayList<String>((Collection<? extends String>) rawProps.get(regProp))); ps.propValues.put(regProp, null); } } ps.cm = cm; ps.owner = null; ps.instanceName = this.instanceName; return ps; } /** * use annotation based class parsing to detect the configurable properties of a <code>Configurable</code>-class * * @param propertySheet of type PropertySheet * @param configurable of type Class<? extends Configurable> */ public static void processAnnotations(PropertySheet propertySheet, Class<? extends Configurable> configurable) { Field[] classFields = configurable.getFields(); for (Field field : classFields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { Annotation[] superAnnotations = annotation.annotationType().getAnnotations(); for (Annotation superAnnotation : superAnnotations) { if (superAnnotation instanceof S4Property) { int fieldModifiers = field.getModifiers(); assert Modifier.isStatic(fieldModifiers) : "property fields are assumed to be static"; assert Modifier.isPublic(fieldModifiers) : "property fields are assumed to be public"; assert field.getType().equals(String.class) : "properties fields are assumed to be instances of java.lang.String"; try { String propertyName = (String) field.get(null); // make sure that there is not already another property with this name assert !propertySheet.getRegisteredProperties().contains(propertyName) : "duplicate property-name for different properties: " + propertyName; propertySheet.registerProperty(propertyName, new S4PropWrapper((Proxy) annotation)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } } }
true
true
public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); Object propVal = propValues.get(name); if (propVal == null || propVal instanceof String || propVal instanceof GlobalProperty) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet(flattenProp(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, make sure that it is set if (defClass.equals(Configurable.class)) { if (s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); } else { return null; } } configurable = ConfigurationManager.getInstance(defClass); if (configurable == null) { throw new InternalConfigurationException(getInstanceName(), name, "instantiation of referenenced Configurable failed"); } } } } catch (ClassNotFoundException e) { throw new PropertyException(e, getInstanceName(), null, null); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); }
public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); Object propVal = propValues.get(name); if (propVal == null || propVal instanceof String || propVal instanceof GlobalProperty) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet(flattenProp(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, make sure that it is set if (defClass.equals(Configurable.class)) { if (s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); } else { return null; } } configurable = ConfigurationManager.getInstance(defClass); if (configurable == null) { throw new InternalConfigurationException(getInstanceName(), name, "instantiation of referenenced Configurable failed"); } } } } catch (ClassNotFoundException e) { throw new PropertyException(e, getInstanceName(), name, null); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); }
diff --git a/src/solandra/SolandraDispatchFilter.java b/src/solandra/SolandraDispatchFilter.java index a6f81c7..b0d9717 100644 --- a/src/solandra/SolandraDispatchFilter.java +++ b/src/solandra/SolandraDispatchFilter.java @@ -1,206 +1,206 @@ /** * Copyright T Jake Luciani * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package solandra; import java.io.*; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.solr.core.SolandraCoreContainer; import org.apache.solr.core.CoreContainer.Initializer; import org.apache.solr.request.*; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.servlet.SolrDispatchFilter; import org.apache.solr.servlet.cache.Method; public class SolandraDispatchFilter extends SolrDispatchFilter { private static final String schemaPrefix = "/schema"; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String indexName = ""; String resourceName = ""; String path = req.getServletPath(); if (req.getPathInfo() != null) { // this lets you handle /update/commit when /update is a servlet path += req.getPathInfo(); } if (path.startsWith(schemaPrefix)) { path = path.substring(schemaPrefix.length()); // otherwise, we should find a index from the path int idx = path.indexOf("/", 1); - if (idx == schemaPrefix.length()) + if (idx > 1 && path.startsWith("/")) { // try to get the index as a request parameter first indexName = path.substring(1, idx); resourceName = path.substring(idx+1); } else { indexName = path.substring(1); } // REST String method = req.getMethod().toUpperCase(); if (method.equals("GET")) { try { String resource = ""; if(resourceName.isEmpty() || resourceName.equalsIgnoreCase("schema.xml")) { resource = SolandraCoreContainer.getCoreMetaInfo(indexName); response.setContentType("text/xml"); } else { resource = ByteBufferUtil.string(SolandraCoreContainer.readCoreResource(indexName, resourceName)); } PrintWriter out = resp.getWriter(); out.print(resource); } catch (IOException e) { resp.sendError(404,e.toString()); } return; } if (method.equals("POST") || method.equals("PUT")) { try { BufferedReader rd = new BufferedReader(new InputStreamReader(req.getInputStream())); String line; String resource = ""; while ((line = rd.readLine()) != null) { resource += line + "\n"; } if(resourceName.isEmpty() || resourceName.equalsIgnoreCase("schema.xml")) { SolandraCoreContainer.writeSchema(indexName, resource); } else { SolandraCoreContainer.writeCoreResource(indexName, resourceName, resource); } } catch (IOException e) { resp.sendError(500); } return; } } SolandraCoreContainer.activeRequest.set(req); super.doFilter(request, response, chain); } @Override protected Initializer createInitializer() { SolandraInitializer init = new SolandraInitializer(); return init; } @Override protected void execute(HttpServletRequest req, SolrRequestHandler handler, SolrQueryRequest sreq, SolrQueryResponse rsp) { String path = req.getServletPath(); if (req.getPathInfo() != null) { // this lets you handle /update/commit when /update is a servlet path += req.getPathInfo(); } if (pathPrefix != null && path.startsWith(pathPrefix)) { path = path.substring(pathPrefix.length()); } int idx = path.indexOf("/", 1); if (idx > 1) { // try to get the corename as a request parameter first sreq.getContext().put("solandra-index", path.substring(1, idx)); } super.execute(req, handler, sreq, rsp); } private void writeResponse(SolrQueryResponse solrRsp, ServletResponse response, QueryResponseWriter responseWriter, SolrQueryRequest solrReq, Method reqMethod) throws IOException { if (solrRsp.getException() != null) { sendError((HttpServletResponse) response, solrRsp.getException()); } else { // Now write it out response.setContentType(responseWriter.getContentType(solrReq, solrRsp)); if (Method.HEAD != reqMethod) { if (responseWriter instanceof BinaryQueryResponseWriter) { BinaryQueryResponseWriter binWriter = (BinaryQueryResponseWriter) responseWriter; binWriter.write(response.getOutputStream(), solrReq, solrRsp); } else { PrintWriter out = response.getWriter(); responseWriter.write(out, solrReq, solrRsp); } } // else http HEAD request, nothing to write out, waited this long // just to get ContentType } } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String indexName = ""; String resourceName = ""; String path = req.getServletPath(); if (req.getPathInfo() != null) { // this lets you handle /update/commit when /update is a servlet path += req.getPathInfo(); } if (path.startsWith(schemaPrefix)) { path = path.substring(schemaPrefix.length()); // otherwise, we should find a index from the path int idx = path.indexOf("/", 1); if (idx == schemaPrefix.length()) { // try to get the index as a request parameter first indexName = path.substring(1, idx); resourceName = path.substring(idx+1); } else { indexName = path.substring(1); } // REST String method = req.getMethod().toUpperCase(); if (method.equals("GET")) { try { String resource = ""; if(resourceName.isEmpty() || resourceName.equalsIgnoreCase("schema.xml")) { resource = SolandraCoreContainer.getCoreMetaInfo(indexName); response.setContentType("text/xml"); } else { resource = ByteBufferUtil.string(SolandraCoreContainer.readCoreResource(indexName, resourceName)); } PrintWriter out = resp.getWriter(); out.print(resource); } catch (IOException e) { resp.sendError(404,e.toString()); } return; } if (method.equals("POST") || method.equals("PUT")) { try { BufferedReader rd = new BufferedReader(new InputStreamReader(req.getInputStream())); String line; String resource = ""; while ((line = rd.readLine()) != null) { resource += line + "\n"; } if(resourceName.isEmpty() || resourceName.equalsIgnoreCase("schema.xml")) { SolandraCoreContainer.writeSchema(indexName, resource); } else { SolandraCoreContainer.writeCoreResource(indexName, resourceName, resource); } } catch (IOException e) { resp.sendError(500); } return; } } SolandraCoreContainer.activeRequest.set(req); super.doFilter(request, response, chain); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String indexName = ""; String resourceName = ""; String path = req.getServletPath(); if (req.getPathInfo() != null) { // this lets you handle /update/commit when /update is a servlet path += req.getPathInfo(); } if (path.startsWith(schemaPrefix)) { path = path.substring(schemaPrefix.length()); // otherwise, we should find a index from the path int idx = path.indexOf("/", 1); if (idx > 1 && path.startsWith("/")) { // try to get the index as a request parameter first indexName = path.substring(1, idx); resourceName = path.substring(idx+1); } else { indexName = path.substring(1); } // REST String method = req.getMethod().toUpperCase(); if (method.equals("GET")) { try { String resource = ""; if(resourceName.isEmpty() || resourceName.equalsIgnoreCase("schema.xml")) { resource = SolandraCoreContainer.getCoreMetaInfo(indexName); response.setContentType("text/xml"); } else { resource = ByteBufferUtil.string(SolandraCoreContainer.readCoreResource(indexName, resourceName)); } PrintWriter out = resp.getWriter(); out.print(resource); } catch (IOException e) { resp.sendError(404,e.toString()); } return; } if (method.equals("POST") || method.equals("PUT")) { try { BufferedReader rd = new BufferedReader(new InputStreamReader(req.getInputStream())); String line; String resource = ""; while ((line = rd.readLine()) != null) { resource += line + "\n"; } if(resourceName.isEmpty() || resourceName.equalsIgnoreCase("schema.xml")) { SolandraCoreContainer.writeSchema(indexName, resource); } else { SolandraCoreContainer.writeCoreResource(indexName, resourceName, resource); } } catch (IOException e) { resp.sendError(500); } return; } } SolandraCoreContainer.activeRequest.set(req); super.doFilter(request, response, chain); }
diff --git a/Builder/src/UnpackBinaryResources.java b/Builder/src/UnpackBinaryResources.java index e36d9df..7b6c37f 100644 --- a/Builder/src/UnpackBinaryResources.java +++ b/Builder/src/UnpackBinaryResources.java @@ -1,150 +1,152 @@ import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.xml.bind.JAXBContext; import org.alex73.android.Context; import org.alex73.android.IDecoder; import org.alex73.android.IEncoder; import org.alex73.android.StAXDecoder; import org.alex73.android.StAXEncoder; import org.alex73.android.StyledString; import org.alex73.android.arsc.ChunkReader; import org.alex73.android.arsc.ChunkWriter; import org.alex73.android.arsc.ManifestInfo; import org.alex73.android.arsc.Resources; import org.alex73.android.arsc.StringTable; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Assert; import android.control.App; import android.control.Translation; /** * Imports binary resources. arg0 is binaries .zips dir */ public class UnpackBinaryResources { static String projectPath = "../../Android.OmegaT/Android/"; static File[] zips; static List<BuildAll.FileInfo> fileNames = new ArrayList<BuildAll.FileInfo>(); static Translation translationInfo; public static void main(String[] args) throws Exception { readTranslationInfo(); // process binary zips zips = new File(args[0]).listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".zip"); } }); for (File zipFile : zips) { System.out.println(zipFile); ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze; while ((ze = in.getNextEntry()) != null) { if (ze.getName().contains("GameHub") && zipFile.getName().contains("s2")) { // invalid entry size (expected 2255224840 but got 50345 // bytes) continue; } if (ze.getName().endsWith(".apk")) { byte[] apk = IOUtils.toByteArray(in); byte[] manifest = BuildAll.extractFile(apk, "AndroidManifest.xml"); ManifestInfo mi = new ManifestInfo(manifest); System.out.println(" " + ze.getName() + " p:" + mi.getPackageName() + " v:" + mi.getVersion()); Context.setByManifest(mi); String dirName = getDirName(mi.getPackageName(), mi.getVersion()); if (dirName != null) { byte[] arsc = BuildAll.extractFile(apk, "resources.arsc"); - processARSC(arsc, dirName, createSuffix(mi)); + if (arsc != null) { + processARSC(arsc, dirName, createSuffix(mi)); + } } } System.gc(); } } } protected static void processARSC(byte[] arsc, String dirName, String suffixVersion) throws Exception { ChunkReader rsReader = new ChunkReader(arsc); Resources rs = new Resources(rsReader); File out = new File(projectPath + "/source/" + dirName); out.mkdirs(); checkAllStrings(rs.getStringTable()); // checks ChunkWriter wr = rs.getStringTable().write(); byte[] readed = rs.getStringTable().getOriginalBytes(); byte[] written = wr.getBytes(); if (!Arrays.equals(readed, written)) { FileUtils.writeByteArrayToFile(new File("/tmp/st-orig"), readed); FileUtils.writeByteArrayToFile(new File("/tmp/st-new"), written); throw new Exception("StringTables are differ: /tmp/st-orig, /tmp/st-new"); } System.out.println(" Store resources in " + out.getAbsolutePath() + " version=" + suffixVersion); new StAXEncoder().dump(rs, out, suffixVersion); // зыходныя рэсурсы захаваныя наноў - для параўняньня ChunkWriter rsWriterOriginal = rs.write(); Assert.assertArrayEquals(arsc, rsWriterOriginal.getBytes()); } protected static void checkAllStrings(final StringTable table) throws Exception { IEncoder encoder = new StAXEncoder(); IDecoder decoder = new StAXDecoder(); for (int i = 0; i < table.getStringCount(); i++) { StyledString ss1 = table.getStyledString(i); if (ss1.hasInvalidChars()) { continue; } String x = encoder.marshall(ss1); StyledString ss2 = decoder.unmarshall(x); Assert.assertEquals(ss1.raw, ss2.raw); Assert.assertArrayEquals(ss1.tags, ss2.tags); } } static final String ALLOWED_VER = "0123456789."; static String createSuffix(ManifestInfo mi) { return mi.getVersion(); } static void readTranslationInfo() throws Exception { JAXBContext ctx = JAXBContext.newInstance(Translation.class); translationInfo = (Translation) ctx.createUnmarshaller() .unmarshal(new File(projectPath + "../translation.xml")); } static String getDirName(String packageName, String versionName) { String dirName = null; for (App app : translationInfo.getApp()) { if (!packageName.equals(app.getPackageName())) { continue; } if (dirName != null) { throw new RuntimeException("Duplicate dir for package " + packageName); } dirName = app.getDirName(); } return dirName; } }
true
true
public static void main(String[] args) throws Exception { readTranslationInfo(); // process binary zips zips = new File(args[0]).listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".zip"); } }); for (File zipFile : zips) { System.out.println(zipFile); ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze; while ((ze = in.getNextEntry()) != null) { if (ze.getName().contains("GameHub") && zipFile.getName().contains("s2")) { // invalid entry size (expected 2255224840 but got 50345 // bytes) continue; } if (ze.getName().endsWith(".apk")) { byte[] apk = IOUtils.toByteArray(in); byte[] manifest = BuildAll.extractFile(apk, "AndroidManifest.xml"); ManifestInfo mi = new ManifestInfo(manifest); System.out.println(" " + ze.getName() + " p:" + mi.getPackageName() + " v:" + mi.getVersion()); Context.setByManifest(mi); String dirName = getDirName(mi.getPackageName(), mi.getVersion()); if (dirName != null) { byte[] arsc = BuildAll.extractFile(apk, "resources.arsc"); processARSC(arsc, dirName, createSuffix(mi)); } } System.gc(); } } }
public static void main(String[] args) throws Exception { readTranslationInfo(); // process binary zips zips = new File(args[0]).listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".zip"); } }); for (File zipFile : zips) { System.out.println(zipFile); ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze; while ((ze = in.getNextEntry()) != null) { if (ze.getName().contains("GameHub") && zipFile.getName().contains("s2")) { // invalid entry size (expected 2255224840 but got 50345 // bytes) continue; } if (ze.getName().endsWith(".apk")) { byte[] apk = IOUtils.toByteArray(in); byte[] manifest = BuildAll.extractFile(apk, "AndroidManifest.xml"); ManifestInfo mi = new ManifestInfo(manifest); System.out.println(" " + ze.getName() + " p:" + mi.getPackageName() + " v:" + mi.getVersion()); Context.setByManifest(mi); String dirName = getDirName(mi.getPackageName(), mi.getVersion()); if (dirName != null) { byte[] arsc = BuildAll.extractFile(apk, "resources.arsc"); if (arsc != null) { processARSC(arsc, dirName, createSuffix(mi)); } } } System.gc(); } } }
diff --git a/src/main/java/org/zkoss/fiddle/composer/SourceCodeEditorInsertComposer.java b/src/main/java/org/zkoss/fiddle/composer/SourceCodeEditorInsertComposer.java index 5bd1ed5..8185f20 100755 --- a/src/main/java/org/zkoss/fiddle/composer/SourceCodeEditorInsertComposer.java +++ b/src/main/java/org/zkoss/fiddle/composer/SourceCodeEditorInsertComposer.java @@ -1,85 +1,86 @@ package org.zkoss.fiddle.composer; import org.zkoss.fiddle.composer.eventqueue.impl.FiddleSourceEventQueue; import org.zkoss.fiddle.core.utils.ResourceFactory; import org.zkoss.fiddle.model.Resource; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Combobox; import org.zkoss.zul.Label; import org.zkoss.zul.ListModelList; import org.zkoss.zul.Textbox; public class SourceCodeEditorInsertComposer extends GenericForwardComposer { /** * */ private static final long serialVersionUID = -316305359195204898L; private Combobox type; private Label extension; private Textbox fileName; private static final String[] DATA = new String[] { "zul", "java", "html", "js", "js.dsp", "css", "css.dsp" }; @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); type.setModel(new ListModelList(DATA)); } /** * we use desktop level event queue. */ // private EventQueue sourceQueue = // EventQueues.lookup(FiddleEventQueues.SOURCE, true); public void onClick$insert(Event e) { String fileNameStr = fileName.getValue(); if ("".equals(fileNameStr)) { alert("file name cannot be empty!"); return; } String selected = type.getSelectedItem().getLabel(); int typeVal = getType(selected); String fileNameVal = fileNameStr + getTypeExtension(selected); Resource resource = ResourceFactory.getDefaultResource(typeVal, fileNameVal); FiddleSourceEventQueue.lookup().fireResourceInsert(fileNameVal, typeVal, resource); type.setSelectedIndex(0); + extension.setValue(getTypeExtension(type.getValue())); fileName.setText("test"); self.setVisible(false); } public void onCreate() { type.setSelectedIndex(0); } public void onSelect$type() { String tpStr = type.getValue(); extension.setValue(getTypeExtension(tpStr)); } private static int getType(String tpStr) { if("zul".equals(tpStr)){ return Resource.TYPE_ZUL; }else if("java".equals(tpStr)){ return Resource.TYPE_JAVA; }else if("html".equals(tpStr)){ return Resource.TYPE_HTML; }else if("js".equals(tpStr) || "js.dsp".equals(tpStr)){ return Resource.TYPE_JS; }else if("css".equals(tpStr) || "css.dsp".equals(tpStr)){ return Resource.TYPE_CSS; } return Resource.TYPE_HTML; } private static String getTypeExtension(String tpStr) { return "." + tpStr; } }
true
true
public void onClick$insert(Event e) { String fileNameStr = fileName.getValue(); if ("".equals(fileNameStr)) { alert("file name cannot be empty!"); return; } String selected = type.getSelectedItem().getLabel(); int typeVal = getType(selected); String fileNameVal = fileNameStr + getTypeExtension(selected); Resource resource = ResourceFactory.getDefaultResource(typeVal, fileNameVal); FiddleSourceEventQueue.lookup().fireResourceInsert(fileNameVal, typeVal, resource); type.setSelectedIndex(0); fileName.setText("test"); self.setVisible(false); }
public void onClick$insert(Event e) { String fileNameStr = fileName.getValue(); if ("".equals(fileNameStr)) { alert("file name cannot be empty!"); return; } String selected = type.getSelectedItem().getLabel(); int typeVal = getType(selected); String fileNameVal = fileNameStr + getTypeExtension(selected); Resource resource = ResourceFactory.getDefaultResource(typeVal, fileNameVal); FiddleSourceEventQueue.lookup().fireResourceInsert(fileNameVal, typeVal, resource); type.setSelectedIndex(0); extension.setValue(getTypeExtension(type.getValue())); fileName.setText("test"); self.setVisible(false); }
diff --git a/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizard.java b/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizard.java index 85a29bf6..e2375e5f 100644 --- a/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizard.java +++ b/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizard.java @@ -1,606 +1,606 @@ /******************************************************************************* * Copyright (c) 2006, 2010 Soyatec(http://www.soyatec.com) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Soyatec - initial API and implementation *******************************************************************************/ package org.eclipse.e4.internal.tools.wizards.project; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.e4.ui.model.application.MApplication; import org.eclipse.e4.ui.model.application.MApplicationFactory; import org.eclipse.e4.ui.model.application.commands.MBindingContext; import org.eclipse.e4.ui.model.application.commands.MBindingTable; import org.eclipse.e4.ui.model.application.commands.MCommand; import org.eclipse.e4.ui.model.application.commands.MCommandsFactory; import org.eclipse.e4.ui.model.application.commands.MHandler; import org.eclipse.e4.ui.model.application.commands.MKeyBinding; import org.eclipse.e4.ui.model.application.ui.advanced.MAdvancedFactory; import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective; import org.eclipse.e4.ui.model.application.ui.advanced.MPerspectiveStack; import org.eclipse.e4.ui.model.application.ui.basic.MBasicFactory; import org.eclipse.e4.ui.model.application.ui.basic.MPartSashContainer; import org.eclipse.e4.ui.model.application.ui.basic.MPartStack; import org.eclipse.e4.ui.model.application.ui.basic.MTrimBar; import org.eclipse.e4.ui.model.application.ui.basic.MTrimmedWindow; import org.eclipse.e4.ui.model.application.ui.menu.MHandledMenuItem; import org.eclipse.e4.ui.model.application.ui.menu.MHandledToolItem; import org.eclipse.e4.ui.model.application.ui.menu.MMenu; import org.eclipse.e4.ui.model.application.ui.menu.MMenuFactory; import org.eclipse.e4.ui.model.application.ui.menu.MToolBar; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.pde.core.plugin.IPluginBase; import org.eclipse.pde.core.plugin.IPluginElement; import org.eclipse.pde.core.plugin.IPluginExtension; import org.eclipse.pde.core.plugin.IPluginImport; import org.eclipse.pde.internal.core.ICoreConstants; import org.eclipse.pde.internal.core.bundle.WorkspaceBundlePluginModel; import org.eclipse.pde.internal.core.plugin.WorkspacePluginModelBase; import org.eclipse.pde.internal.ui.PDEPlugin; import org.eclipse.pde.internal.ui.PDEUIMessages; import org.eclipse.pde.internal.ui.wizards.IProjectProvider; import org.eclipse.pde.internal.ui.wizards.plugin.NewPluginProjectWizard; import org.eclipse.pde.internal.ui.wizards.plugin.NewProjectCreationOperation; import org.eclipse.pde.internal.ui.wizards.plugin.PluginFieldData; import org.eclipse.ui.IWorkingSet; import org.osgi.framework.Bundle; import org.osgi.framework.Version; /** * @author jin.liu ([email protected]) */ public class E4NewProjectWizard extends NewPluginProjectWizard { private PluginFieldData fPluginData; private NewApplicationWizardPage fApplicationPage; private IProjectProvider fProjectProvider; private PluginContentPage fContentPage; public E4NewProjectWizard() { fPluginData = new PluginFieldData(); } public void addPages() { fMainPage = new E4NewProjectWizardPage( "main", fPluginData, false, getSelection()); //$NON-NLS-1$ fMainPage.setTitle(PDEUIMessages.NewProjectWizard_MainPage_title); fMainPage.setDescription(PDEUIMessages.NewProjectWizard_MainPage_desc); String pname = getDefaultValue(DEF_PROJECT_NAME); if (pname != null) fMainPage.setInitialProjectName(pname); addPage(fMainPage); fProjectProvider = new IProjectProvider() { public String getProjectName() { return fMainPage.getProjectName(); } public IProject getProject() { return fMainPage.getProjectHandle(); } public IPath getLocationPath() { return fMainPage.getLocationPath(); } }; fContentPage = new PluginContentPage( "page2", fProjectProvider, fMainPage, fPluginData); //$NON-NLS-1$ fApplicationPage = new NewApplicationWizardPage(fProjectProvider); addPage(fContentPage); addPage(fApplicationPage); } @SuppressWarnings("restriction") public boolean performFinish() { try { fMainPage.updateData(); fContentPage.updateData(); IDialogSettings settings = getDialogSettings(); if (settings != null) { fMainPage.saveSettings(settings); fContentPage.saveSettings(settings); } getContainer().run( false, true, new NewProjectCreationOperation(fPluginData, fProjectProvider, null) { private WorkspacePluginModelBase model; @Override protected void adjustManifests( IProgressMonitor monitor, IProject project, IPluginBase bundle) throws CoreException { super.adjustManifests(monitor, project, bundle); IPluginBase pluginBase = model.getPluginBase(); String[] dependencyId = new String[] { "javax.inject", "org.eclipse.core.resources", "org.eclipse.core.runtime", "org.eclipse.swt", "org.eclipse.core.databinding", "org.eclipse.core.databinding.beans", "org.eclipse.jface", "org.eclipse.jface.databinding", "org.eclipse.e4.ui.services", "org.eclipse.e4.ui.workbench", "org.eclipse.e4.core.services", "org.eclipse.e4.core.di", "org.eclipse.e4.core.contexts", "org.eclipse.e4.ui.workbench.swt", "org.eclipse.core.databinding.property", "org.eclipse.e4.ui.css.core", "org.w3c.css.sac", "org.eclipse.e4.core.commands", "org.eclipse.e4.ui.bindings" }; for (String id : dependencyId) { Bundle dependency = Platform.getBundle(id); IPluginImport iimport = model .getPluginFactory().createImport(); iimport.setId(id); Version version = dependency.getVersion(); String versionString = version.getMajor() + "." + version.getMinor() + "." + version.getMicro(); iimport.setVersion(versionString); pluginBase.add(iimport); } } @Override protected void setPluginLibraries( WorkspacePluginModelBase model) throws CoreException { this.model = model; super.setPluginLibraries(model); } }); IWorkingSet[] workingSets = fMainPage.getSelectedWorkingSets(); if (workingSets.length > 0) getWorkbench().getWorkingSetManager().addToWorkingSets( fProjectProvider.getProject(), workingSets); this.createProductsExtension(fProjectProvider.getProject()); this.createApplicationResources(fProjectProvider.getProject(), new NullProgressMonitor()); return true; } catch (InvocationTargetException e) { PDEPlugin.logException(e); } catch (InterruptedException e) { } return false; } /** * create products extension detail * * @param project */ @SuppressWarnings("restriction") public void createProductsExtension(IProject project) { Map<String, String> map = fApplicationPage.getData(); if (map == null || map.get(NewApplicationWizardPage.PRODUCT_NAME) == null) return; WorkspacePluginModelBase fmodel = new WorkspaceBundlePluginModel( project.getFile(ICoreConstants.BUNDLE_FILENAME_DESCRIPTOR), project.getFile(ICoreConstants.PLUGIN_FILENAME_DESCRIPTOR)); IPluginExtension extension = fmodel.getFactory().createExtension(); try { String productName = map.get(NewApplicationWizardPage.PRODUCT_NAME); String applicationName = map .get(NewApplicationWizardPage.APPLICATION); String xmiPath = map .get(NewApplicationWizardPage.APPLICATION_XMI_PROPERTY); if (xmiPath != null) { xmiPath = productName + "/" + xmiPath; map.put(NewApplicationWizardPage.APPLICATION_XMI_PROPERTY, xmiPath); } String cssValue = map .get(NewApplicationWizardPage.APPLICATION_CSS_PROPERTY); if (cssValue != null) { cssValue = "platform:/plugin/" + productName + "/" + cssValue; map.put(NewApplicationWizardPage.APPLICATION_CSS_PROPERTY, cssValue); } extension.setPoint("org.eclipse.core.runtime.products"); extension.setId("product"); IPluginElement productElement = fmodel.getFactory().createElement( extension); productElement.setName("product"); if (applicationName != null) { productElement.setAttribute("application", applicationName); } else { productElement.setAttribute("application", NewApplicationWizardPage.E4_APPLICATION); } productElement.setAttribute("name", productName); Set<Entry<String, String>> set = map.entrySet(); if (set != null) { Iterator<Entry<String, String>> it = set.iterator(); if (it != null) { while (it.hasNext()) { Entry<String, String> entry = it.next(); String value = entry.getValue(); if (value == null || value.trim().length() == 0) { continue; } if (entry.getKey().equals( NewApplicationWizardPage.PRODUCT_NAME) || entry.getKey().equals( NewApplicationWizardPage.APPLICATION)) { continue; } IPluginElement element = fmodel.getFactory() .createElement(productElement); element.setName("property"); element.setAttribute("name", entry.getKey()); element.setAttribute("value", value); productElement.add(element); } } } extension.add(productElement); fmodel.getPluginBase().add(extension); fmodel.save(); } catch (CoreException e) { PDEPlugin.logException(e); } } /** * create products extension detail * * @param project */ @SuppressWarnings("restriction") public void createApplicationResources(IProject project, IProgressMonitor monitor) { Map<String, String> map = fApplicationPage.getData(); if (map == null || map.get(NewApplicationWizardPage.PRODUCT_NAME) == null) return; String projectName = map.get(NewApplicationWizardPage.PRODUCT_NAME); String xmiPath = map .get(NewApplicationWizardPage.APPLICATION_XMI_PROPERTY); IJavaProject javaProject = JavaCore.create(project); IPackageFragment fragment = null; try { for (IPackageFragment element : javaProject.getPackageFragments()) { if (element.getKind() == IPackageFragmentRoot.K_SOURCE) { fragment = element; } } } catch (JavaModelException e1) { e1.printStackTrace(); } if (xmiPath != null && xmiPath.trim().length() > 0) { // Create a resource set // ResourceSet resourceSet = new ResourceSetImpl(); // Get the URI of the model file. // URI fileURI = URI.createPlatformResourceURI(project.getName() + "/" + xmiPath, true); // Create a resource for this file. // Resource resource = resourceSet.createResource(fileURI); MApplication application = MApplicationFactory.INSTANCE .createApplication(); application.setElementId("org.eclipse.e4.ide.application"); MBindingContext rootContext = MCommandsFactory.INSTANCE.createBindingContext(); rootContext.setElementId("org.eclipse.ui.contexts.dialogAndWindow"); rootContext.setName("In Dialog and Windows"); MBindingContext childContext = MCommandsFactory.INSTANCE.createBindingContext(); childContext.setElementId("org.eclipse.ui.contexts.window"); childContext.setName("In Windows"); rootContext.getChildren().add(childContext); childContext = MCommandsFactory.INSTANCE.createBindingContext(); childContext.setElementId("org.eclipse.ui.contexts.dialog"); childContext.setName("In Dialogs"); rootContext.getChildren().add(childContext); - application.setRootContext(rootContext); + application.getRootContext().add(rootContext); application.getBindingContexts().add("org.eclipse.ui.contexts.dialogAndWindow"); resource.getContents().add((EObject) application); // Create Quit command MCommand quitCommand = createCommand("quitCommand", "QuitHandler", "Ctrl+Q", projectName, fragment, application); MCommand openCommand = createCommand("openCommand", "OpenHandler", "Ctrl+O", projectName, fragment, application); MCommand saveCommand = createCommand("saveCommand", "SaveHandler", "Ctrl+S", projectName, fragment, application); MCommand aboutCommand = createCommand("aboutCommand", "AboutHandler", "Ctrl+A", projectName, fragment, application); MTrimmedWindow mainWindow = MBasicFactory.INSTANCE.createTrimmedWindow(); application.getChildren().add(mainWindow); { mainWindow.setLabel(projectName); mainWindow.setWidth(500); mainWindow.setHeight(400); // Menu { MMenu menu = MMenuFactory.INSTANCE.createMenu(); mainWindow.setMainMenu(menu); menu.setElementId("menu:org.eclipse.ui.main.menu"); MMenu fileMenuItem = MMenuFactory.INSTANCE .createMenu(); menu.getChildren().add(fileMenuItem); fileMenuItem.setLabel("File"); { MHandledMenuItem menuItemOpen = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemOpen); menuItemOpen.setLabel("Open"); menuItemOpen.setIconURI("platform:/plugin/" + project.getName() + "/icons/sample.gif"); menuItemOpen.setCommand(openCommand); MHandledMenuItem menuItemSave = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemSave); menuItemSave.setLabel("Save"); menuItemSave.setIconURI("platform:/plugin/" + project.getName() + "/icons/save_edit.gif"); menuItemSave.setCommand(saveCommand); MHandledMenuItem menuItemQuit = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemQuit); menuItemQuit.setLabel("Quit"); menuItemQuit.setCommand(quitCommand); } MMenu helpMenuItem = MMenuFactory.INSTANCE .createMenu(); menu.getChildren().add(helpMenuItem); helpMenuItem.setLabel("Help"); { MHandledMenuItem menuItemAbout = MMenuFactory.INSTANCE .createHandledMenuItem(); helpMenuItem.getChildren().add(menuItemAbout); menuItemAbout.setLabel("About"); menuItemAbout.setCommand(aboutCommand); } } // PerspectiveStack { MPerspectiveStack perspectiveStack = MAdvancedFactory.INSTANCE .createPerspectiveStack(); mainWindow.getChildren().add(perspectiveStack); MPerspective perspective = MAdvancedFactory.INSTANCE .createPerspective(); perspectiveStack.getChildren().add(perspective); { // Part Container MPartSashContainer partSashContainer = MBasicFactory.INSTANCE .createPartSashContainer(); perspective.getChildren().add(partSashContainer); MPartStack partStack = MBasicFactory.INSTANCE .createPartStack(); partSashContainer.getChildren().add(partStack); // // MPart part = MApplicationFactory.eINSTANCE.createPart(); // partStack.getChildren().add(part); // part.setLabel("Main"); } // WindowTrim { MTrimBar trimBar = MBasicFactory.INSTANCE.createTrimBar(); mainWindow.getTrimBars().add(trimBar); MToolBar toolBar = MMenuFactory.INSTANCE .createToolBar(); toolBar.setElementId("toolbar:org.eclipse.ui.main.toolbar"); trimBar.getChildren().add(toolBar); MHandledToolItem toolItemOpen = MMenuFactory.INSTANCE .createHandledToolItem(); toolBar.getChildren().add(toolItemOpen); toolItemOpen.setIconURI("platform:/plugin/" + project.getName() + "/icons/sample.gif"); toolItemOpen.setCommand(openCommand); MHandledToolItem toolItemSave = MMenuFactory.INSTANCE .createHandledToolItem(); toolBar.getChildren().add(toolItemSave); toolItemSave.setIconURI("platform:/plugin/" + project.getName() + "/icons/save_edit.gif"); toolItemSave.setCommand(saveCommand); } } } Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); try { resource.save(options); } catch (IOException e) { PDEPlugin.logException(e); } } String cssPath = map .get(NewApplicationWizardPage.APPLICATION_CSS_PROPERTY); if (cssPath != null && cssPath.trim().length() > 0) { IFile file = project.getFile(cssPath); try { prepareFolder(file.getParent(), monitor); URL corePath = ResourceLocator .getProjectTemplateFiles("css/default.css"); file.create(corePath.openStream(), true, monitor); } catch (Exception e) { PDEPlugin.logException(e); } } // IFolder folder = project.getFolder("icons"); // try { // folder.create(true, true, monitor); // Bundle bundle = Platform // .getBundle("org.eclipse.e4.tools.ui.designer"); // // for (String fileName : new String[] { "sample.gif", "save_edit.gif" // }) { // URL sampleUrl = bundle.getEntry("resources/icons/" + fileName); // sampleUrl = FileLocator.resolve(sampleUrl); // InputStream inputStream = sampleUrl.openStream(); // IFile file = folder.getFile(fileName); // file.create(inputStream, true, monitor); // } // } catch (Exception e) { // PDEPlugin.logException(e); // } String template_id = "common"; Set<String> binaryExtentions = new HashSet<String>(); binaryExtentions.add(".gif"); binaryExtentions.add(".png"); Map<String, String> keys = new HashMap<String, String>(); keys.put("projectName", projectName); keys.put("packageName", fragment.getElementName() + ".handlers"); try { URL corePath = ResourceLocator.getProjectTemplateFiles(template_id); IRunnableWithProgress op = new TemplateOperation(corePath, project, keys, binaryExtentions); getContainer().run(false, true, op); } catch (Exception e) { PDEPlugin.logException(e); } try { URL corePath = ResourceLocator.getProjectTemplateFiles("src"); IRunnableWithProgress op = new TemplateOperation(corePath, (IContainer) fragment.getResource(), keys, binaryExtentions); getContainer().run(false, true, op); } catch (Exception e) { PDEPlugin.logException(e); } } private MCommand createCommand(String name, String className, String keyBinding, String projectName, IPackageFragment fragment, MApplication application) { MCommand command = MCommandsFactory.INSTANCE.createCommand(); command.setCommandName(name); command.setElementId(projectName + "." + name); application.getCommands().add(command); { // Create Quit handler for command MHandler quitHandler =MCommandsFactory.INSTANCE .createHandler(); quitHandler.setCommand(command); quitHandler.setContributionURI("platform:/plugin/" + projectName + "/" + fragment.getElementName() + ".handlers." + className); application.getHandlers().add(quitHandler); MKeyBinding binding = MCommandsFactory.INSTANCE .createKeyBinding(); binding.setKeySequence(keyBinding); binding.setCommand(command); List<MBindingTable> tables = application.getBindingTables(); if (tables.size()==0) { MBindingTable table = MCommandsFactory.INSTANCE.createBindingTable(); table.setBindingContextId("org.eclipse.ui.contexts.dialogAndWindow"); tables.add(table); } tables.get(0).getBindings().add(binding); } return command; } private void prepareFolder(IContainer container, IProgressMonitor monitor) throws CoreException { IContainer parent = container.getParent(); if (parent instanceof IFolder) { prepareFolder((IFolder) parent, monitor); } if (!container.exists() && container instanceof IFolder) { IFolder folder = (IFolder) container; folder.create(true, true, monitor); } } public String getPluginId() { return fPluginData.getId(); } public String getPluginVersion() { return fPluginData.getVersion(); } }
true
true
public void createApplicationResources(IProject project, IProgressMonitor monitor) { Map<String, String> map = fApplicationPage.getData(); if (map == null || map.get(NewApplicationWizardPage.PRODUCT_NAME) == null) return; String projectName = map.get(NewApplicationWizardPage.PRODUCT_NAME); String xmiPath = map .get(NewApplicationWizardPage.APPLICATION_XMI_PROPERTY); IJavaProject javaProject = JavaCore.create(project); IPackageFragment fragment = null; try { for (IPackageFragment element : javaProject.getPackageFragments()) { if (element.getKind() == IPackageFragmentRoot.K_SOURCE) { fragment = element; } } } catch (JavaModelException e1) { e1.printStackTrace(); } if (xmiPath != null && xmiPath.trim().length() > 0) { // Create a resource set // ResourceSet resourceSet = new ResourceSetImpl(); // Get the URI of the model file. // URI fileURI = URI.createPlatformResourceURI(project.getName() + "/" + xmiPath, true); // Create a resource for this file. // Resource resource = resourceSet.createResource(fileURI); MApplication application = MApplicationFactory.INSTANCE .createApplication(); application.setElementId("org.eclipse.e4.ide.application"); MBindingContext rootContext = MCommandsFactory.INSTANCE.createBindingContext(); rootContext.setElementId("org.eclipse.ui.contexts.dialogAndWindow"); rootContext.setName("In Dialog and Windows"); MBindingContext childContext = MCommandsFactory.INSTANCE.createBindingContext(); childContext.setElementId("org.eclipse.ui.contexts.window"); childContext.setName("In Windows"); rootContext.getChildren().add(childContext); childContext = MCommandsFactory.INSTANCE.createBindingContext(); childContext.setElementId("org.eclipse.ui.contexts.dialog"); childContext.setName("In Dialogs"); rootContext.getChildren().add(childContext); application.setRootContext(rootContext); application.getBindingContexts().add("org.eclipse.ui.contexts.dialogAndWindow"); resource.getContents().add((EObject) application); // Create Quit command MCommand quitCommand = createCommand("quitCommand", "QuitHandler", "Ctrl+Q", projectName, fragment, application); MCommand openCommand = createCommand("openCommand", "OpenHandler", "Ctrl+O", projectName, fragment, application); MCommand saveCommand = createCommand("saveCommand", "SaveHandler", "Ctrl+S", projectName, fragment, application); MCommand aboutCommand = createCommand("aboutCommand", "AboutHandler", "Ctrl+A", projectName, fragment, application); MTrimmedWindow mainWindow = MBasicFactory.INSTANCE.createTrimmedWindow(); application.getChildren().add(mainWindow); { mainWindow.setLabel(projectName); mainWindow.setWidth(500); mainWindow.setHeight(400); // Menu { MMenu menu = MMenuFactory.INSTANCE.createMenu(); mainWindow.setMainMenu(menu); menu.setElementId("menu:org.eclipse.ui.main.menu"); MMenu fileMenuItem = MMenuFactory.INSTANCE .createMenu(); menu.getChildren().add(fileMenuItem); fileMenuItem.setLabel("File"); { MHandledMenuItem menuItemOpen = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemOpen); menuItemOpen.setLabel("Open"); menuItemOpen.setIconURI("platform:/plugin/" + project.getName() + "/icons/sample.gif"); menuItemOpen.setCommand(openCommand); MHandledMenuItem menuItemSave = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemSave); menuItemSave.setLabel("Save"); menuItemSave.setIconURI("platform:/plugin/" + project.getName() + "/icons/save_edit.gif"); menuItemSave.setCommand(saveCommand); MHandledMenuItem menuItemQuit = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemQuit); menuItemQuit.setLabel("Quit"); menuItemQuit.setCommand(quitCommand); } MMenu helpMenuItem = MMenuFactory.INSTANCE .createMenu(); menu.getChildren().add(helpMenuItem); helpMenuItem.setLabel("Help"); { MHandledMenuItem menuItemAbout = MMenuFactory.INSTANCE .createHandledMenuItem(); helpMenuItem.getChildren().add(menuItemAbout); menuItemAbout.setLabel("About"); menuItemAbout.setCommand(aboutCommand); } } // PerspectiveStack { MPerspectiveStack perspectiveStack = MAdvancedFactory.INSTANCE .createPerspectiveStack(); mainWindow.getChildren().add(perspectiveStack); MPerspective perspective = MAdvancedFactory.INSTANCE .createPerspective(); perspectiveStack.getChildren().add(perspective); { // Part Container MPartSashContainer partSashContainer = MBasicFactory.INSTANCE .createPartSashContainer(); perspective.getChildren().add(partSashContainer); MPartStack partStack = MBasicFactory.INSTANCE .createPartStack(); partSashContainer.getChildren().add(partStack); // // MPart part = MApplicationFactory.eINSTANCE.createPart(); // partStack.getChildren().add(part); // part.setLabel("Main"); } // WindowTrim { MTrimBar trimBar = MBasicFactory.INSTANCE.createTrimBar(); mainWindow.getTrimBars().add(trimBar); MToolBar toolBar = MMenuFactory.INSTANCE .createToolBar(); toolBar.setElementId("toolbar:org.eclipse.ui.main.toolbar"); trimBar.getChildren().add(toolBar); MHandledToolItem toolItemOpen = MMenuFactory.INSTANCE .createHandledToolItem(); toolBar.getChildren().add(toolItemOpen); toolItemOpen.setIconURI("platform:/plugin/" + project.getName() + "/icons/sample.gif"); toolItemOpen.setCommand(openCommand); MHandledToolItem toolItemSave = MMenuFactory.INSTANCE .createHandledToolItem(); toolBar.getChildren().add(toolItemSave); toolItemSave.setIconURI("platform:/plugin/" + project.getName() + "/icons/save_edit.gif"); toolItemSave.setCommand(saveCommand); } } } Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); try { resource.save(options); } catch (IOException e) { PDEPlugin.logException(e); } } String cssPath = map .get(NewApplicationWizardPage.APPLICATION_CSS_PROPERTY); if (cssPath != null && cssPath.trim().length() > 0) { IFile file = project.getFile(cssPath); try { prepareFolder(file.getParent(), monitor); URL corePath = ResourceLocator .getProjectTemplateFiles("css/default.css"); file.create(corePath.openStream(), true, monitor); } catch (Exception e) { PDEPlugin.logException(e); } } // IFolder folder = project.getFolder("icons"); // try { // folder.create(true, true, monitor); // Bundle bundle = Platform // .getBundle("org.eclipse.e4.tools.ui.designer"); // // for (String fileName : new String[] { "sample.gif", "save_edit.gif" // }) { // URL sampleUrl = bundle.getEntry("resources/icons/" + fileName); // sampleUrl = FileLocator.resolve(sampleUrl); // InputStream inputStream = sampleUrl.openStream(); // IFile file = folder.getFile(fileName); // file.create(inputStream, true, monitor); // } // } catch (Exception e) { // PDEPlugin.logException(e); // } String template_id = "common"; Set<String> binaryExtentions = new HashSet<String>(); binaryExtentions.add(".gif"); binaryExtentions.add(".png"); Map<String, String> keys = new HashMap<String, String>(); keys.put("projectName", projectName); keys.put("packageName", fragment.getElementName() + ".handlers"); try { URL corePath = ResourceLocator.getProjectTemplateFiles(template_id); IRunnableWithProgress op = new TemplateOperation(corePath, project, keys, binaryExtentions); getContainer().run(false, true, op); } catch (Exception e) { PDEPlugin.logException(e); } try { URL corePath = ResourceLocator.getProjectTemplateFiles("src"); IRunnableWithProgress op = new TemplateOperation(corePath, (IContainer) fragment.getResource(), keys, binaryExtentions); getContainer().run(false, true, op); } catch (Exception e) { PDEPlugin.logException(e); } }
public void createApplicationResources(IProject project, IProgressMonitor monitor) { Map<String, String> map = fApplicationPage.getData(); if (map == null || map.get(NewApplicationWizardPage.PRODUCT_NAME) == null) return; String projectName = map.get(NewApplicationWizardPage.PRODUCT_NAME); String xmiPath = map .get(NewApplicationWizardPage.APPLICATION_XMI_PROPERTY); IJavaProject javaProject = JavaCore.create(project); IPackageFragment fragment = null; try { for (IPackageFragment element : javaProject.getPackageFragments()) { if (element.getKind() == IPackageFragmentRoot.K_SOURCE) { fragment = element; } } } catch (JavaModelException e1) { e1.printStackTrace(); } if (xmiPath != null && xmiPath.trim().length() > 0) { // Create a resource set // ResourceSet resourceSet = new ResourceSetImpl(); // Get the URI of the model file. // URI fileURI = URI.createPlatformResourceURI(project.getName() + "/" + xmiPath, true); // Create a resource for this file. // Resource resource = resourceSet.createResource(fileURI); MApplication application = MApplicationFactory.INSTANCE .createApplication(); application.setElementId("org.eclipse.e4.ide.application"); MBindingContext rootContext = MCommandsFactory.INSTANCE.createBindingContext(); rootContext.setElementId("org.eclipse.ui.contexts.dialogAndWindow"); rootContext.setName("In Dialog and Windows"); MBindingContext childContext = MCommandsFactory.INSTANCE.createBindingContext(); childContext.setElementId("org.eclipse.ui.contexts.window"); childContext.setName("In Windows"); rootContext.getChildren().add(childContext); childContext = MCommandsFactory.INSTANCE.createBindingContext(); childContext.setElementId("org.eclipse.ui.contexts.dialog"); childContext.setName("In Dialogs"); rootContext.getChildren().add(childContext); application.getRootContext().add(rootContext); application.getBindingContexts().add("org.eclipse.ui.contexts.dialogAndWindow"); resource.getContents().add((EObject) application); // Create Quit command MCommand quitCommand = createCommand("quitCommand", "QuitHandler", "Ctrl+Q", projectName, fragment, application); MCommand openCommand = createCommand("openCommand", "OpenHandler", "Ctrl+O", projectName, fragment, application); MCommand saveCommand = createCommand("saveCommand", "SaveHandler", "Ctrl+S", projectName, fragment, application); MCommand aboutCommand = createCommand("aboutCommand", "AboutHandler", "Ctrl+A", projectName, fragment, application); MTrimmedWindow mainWindow = MBasicFactory.INSTANCE.createTrimmedWindow(); application.getChildren().add(mainWindow); { mainWindow.setLabel(projectName); mainWindow.setWidth(500); mainWindow.setHeight(400); // Menu { MMenu menu = MMenuFactory.INSTANCE.createMenu(); mainWindow.setMainMenu(menu); menu.setElementId("menu:org.eclipse.ui.main.menu"); MMenu fileMenuItem = MMenuFactory.INSTANCE .createMenu(); menu.getChildren().add(fileMenuItem); fileMenuItem.setLabel("File"); { MHandledMenuItem menuItemOpen = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemOpen); menuItemOpen.setLabel("Open"); menuItemOpen.setIconURI("platform:/plugin/" + project.getName() + "/icons/sample.gif"); menuItemOpen.setCommand(openCommand); MHandledMenuItem menuItemSave = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemSave); menuItemSave.setLabel("Save"); menuItemSave.setIconURI("platform:/plugin/" + project.getName() + "/icons/save_edit.gif"); menuItemSave.setCommand(saveCommand); MHandledMenuItem menuItemQuit = MMenuFactory.INSTANCE .createHandledMenuItem(); fileMenuItem.getChildren().add(menuItemQuit); menuItemQuit.setLabel("Quit"); menuItemQuit.setCommand(quitCommand); } MMenu helpMenuItem = MMenuFactory.INSTANCE .createMenu(); menu.getChildren().add(helpMenuItem); helpMenuItem.setLabel("Help"); { MHandledMenuItem menuItemAbout = MMenuFactory.INSTANCE .createHandledMenuItem(); helpMenuItem.getChildren().add(menuItemAbout); menuItemAbout.setLabel("About"); menuItemAbout.setCommand(aboutCommand); } } // PerspectiveStack { MPerspectiveStack perspectiveStack = MAdvancedFactory.INSTANCE .createPerspectiveStack(); mainWindow.getChildren().add(perspectiveStack); MPerspective perspective = MAdvancedFactory.INSTANCE .createPerspective(); perspectiveStack.getChildren().add(perspective); { // Part Container MPartSashContainer partSashContainer = MBasicFactory.INSTANCE .createPartSashContainer(); perspective.getChildren().add(partSashContainer); MPartStack partStack = MBasicFactory.INSTANCE .createPartStack(); partSashContainer.getChildren().add(partStack); // // MPart part = MApplicationFactory.eINSTANCE.createPart(); // partStack.getChildren().add(part); // part.setLabel("Main"); } // WindowTrim { MTrimBar trimBar = MBasicFactory.INSTANCE.createTrimBar(); mainWindow.getTrimBars().add(trimBar); MToolBar toolBar = MMenuFactory.INSTANCE .createToolBar(); toolBar.setElementId("toolbar:org.eclipse.ui.main.toolbar"); trimBar.getChildren().add(toolBar); MHandledToolItem toolItemOpen = MMenuFactory.INSTANCE .createHandledToolItem(); toolBar.getChildren().add(toolItemOpen); toolItemOpen.setIconURI("platform:/plugin/" + project.getName() + "/icons/sample.gif"); toolItemOpen.setCommand(openCommand); MHandledToolItem toolItemSave = MMenuFactory.INSTANCE .createHandledToolItem(); toolBar.getChildren().add(toolItemSave); toolItemSave.setIconURI("platform:/plugin/" + project.getName() + "/icons/save_edit.gif"); toolItemSave.setCommand(saveCommand); } } } Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); try { resource.save(options); } catch (IOException e) { PDEPlugin.logException(e); } } String cssPath = map .get(NewApplicationWizardPage.APPLICATION_CSS_PROPERTY); if (cssPath != null && cssPath.trim().length() > 0) { IFile file = project.getFile(cssPath); try { prepareFolder(file.getParent(), monitor); URL corePath = ResourceLocator .getProjectTemplateFiles("css/default.css"); file.create(corePath.openStream(), true, monitor); } catch (Exception e) { PDEPlugin.logException(e); } } // IFolder folder = project.getFolder("icons"); // try { // folder.create(true, true, monitor); // Bundle bundle = Platform // .getBundle("org.eclipse.e4.tools.ui.designer"); // // for (String fileName : new String[] { "sample.gif", "save_edit.gif" // }) { // URL sampleUrl = bundle.getEntry("resources/icons/" + fileName); // sampleUrl = FileLocator.resolve(sampleUrl); // InputStream inputStream = sampleUrl.openStream(); // IFile file = folder.getFile(fileName); // file.create(inputStream, true, monitor); // } // } catch (Exception e) { // PDEPlugin.logException(e); // } String template_id = "common"; Set<String> binaryExtentions = new HashSet<String>(); binaryExtentions.add(".gif"); binaryExtentions.add(".png"); Map<String, String> keys = new HashMap<String, String>(); keys.put("projectName", projectName); keys.put("packageName", fragment.getElementName() + ".handlers"); try { URL corePath = ResourceLocator.getProjectTemplateFiles(template_id); IRunnableWithProgress op = new TemplateOperation(corePath, project, keys, binaryExtentions); getContainer().run(false, true, op); } catch (Exception e) { PDEPlugin.logException(e); } try { URL corePath = ResourceLocator.getProjectTemplateFiles("src"); IRunnableWithProgress op = new TemplateOperation(corePath, (IContainer) fragment.getResource(), keys, binaryExtentions); getContainer().run(false, true, op); } catch (Exception e) { PDEPlugin.logException(e); } }
diff --git a/src/pl/xsolve/verfluchter/tools/AutoSettingsImpl.java b/src/pl/xsolve/verfluchter/tools/AutoSettingsImpl.java index b853874..ef33ec2 100644 --- a/src/pl/xsolve/verfluchter/tools/AutoSettingsImpl.java +++ b/src/pl/xsolve/verfluchter/tools/AutoSettingsImpl.java @@ -1,155 +1,155 @@ /* * This file is part of verfluchter-android. * * verfluchter-android is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * verfluchter-android is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ package pl.xsolve.verfluchter.tools; import android.app.Activity; import android.content.SharedPreferences; import android.util.Log; import com.google.inject.Inject; import java.util.HashMap; import java.util.Map; /** * @author Konrad Ktoso Malawski */ public class AutoSettingsImpl extends Activity implements AutoSettings { // Logger tag private static final String TAG = AutoSettingsImpl.class.getSimpleName(); // My instance, "the one to rule them all" // private static AutoSettings myInstance; protected SharedPreferences preferences; protected PasswdUtil passwdUtil; protected Map<String, Object> settings = new HashMap<String, Object>(); protected static final String INT_SUFFIX = "_I"; protected static final String FLOAT_SUFFIX = "_F"; protected static final String STRING_SUFFIX = "_S"; protected static final String BOOLEAN_SUFFIX = "_B"; protected static final String LONG_SUFFIX = "_L"; @Inject - private AutoSettingsImpl(SharedPreferences preferences, PasswdUtil passwdUtil) { + public AutoSettingsImpl(SharedPreferences preferences, PasswdUtil passwdUtil) { this.preferences = preferences; this.passwdUtil = passwdUtil; //default values and automatic setting+loading setup settings.put(SERVER_DOMAIN_S, Constants.DEFAULT.SERVER_DOMAIN); settings.put(MY_AUTH_USER_S, null); settings.put(MY_AUTH_PASS_S, null); settings.put(BASIC_AUTH_USER_S, Constants.DEFAULT.BASIC_AUTH_USER); settings.put(BASIC_AUTH_PASS_S, Constants.DEFAULT.BASIC_AUTH_PASS); settings.put(USE_REMINDER_SERVICE_B, Constants.DEFAULT.USE_REMINDER_SERVICE); settings.put(USE_REFRESHER_SERVICE_B, Constants.DEFAULT.USE_REFRESHER_SERVICE); settings.put(WORKING_HOURS_START_HOUR_I, Constants.DEFAULT.WORKING_HOURS_START_HOUR); settings.put(WORKING_HOURS_START_MIN_I, Constants.DEFAULT.WORKING_HOURS_START_MIN); settings.put(WORKING_HOURS_END_HOUR_I, Constants.DEFAULT.WORKING_HOURS_END_HOUR); settings.put(WORKING_HOURS_END_MIN_I, Constants.DEFAULT.WORKING_HOURS_END_MIN); settings.put(USE_SOUND_B, Constants.DEFAULT.USE_SOUND); restoreSettings(); } /** * Restore preferences and load them into our variables */ @Override public void restoreSettings() { for (String key : settings.keySet()) { Object value = restoreFromPreferences(preferences, key); // if (key.contains("PASS") && value != null) { // value = passwdUtil.decrypt((String) value); // } if (value != null) { settings.put(key, value); } } } /** * Persist our cache into persistent SharedPreferences */ @Override public void persistSettings() { Log.d(TAG, "Persisting autoSettings: " + settings); // We need an Editor object to make preference changes. SharedPreferences.Editor editor = preferences.edit(); for (String key : settings.keySet()) { Object value = getSetting(key, Object.class); // if (key.contains("PASS") && value != null) { // value = passwdUtil.encrypt((String) value); // } persistIntoPreferencesEditor(editor, key, value); } editor.commit(); // Commit the edits! } private Object restoreFromPreferences(SharedPreferences preferences, String key) { if (key.endsWith(STRING_SUFFIX)) { return preferences.getString(key, null); } else if (key.endsWith(BOOLEAN_SUFFIX)) { return preferences.getBoolean(key, false); } else if (key.endsWith(INT_SUFFIX)) { return preferences.getInt(key, 0); } else if (key.endsWith(FLOAT_SUFFIX)) { return preferences.getFloat(key, 0); } else if (key.endsWith(LONG_SUFFIX)) { return preferences.getLong(key, 0); } return null; } private void persistIntoPreferencesEditor(SharedPreferences.Editor editor, String key, Object value) { if (key.endsWith(STRING_SUFFIX) || value == null) { editor.putString(key, (String) value); } else if (key.endsWith(BOOLEAN_SUFFIX)) { editor.putBoolean(key, (Boolean) value); } else if (key.endsWith(INT_SUFFIX)) { editor.putInt(key, (Integer) value); } else if (key.endsWith(FLOAT_SUFFIX)) { editor.putFloat(key, (Float) value); } else if (key.endsWith(LONG_SUFFIX)) { editor.putLong(key, (Long) value); } } @Override @SuppressWarnings("unchecked") public <T> T getSetting(String key, Class<T> clazz) { return (T) settings.get(key); } @Override public <T> void setSetting(String key, T value) { settings.put(key, value); } @Override public String print() { StringBuilder sb = new StringBuilder("-- AutoSettings (" + this + ") --\n"); sb.append(settings).append("\n"); return sb.append("------------------").toString(); } }
true
true
private AutoSettingsImpl(SharedPreferences preferences, PasswdUtil passwdUtil) { this.preferences = preferences; this.passwdUtil = passwdUtil; //default values and automatic setting+loading setup settings.put(SERVER_DOMAIN_S, Constants.DEFAULT.SERVER_DOMAIN); settings.put(MY_AUTH_USER_S, null); settings.put(MY_AUTH_PASS_S, null); settings.put(BASIC_AUTH_USER_S, Constants.DEFAULT.BASIC_AUTH_USER); settings.put(BASIC_AUTH_PASS_S, Constants.DEFAULT.BASIC_AUTH_PASS); settings.put(USE_REMINDER_SERVICE_B, Constants.DEFAULT.USE_REMINDER_SERVICE); settings.put(USE_REFRESHER_SERVICE_B, Constants.DEFAULT.USE_REFRESHER_SERVICE); settings.put(WORKING_HOURS_START_HOUR_I, Constants.DEFAULT.WORKING_HOURS_START_HOUR); settings.put(WORKING_HOURS_START_MIN_I, Constants.DEFAULT.WORKING_HOURS_START_MIN); settings.put(WORKING_HOURS_END_HOUR_I, Constants.DEFAULT.WORKING_HOURS_END_HOUR); settings.put(WORKING_HOURS_END_MIN_I, Constants.DEFAULT.WORKING_HOURS_END_MIN); settings.put(USE_SOUND_B, Constants.DEFAULT.USE_SOUND); restoreSettings(); }
public AutoSettingsImpl(SharedPreferences preferences, PasswdUtil passwdUtil) { this.preferences = preferences; this.passwdUtil = passwdUtil; //default values and automatic setting+loading setup settings.put(SERVER_DOMAIN_S, Constants.DEFAULT.SERVER_DOMAIN); settings.put(MY_AUTH_USER_S, null); settings.put(MY_AUTH_PASS_S, null); settings.put(BASIC_AUTH_USER_S, Constants.DEFAULT.BASIC_AUTH_USER); settings.put(BASIC_AUTH_PASS_S, Constants.DEFAULT.BASIC_AUTH_PASS); settings.put(USE_REMINDER_SERVICE_B, Constants.DEFAULT.USE_REMINDER_SERVICE); settings.put(USE_REFRESHER_SERVICE_B, Constants.DEFAULT.USE_REFRESHER_SERVICE); settings.put(WORKING_HOURS_START_HOUR_I, Constants.DEFAULT.WORKING_HOURS_START_HOUR); settings.put(WORKING_HOURS_START_MIN_I, Constants.DEFAULT.WORKING_HOURS_START_MIN); settings.put(WORKING_HOURS_END_HOUR_I, Constants.DEFAULT.WORKING_HOURS_END_HOUR); settings.put(WORKING_HOURS_END_MIN_I, Constants.DEFAULT.WORKING_HOURS_END_MIN); settings.put(USE_SOUND_B, Constants.DEFAULT.USE_SOUND); restoreSettings(); }
diff --git a/src/biz/bokhorst/xprivacy/PrivacyService.java b/src/biz/bokhorst/xprivacy/PrivacyService.java index 189fd597..22e78e75 100644 --- a/src/biz/bokhorst/xprivacy/PrivacyService.java +++ b/src/biz/bokhorst/xprivacy/PrivacyService.java @@ -1,2174 +1,2178 @@ package biz.bokhorst.xprivacy; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteStatement; import android.os.Binder; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Process; import android.os.RemoteException; import android.os.StrictMode; import android.os.StrictMode.ThreadPolicy; import android.text.TextUtils; import android.util.Log; import android.util.Patterns; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; public class PrivacyService { private static int mXUid = -1; private static boolean mRegistered = false; private static boolean mUseCache = false; private static String mSecret = null; private static Thread mWorker = null; private static Handler mHandler = null; private static Semaphore mOndemandSemaphore = new Semaphore(1, true); private static List<String> mListError = new ArrayList<String>(); private static IPrivacyService mClient = null; private static final String cTableRestriction = "restriction"; private static final String cTableUsage = "usage"; private static final String cTableSetting = "setting"; private static final int cCurrentVersion = 306; private static final String cServiceName = "xprivacy305"; // TODO: define column names // sqlite3 /data/system/xprivacy/xprivacy.db public static void register(List<String> listError, String secret) { // Store secret and errors mSecret = secret; mListError.addAll(listError); try { // Register privacy service // @formatter:off // public static void addService(String name, IBinder service) // public static void addService(String name, IBinder service, boolean allowIsolated) // @formatter:on Class<?> cServiceManager = Class.forName("android.os.ServiceManager"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class, boolean.class); mAddService.invoke(null, cServiceName, mPrivacyService, true); } else { Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class); mAddService.invoke(null, cServiceName, mPrivacyService); } // This will and should open the database mRegistered = true; Util.log(null, Log.WARN, "Service registered name=" + cServiceName); // Publish semaphore to activity manager service XActivityManagerService.setSemaphore(mOndemandSemaphore); // Get memory class to enable/disable caching // http://stackoverflow.com/questions/2630158/detect-application-heap-size-in-android int memoryClass = (int) (Runtime.getRuntime().maxMemory() / 1024L / 1024L); mUseCache = (memoryClass >= 32); Util.log(null, Log.WARN, "Memory class=" + memoryClass + " cache=" + mUseCache); // Start a worker thread mWorker = new Thread(new Runnable() { @Override public void run() { try { Looper.prepare(); mHandler = new Handler(); Looper.loop(); } catch (Throwable ex) { Util.bug(null, ex); } } }); mWorker.start(); } catch (Throwable ex) { Util.bug(null, ex); } } public static boolean isRegistered() { return mRegistered; } public static boolean checkClient() { // Runs client side try { IPrivacyService client = getClient(); if (client != null) return (client.getVersion() == cCurrentVersion); } catch (RemoteException ex) { Util.bug(null, ex); } return false; } public static IPrivacyService getClient() { // Runs client side if (mClient == null) try { // public static IBinder getService(String name) Class<?> cServiceManager = Class.forName("android.os.ServiceManager"); Method mGetService = cServiceManager.getDeclaredMethod("getService", String.class); mClient = IPrivacyService.Stub.asInterface((IBinder) mGetService.invoke(null, cServiceName)); } catch (Throwable ex) { Util.bug(null, ex); } // Disable disk/network strict mode // TODO: hook setThreadPolicy try { ThreadPolicy oldPolicy = StrictMode.getThreadPolicy(); ThreadPolicy newpolicy = new ThreadPolicy.Builder(oldPolicy).permitDiskReads().permitDiskWrites() .permitNetwork().build(); StrictMode.setThreadPolicy(newpolicy); } catch (Throwable ex) { Util.bug(null, ex); } return mClient; } public static void reportErrorInternal(String message) { synchronized (mListError) { mListError.add(message); } } public static PRestriction getRestriction(final PRestriction restriction, boolean usage, String secret) throws RemoteException { if (isRegistered()) return mPrivacyService.getRestriction(restriction, usage, secret); else { IPrivacyService client = getClient(); if (client == null) { Log.w("XPrivacy", "No client for " + restriction); Log.w("XPrivacy", Log.getStackTraceString(new Exception("StackTrace"))); PRestriction result = new PRestriction(restriction); result.restricted = false; return result; } else return client.getRestriction(restriction, usage, secret); } } public static PSetting getSetting(PSetting setting) throws RemoteException { if (isRegistered()) return mPrivacyService.getSetting(setting); else { IPrivacyService client = getClient(); if (client == null) { Log.w("XPrivacy", "No client for " + setting + " uid=" + Process.myUid() + " pid=" + Process.myPid()); Log.w("XPrivacy", Log.getStackTraceString(new Exception("StackTrace"))); return setting; } else return client.getSetting(setting); } } private static final IPrivacyService.Stub mPrivacyService = new IPrivacyService.Stub() { private SQLiteDatabase mDb = null; private SQLiteDatabase mDbUsage = null; private SQLiteStatement stmtGetRestriction = null; private SQLiteStatement stmtGetSetting = null; private SQLiteStatement stmtGetUsageRestriction = null; private SQLiteStatement stmtGetUsageMethod = null; private ReentrantReadWriteLock mLock = new ReentrantReadWriteLock(true); private ReentrantReadWriteLock mLockUsage = new ReentrantReadWriteLock(true); private boolean mSelectCategory = true; private boolean mSelectOnce = false; private Map<CSetting, CSetting> mSettingCache = new HashMap<CSetting, CSetting>(); private Map<CRestriction, CRestriction> mAskedOnceCache = new HashMap<CRestriction, CRestriction>(); private Map<CRestriction, CRestriction> mRestrictionCache = new HashMap<CRestriction, CRestriction>(); private final int cMaxUsageData = 500; // entries private final int cMaxOnDemandDialog = 20; // seconds private ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory()); final class PriorityThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } } // Management @Override public int getVersion() throws RemoteException { return cCurrentVersion; } @Override public List<String> check() throws RemoteException { enforcePermission(); List<String> listError = new ArrayList<String>(); synchronized (mListError) { int c = 0; int i = 0; while (i < mListError.size()) { String msg = mListError.get(i); c += msg.length(); if (c < 5000) listError.add(msg); else break; i++; } } File dbFile = getDbFile(); if (!dbFile.exists()) listError.add("Database does not exists"); if (!dbFile.canRead()) listError.add("Database not readable"); if (!dbFile.canWrite()) listError.add("Database not writable"); SQLiteDatabase db = getDb(); if (db == null) listError.add("Database not available"); else if (!db.isOpen()) listError.add("Database not open"); return listError; } @Override public void reportError(String message) throws RemoteException { reportErrorInternal(message); } // Restrictions @Override public void setRestriction(PRestriction restriction) throws RemoteException { try { enforcePermission(); setRestrictionInternal(restriction); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setRestrictionInternal(PRestriction restriction) throws RemoteException { // Validate if (restriction.restrictionName == null) { Util.log(null, Log.ERROR, "Set invalid restriction " + restriction); Util.logStack(null, Log.ERROR); throw new RemoteException("Invalid restriction"); } try { SQLiteDatabase db = getDb(); if (db == null) return; // 0 not restricted, ask // 1 restricted, ask // 2 not restricted, asked // 3 restricted, asked mLock.writeLock().lock(); db.beginTransaction(); try { // Create category record if (restriction.methodName == null) { ContentValues cvalues = new ContentValues(); cvalues.put("uid", restriction.uid); cvalues.put("restriction", restriction.restrictionName); cvalues.put("method", ""); cvalues.put("restricted", (restriction.restricted ? 1 : 0) + (restriction.asked ? 2 : 0)); db.insertWithOnConflict(cTableRestriction, null, cvalues, SQLiteDatabase.CONFLICT_REPLACE); } // Create method exception record if (restriction.methodName != null) { ContentValues mvalues = new ContentValues(); mvalues.put("uid", restriction.uid); mvalues.put("restriction", restriction.restrictionName); mvalues.put("method", restriction.methodName); mvalues.put("restricted", (restriction.restricted ? 0 : 1) + (restriction.asked ? 2 : 0)); db.insertWithOnConflict(cTableRestriction, null, mvalues, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) synchronized (mRestrictionCache) { if (restriction.methodName == null || restriction.extra == null) for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) mRestrictionCache.remove(key); CRestriction key = new CRestriction(restriction, restriction.extra); if (mRestrictionCache.containsKey(key)) mRestrictionCache.remove(key); mRestrictionCache.put(key, key); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setRestrictionList(List<PRestriction> listRestriction) throws RemoteException { enforcePermission(); for (PRestriction restriction : listRestriction) setRestrictionInternal(restriction); } @Override public PRestriction getRestriction(final PRestriction restriction, boolean usage, String secret) throws RemoteException { long start = System.currentTimeMillis(); boolean cached = false; final PRestriction mresult = new PRestriction(restriction); try { // No permissions enforced, but usage data requires a secret // Sanity checks if (restriction.restrictionName == null) { Util.log(null, Log.ERROR, "Get invalid restriction " + restriction); return mresult; } if (usage && restriction.methodName == null) { Util.log(null, Log.ERROR, "Get invalid restriction " + restriction); return mresult; } // Check for self if (Util.getAppId(restriction.uid) == getXUid()) { if (PrivacyManager.cIdentification.equals(restriction.restrictionName) && "getString".equals(restriction.methodName)) { mresult.asked = true; return mresult; } if (PrivacyManager.cIPC.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } else if (PrivacyManager.cStorage.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } else if (PrivacyManager.cSystem.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } else if (PrivacyManager.cView.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } } // Get meta data Hook hook = null; if (restriction.methodName != null) { hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName); if (hook == null) // Can happen after replacing apk Util.log(null, Log.WARN, "Hook not found in service: " + restriction); } // Check for system component if (usage && !PrivacyManager.isApplication(restriction.uid)) if (!getSettingBool(0, PrivacyManager.cSettingSystem, false)) return mresult; // Check if restrictions enabled if (usage && !getSettingBool(restriction.uid, PrivacyManager.cSettingRestricted, true)) return mresult; // Check cache if (mUseCache) { CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) { cached = true; CRestriction cache = mRestrictionCache.get(key); mresult.restricted = cache.restricted; mresult.asked = cache.asked; } } } if (!cached) { PRestriction cresult = new PRestriction(restriction.uid, restriction.restrictionName, null); boolean methodFound = false; // No permissions required SQLiteDatabase db = getDb(); if (db == null) return mresult; // Precompile statement when needed if (stmtGetRestriction == null) { String sql = "SELECT restricted FROM " + cTableRestriction + " WHERE uid=? AND restriction=? AND method=?"; stmtGetRestriction = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetRestriction) { stmtGetRestriction.clearBindings(); stmtGetRestriction.bindLong(1, restriction.uid); stmtGetRestriction.bindString(2, restriction.restrictionName); stmtGetRestriction.bindString(3, ""); long state = stmtGetRestriction.simpleQueryForLong(); cresult.restricted = ((state & 1) != 0); cresult.asked = ((state & 2) != 0); mresult.restricted = cresult.restricted; mresult.asked = cresult.asked; } } catch (SQLiteDoneException ignored) { } if (restriction.methodName != null) try { synchronized (stmtGetRestriction) { stmtGetRestriction.clearBindings(); stmtGetRestriction.bindLong(1, restriction.uid); stmtGetRestriction.bindString(2, restriction.restrictionName); stmtGetRestriction.bindString(3, restriction.methodName); long state = stmtGetRestriction.simpleQueryForLong(); // Method can be excepted if (mresult.restricted) mresult.restricted = ((state & 1) == 0); // Category asked=true takes precedence if (!mresult.asked) mresult.asked = ((state & 2) != 0); methodFound = true; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Default dangerous if (!methodFound && hook != null && hook.isDangerous()) if (!getSettingBool(0, PrivacyManager.cSettingDangerous, false)) { mresult.restricted = false; mresult.asked = true; } // Check whitelist if (usage && hook != null && hook.whitelist() != null && restriction.extra != null) { String value = getSetting(new PSetting(restriction.uid, hook.whitelist(), restriction.extra, null)).value; if (value == null) { String xextra = getXExtra(restriction, hook); if (xextra != null) value = getSetting(new PSetting(restriction.uid, hook.whitelist(), xextra, null)).value; } if (value != null) { // true means allow, false means block mresult.restricted = !Boolean.parseBoolean(value); mresult.asked = true; } } // Fallback if (!mresult.restricted && usage && PrivacyManager.isApplication(restriction.uid) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (hook != null && !hook.isDangerous()) { mresult.restricted = PrivacyProvider.getRestrictedFallback(null, restriction.uid, restriction.restrictionName, restriction.methodName); Util.log(null, Log.WARN, "Fallback " + mresult); } } // Update cache if (mUseCache) { CRestriction key = new CRestriction(mresult, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) mRestrictionCache.remove(key); mRestrictionCache.put(key, key); } } } // Ask to restrict boolean ondemand = false; if (!mresult.asked && usage && PrivacyManager.isApplication(restriction.uid)) ondemand = onDemandDialog(hook, restriction, mresult); // Notify user if (!ondemand && mresult.restricted && usage && hook != null && hook.shouldNotify()) notifyRestricted(restriction); // Store usage data if (usage && hook != null && hook.hasUsageData()) storeUsageData(restriction, secret, mresult); } catch (Throwable ex) { Util.bug(null, ex); } long ms = System.currentTimeMillis() - start; Util.log(null, Log.INFO, String.format("get service %s%s %d ms", restriction, (cached ? " (cached)" : ""), ms)); return mresult; } private void storeUsageData(final PRestriction restriction, String secret, final PRestriction mresult) throws RemoteException { // Check if enabled if (getSettingBool(0, PrivacyManager.cSettingUsage, true)) { // Check secret boolean allowed = true; if (Util.getAppId(Binder.getCallingUid()) != getXUid()) { if (mSecret == null || !mSecret.equals(secret)) { allowed = false; Util.log(null, Log.WARN, "Invalid secret"); } } if (allowed) { mExecutor.execute(new Runnable() { public void run() { try { if (XActivityManagerService.canWriteUsageData()) { SQLiteDatabase dbUsage = getDbUsage(); if (dbUsage == null) return; String extra = ""; if (restriction.extra != null) if (getSettingBool(0, PrivacyManager.cSettingParameters, false)) extra = restriction.extra; mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", restriction.uid); values.put("restriction", restriction.restrictionName); values.put("method", restriction.methodName); values.put("restricted", mresult.restricted); values.put("time", new Date().getTime()); values.put("extra", extra); dbUsage.insertWithOnConflict(cTableUsage, null, values, SQLiteDatabase.CONFLICT_REPLACE); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } } catch (Throwable ex) { Util.bug(null, ex); } } }); } } } @Override public List<PRestriction> getRestrictionList(PRestriction selector) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); PRestriction query; if (selector.restrictionName == null) for (String sRestrictionName : PrivacyManager.getRestrictions()) { PRestriction restriction = new PRestriction(selector.uid, sRestrictionName, null, false); query = getRestriction(restriction, false, null); restriction.restricted = query.restricted; restriction.asked = query.asked; result.add(restriction); } else for (Hook md : PrivacyManager.getHooks(selector.restrictionName)) { PRestriction restriction = new PRestriction(selector.uid, selector.restrictionName, md.getName(), false); query = getRestriction(restriction, false, null); restriction.restricted = query.restricted; restriction.asked = query.asked; result.add(restriction); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteRestrictions(int uid, String restrictionName) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if ("".equals(restrictionName)) db.delete(cTableRestriction, "uid=?", new String[] { Integer.toString(uid) }); else db.delete(cTableRestriction, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }); Util.log(null, Log.WARN, "Restrictions deleted uid=" + uid + " category=" + restrictionName); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Usage @Override public long getUsage(List<PRestriction> listRestriction) throws RemoteException { long lastUsage = 0; try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); // Precompile statement when needed if (stmtGetUsageRestriction == null) { String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=?"; stmtGetUsageRestriction = dbUsage.compileStatement(sql); } if (stmtGetUsageMethod == null) { String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=? AND method=?"; stmtGetUsageMethod = dbUsage.compileStatement(sql); } mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { for (PRestriction restriction : listRestriction) { if (restriction.methodName == null) try { synchronized (stmtGetUsageRestriction) { stmtGetUsageRestriction.clearBindings(); stmtGetUsageRestriction.bindLong(1, restriction.uid); stmtGetUsageRestriction.bindString(2, restriction.restrictionName); lastUsage = Math.max(lastUsage, stmtGetUsageRestriction.simpleQueryForLong()); } } catch (SQLiteDoneException ignored) { } else try { synchronized (stmtGetUsageMethod) { stmtGetUsageMethod.clearBindings(); stmtGetUsageMethod.bindLong(1, restriction.uid); stmtGetUsageMethod.bindString(2, restriction.restrictionName); stmtGetUsageMethod.bindString(3, restriction.methodName); lastUsage = Math.max(lastUsage, stmtGetUsageMethod.simpleQueryForLong()); } } catch (SQLiteDoneException ignored) { } } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return lastUsage; } @Override public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { Cursor cursor; if (uid == 0) { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, null, new String[] {}, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } else { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (usage data)"); else try { while (cursor.moveToNext()) { PRestriction data = new PRestriction(); data.uid = cursor.getInt(0); data.restrictionName = cursor.getString(1); data.methodName = cursor.getString(2); data.restricted = (cursor.getInt(3) > 0); data.time = cursor.getLong(4); data.extra = cursor.getString(5); result.add(data); } } finally { cursor.close(); } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteUsage(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { if (uid == 0) dbUsage.delete(cTableUsage, null, new String[] {}); else dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Usage data deleted uid=" + uid); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Settings @Override public void setSetting(PSetting setting) throws RemoteException { try { enforcePermission(); setSettingInternal(setting); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setSettingInternal(PSetting setting) throws RemoteException { try { SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(setting.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); if (setting.value != null) mSettingCache.put(key, key); } } // Clear restrictions for white list if (Meta.isWhitelist(setting.type)) for (String restrictionName : PrivacyManager.getRestrictions()) for (Hook hook : PrivacyManager.getHooks(restrictionName)) if (setting.type.equals(hook.whitelist())) { PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(), hook.getName()); Util.log(null, Log.WARN, "Clearing cache for " + restriction); synchronized (mRestrictionCache) { for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) { Util.log(null, Log.WARN, "Removing " + key); mRestrictionCache.remove(key); } } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setSettingList(List<PSetting> listSetting) throws RemoteException { enforcePermission(); for (PSetting setting : listSetting) setSettingInternal(setting); } @Override @SuppressLint("DefaultLocale") public PSetting getSetting(PSetting setting) throws RemoteException { PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value); try { // No permissions enforced // Check cache if (mUseCache && setting.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) { result.value = mSettingCache.get(key).getValue(); return result; } } } // No persmissions required SQLiteDatabase db = getDb(); if (db == null) return result; // Fallback if (!PrivacyManager.cSettingMigrated.equals(setting.name) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (setting.uid == 0) result.value = PrivacyProvider.getSettingFallback(setting.name, null, false); if (result.value == null) { result.value = PrivacyProvider.getSettingFallback( String.format("%s.%d", setting.name, setting.uid), setting.value, false); return result; } } // Precompile statement when needed if (stmtGetSetting == null) { String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?"; stmtGetSetting = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetSetting) { stmtGetSetting.clearBindings(); stmtGetSetting.bindLong(1, setting.uid); stmtGetSetting.bindString(2, setting.type); stmtGetSetting.bindString(3, setting.name); String value = stmtGetSetting.simpleQueryForString(); if (value != null) result.value = value; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Add to cache if (mUseCache && result.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(result.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); mSettingCache.put(key, key); } } } catch (Throwable ex) { Util.bug(null, ex); } return result; } @Override public List<PSetting> getSettingList(int uid) throws RemoteException { List<PSetting> listSetting = new ArrayList<PSetting>(); try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return listSetting; mLock.readLock().lock(); db.beginTransaction(); try { Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null); if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (settings)"); else try { while (cursor.moveToNext()) listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor .getString(2))); } finally { cursor.close(); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return listSetting; } @Override public void deleteSettings(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Settings deleted uid=" + uid); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear cache if (mUseCache) synchronized (mSettingCache) { mSettingCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void clear() throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); SQLiteDatabase dbUsage = getDbUsage(); if (db == null || dbUsage == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM " + cTableRestriction); db.execSQL("DELETE FROM " + cTableSetting); Util.log(null, Log.WARN, "Database cleared"); // Reset migrated ContentValues values = new ContentValues(); values.put("uid", 0); values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) { synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } Util.log(null, Log.WARN, "Caches cleared"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("DELETE FROM " + cTableUsage); Util.log(null, Log.WARN, "Usage database cleared"); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void dump(int uid) throws RemoteException { if (uid == 0) { } else { synchronized (mRestrictionCache) { for (CRestriction crestriction : mRestrictionCache.keySet()) if (crestriction.getUid() == uid) Util.log(null, Log.WARN, "Dump crestriction=" + crestriction); } synchronized (mAskedOnceCache) { for (CRestriction crestriction : mAskedOnceCache.keySet()) if (crestriction.getUid() == uid && !crestriction.isExpired()) Util.log(null, Log.WARN, "Dump asked=" + crestriction); } synchronized (mSettingCache) { for (CSetting csetting : mSettingCache.keySet()) if (csetting.getUid() == uid) Util.log(null, Log.WARN, "Dump csetting=" + csetting); } } } // Helper methods private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) { try { // Without handler nothing can be done if (mHandler == null) return false; // Check for exceptions if (hook != null && !hook.canOnDemand()) return false; // Check if enabled if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true)) return false; if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false)) return false; // Skip dangerous methods final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); if (!dangerous && hook != null && hook.isDangerous() && hook.whitelist() == null) return false; // Get am context final Context context = getContext(); if (context == null) return false; long token = 0; try { token = Binder.clearCallingIdentity(); // Get application info final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid); // Check if system application if (!dangerous && appInfo.isSystem()) return false; // Check if activity manager agrees if (!XActivityManagerService.canOnDemand()) return false; // Go ask Util.log(null, Log.WARN, "On demand " + restriction); mOndemandSemaphore.acquireUninterruptibly(); try { // Check if activity manager still agrees if (!XActivityManagerService.canOnDemand()) return false; Util.log(null, Log.WARN, "On demanding " + restriction); // Check if not asked before CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) if (mRestrictionCache.get(key).asked) { Util.log(null, Log.WARN, "Already asked " + restriction); return false; } } synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) { Util.log(null, Log.WARN, "Already asked once " + restriction); return false; } } if (restriction.extra != null && hook != null && hook.whitelist() != null) { CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra); CSetting xkey = null; String xextra = getXExtra(restriction, hook); if (xextra != null) xkey = new CSetting(restriction.uid, hook.whitelist(), xextra); synchronized (mSettingCache) { if (mSettingCache.containsKey(skey) || (xkey != null && mSettingCache.containsKey(xkey))) { Util.log(null, Log.WARN, "Already asked " + skey); return false; } } } final AlertDialogHolder holder = new AlertDialogHolder(); final CountDownLatch latch = new CountDownLatch(1); // Run dialog in looper mHandler.post(new Runnable() { @Override public void run() { try { // Dialog AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo, dangerous, result, context, latch); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE); alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); alertDialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); holder.dialog = alertDialog; // Progress bar final ProgressBar mProgress = (ProgressBar) alertDialog .findViewById(R.id.pbProgress); mProgress.setMax(cMaxOnDemandDialog * 20); mProgress.setProgress(cMaxOnDemandDialog * 20); Runnable rProgress = new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) { mProgress.incrementProgressBy(-1); mHandler.postDelayed(this, 50); } } }; mHandler.postDelayed(rProgress, 50); } catch (Throwable ex) { Util.bug(null, ex); latch.countDown(); } } }); // Wait for dialog to complete if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) { Util.log(null, Log.WARN, "On demand dialog timeout " + restriction); mHandler.post(new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null) dialog.cancel(); } }); } } finally { mOndemandSemaphore.release(); } } finally { Binder.restoreCallingIdentity(token); } } catch (Throwable ex) { Util.bug(null, ex); } return true; } final class AlertDialogHolder { public AlertDialog dialog = null; } private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook, ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context, final CountDownLatch latch) throws NameNotFoundException { // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Reference views View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null); ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon); TextView tvUid = (TextView) view.findViewById(R.id.tvUid); TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName); TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt); TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory); TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction); TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters); TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters); final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory); final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce); final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist); final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra); // Set values if ((hook != null && hook.isDangerous()) || appInfo.isSystem()) view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark)); ivAppIcon.setImageDrawable(appInfo.getIcon(context)); tvUid.setText(Integer.toString(appInfo.getUid())); tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName())); String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow); tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")"); int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self); tvCategory.setText(resources.getString(catId)); tvFunction.setText(restriction.methodName); if (restriction.extra == null) rowParameters.setVisibility(View.GONE); else tvParameters.setText(restriction.extra); cbCategory.setChecked(mSelectCategory); cbOnce.setChecked(mSelectOnce); cbOnce.setText(String.format(resources.getString(R.string.title_once), PrivacyManager.cRestrictionCacheTimeoutMs / 1000)); if (hook != null && hook.whitelist() != null && restriction.extra != null) { cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra)); cbWhitelist.setVisibility(View.VISIBLE); String xextra = getXExtra(restriction, hook); if (xextra != null) { cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra)); cbWhitelistExtra.setVisibility(View.VISIBLE); } } // Category, once and whitelist exclude each other cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); } } }); // Ask AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(resources.getString(R.string.app_name)); alertDialogBuilder.setView(view); alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher)); alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Deny result.restricted = true; - mSelectCategory = cbCategory.isChecked(); - mSelectOnce = cbOnce.isChecked(); + if (cbCategory.isChecked() || cbOnce.isChecked()) { + mSelectCategory = cbCategory.isChecked(); + mSelectOnce = cbOnce.isChecked(); + } if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), true); latch.countDown(); } }); alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Allow result.restricted = false; - mSelectCategory = cbCategory.isChecked(); - mSelectOnce = cbOnce.isChecked(); + if (cbCategory.isChecked() || cbOnce.isChecked()) { + mSelectCategory = cbCategory.isChecked(); + mSelectOnce = cbOnce.isChecked(); + } if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), false); latch.countDown(); } }); return alertDialogBuilder; } private String getXExtra(PRestriction restriction, Hook hook) { if (hook != null) if (hook.whitelist().equals(Meta.cTypeFilename)) { String folder = new File(restriction.extra).getParent(); if (!TextUtils.isEmpty(folder)) return folder + File.separatorChar + "*"; } else if (hook.whitelist().equals(Meta.cTypeIPAddress)) { int semi = restriction.extra.lastIndexOf(':'); String address = (semi >= 0 ? restriction.extra.substring(0, semi) : restriction.extra); if (Patterns.IP_ADDRESS.matcher(address).matches()) { int dot = address.lastIndexOf('.'); return address.substring(0, dot + 1) + '*' + (semi >= 0 ? restriction.extra.substring(semi) : ""); } else { int dot = restriction.extra.indexOf('.'); if (dot > 0) return '*' + restriction.extra.substring(dot); } } return null; } private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result, Hook hook) { try { // Set the whitelist Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction + " xextra=" + xextra); setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra : xextra), Boolean.toString(!result.restricted))); } catch (Throwable ex) { Util.bug(null, ex); } } private void onDemandOnce(final PRestriction restriction, final PRestriction result) { Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction); result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key)) mAskedOnceCache.remove(key); mAskedOnceCache.put(key, key); } } private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) { try { PRestriction result = new PRestriction(restriction); // Get current category restriction state boolean prevRestricted = false; CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) prevRestricted = mRestrictionCache.get(key).restricted; } Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/" + prevRestricted + " restrict=" + restrict); if (category || (restrict && restrict != prevRestricted)) { // Set category restriction result.methodName = null; result.restricted = restrict; result.asked = category; setRestrictionInternal(result); // Clear category on change boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) { result.methodName = md.getName(); result.restricted = (md.isDangerous() && !dangerous ? false : restrict); result.asked = category; setRestrictionInternal(result); } } if (!category) { // Set method restriction result.methodName = restriction.methodName; result.restricted = restrict; result.asked = true; result.extra = restriction.extra; setRestrictionInternal(result); } // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } catch (Throwable ex) { Util.bug(null, ex); } } private void notifyRestricted(final PRestriction restriction) { final Context context = getContext(); if (context != null && mHandler != null) mHandler.post(new Runnable() { @Override public void run() { long token = 0; try { token = Binder.clearCallingIdentity(); // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Notify user String text = resources.getString(R.string.msg_restrictedby); text += " (" + restriction.uid + " " + restriction.restrictionName + "/" + restriction.methodName + ")"; Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException ex) { Util.bug(null, ex); } finally { Binder.restoreCallingIdentity(token); } } }); } private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException { return getSettingBool(uid, "", name, defaultValue); } private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException { String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value; return Boolean.parseBoolean(value); } private void enforcePermission() { int callingUid = Util.getAppId(Binder.getCallingUid()); if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid()); } private Context getContext() { // public static ActivityManagerService self() // frameworks/base/services/java/com/android/server/am/ActivityManagerService.java try { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); Object am = cam.getMethod("self").invoke(null); if (am == null) return null; return (Context) cam.getDeclaredField("mContext").get(am); } catch (Throwable ex) { Util.bug(null, ex); return null; } } private int getXUid() { if (mXUid < 0) try { Context context = getContext(); if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { String self = PrivacyService.class.getPackage().getName(); ApplicationInfo xInfo = pm.getApplicationInfo(self, 0); mXUid = xInfo.uid; } } } catch (Throwable ignored) { // The package manager may not be up-to-date yet } return mXUid; } private File getDbFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "xprivacy.db"); } private File getDbUsageFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "usage.db"); } private void setupDatabase() { try { File dbFile = getDbFile(); // Create database folder dbFile.getParentFile().mkdirs(); // Check database folder if (dbFile.getParentFile().isDirectory()) Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile()); else Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile()); // Move database from data/xprivacy folder File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy"); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Move database from data/application folder folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator + PrivacyService.class.getPackage().getName()); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Set database file permissions // Owner: rwx (system) // Group: rwx (system) // World: --- Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); File[] files = dbFile.getParentFile().listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); } catch (Throwable ex) { Util.bug(null, ex); } } private SQLiteDatabase getDb() { synchronized (this) { // Check current reference if (mDb != null && !mDb.isOpen()) { mDb = null; Util.log(null, Log.ERROR, "Database not open"); } mLock.readLock().lock(); try { if (mDb != null && mDb.getVersion() != 11) { mDb = null; Util.log(null, Log.ERROR, "Database wrong version=" + mDb.getVersion()); } } finally { mLock.readLock().unlock(); } if (mDb == null) try { setupDatabase(); // Create/upgrade database when needed File dbFile = getDbFile(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); // Check database integrity if (db.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Database integrity ok"); else { // http://www.sqlite.org/howtocorrupt.html Util.log(null, Log.ERROR, "Database corrupt"); Cursor cursor = db.rawQuery("PRAGMA integrity_check", null); try { while (cursor.moveToNext()) { String message = cursor.getString(0); Util.log(null, Log.ERROR, message); } } finally { cursor.close(); } db.close(); // Backup database file File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup"); dbBackup.delete(); dbFile.renameTo(dbBackup); File dbJournal = new File(dbFile.getAbsolutePath() + "-journal"); File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal"); dbJournalBackup.delete(); dbJournal.renameTo(dbJournalBackup); Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath()); // Create new database db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); Util.log(null, Log.ERROR, "New, empty database created"); } // Update migration status if (db.getVersion() > 1) { Util.log(null, Log.WARN, "Updating migration status"); mLock.writeLock().lock(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", 0); if (db.getVersion() > 9) values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } // Upgrade database if needed if (db.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating database"); mLock.writeLock().lock(); db.beginTransaction(); try { // http://www.sqlite.org/lang_createtable.html db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)"); db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)"); db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)"); db.setVersion(1); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); // Old migrated indication db.setVersion(2); } if (db.needUpgrade(3)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM usage WHERE method=''"); db.setVersion(3); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(4)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value IS NULL"); db.setVersion(4); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(5)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value = ''"); db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'"); db.setVersion(5); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(6)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'"); db.setVersion(6); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(7)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT"); db.setVersion(7); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(8)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP INDEX idx_usage"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); db.setVersion(8); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(9)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP TABLE usage"); db.setVersion(9); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(10)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT"); db.execSQL("DROP INDEX idx_setting"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)"); db.execSQL("UPDATE setting SET type=''"); db.setVersion(10); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(11)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { List<PSetting> listSetting = new ArrayList<PSetting>(); Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null, null, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { int uid = cursor.getInt(0); String name = cursor.getString(1); String value = cursor.getString(2); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); String type = name.substring(0, dot); listSetting .add(new PSetting(uid, type, name.substring(dot + 1), value)); listSetting.add(new PSetting(uid, "", name, null)); } else if (name.startsWith("Whitelist.")) { String[] component = name.split("\\."); listSetting.add(new PSetting(uid, component[1], name.replace( component[0] + "." + component[1] + ".", ""), value)); listSetting.add(new PSetting(uid, "", name, null)); } } } finally { cursor.close(); } for (PSetting setting : listSetting) { Util.log(null, Log.WARN, "Converting " + setting); if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } db.setVersion(11); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLock.writeLock().lock(); try { db.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLock.writeLock().unlock(); } Util.log(null, Log.WARN, "Database version=" + db.getVersion()); mDb = db; } catch (Throwable ex) { mDb = null; // retry Util.bug(null, ex); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream( "/cache/xprivacy.log", true)); outputStreamWriter.write(ex.toString()); outputStreamWriter.write("\n"); outputStreamWriter.write(Log.getStackTraceString(ex)); outputStreamWriter.write("\n"); outputStreamWriter.close(); } catch (Throwable exex) { Util.bug(null, exex); } } return mDb; } } private SQLiteDatabase getDbUsage() { synchronized (this) { // Check current reference if (mDbUsage != null && !mDbUsage.isOpen()) { mDbUsage = null; Util.log(null, Log.ERROR, "Usage database not open"); } if (mDbUsage == null) try { // Create/upgrade database when needed File dbUsageFile = getDbUsageFile(); SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); // Check database integrity if (dbUsage.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Usage database integrity ok"); else { dbUsage.close(); dbUsageFile.delete(); new File(dbUsageFile + "-journal").delete(); dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); Util.log(null, Log.ERROR, "Deleted corrupt usage data database"); } // Upgrade database if needed if (dbUsage.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating usage database"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); dbUsage.setVersion(1); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLockUsage.writeLock().lock(); try { dbUsage.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLockUsage.writeLock().unlock(); } Util.log(null, Log.WARN, "Changing to asynchronous mode"); try { dbUsage.rawQuery("PRAGMA synchronous=OFF", null); } catch (Throwable ex) { Util.bug(null, ex); } Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion()); mDbUsage = dbUsage; } catch (Throwable ex) { mDbUsage = null; // retry Util.bug(null, ex); } return mDbUsage; } } }; }
false
true
public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { Cursor cursor; if (uid == 0) { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, null, new String[] {}, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } else { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (usage data)"); else try { while (cursor.moveToNext()) { PRestriction data = new PRestriction(); data.uid = cursor.getInt(0); data.restrictionName = cursor.getString(1); data.methodName = cursor.getString(2); data.restricted = (cursor.getInt(3) > 0); data.time = cursor.getLong(4); data.extra = cursor.getString(5); result.add(data); } } finally { cursor.close(); } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteUsage(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { if (uid == 0) dbUsage.delete(cTableUsage, null, new String[] {}); else dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Usage data deleted uid=" + uid); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Settings @Override public void setSetting(PSetting setting) throws RemoteException { try { enforcePermission(); setSettingInternal(setting); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setSettingInternal(PSetting setting) throws RemoteException { try { SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(setting.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); if (setting.value != null) mSettingCache.put(key, key); } } // Clear restrictions for white list if (Meta.isWhitelist(setting.type)) for (String restrictionName : PrivacyManager.getRestrictions()) for (Hook hook : PrivacyManager.getHooks(restrictionName)) if (setting.type.equals(hook.whitelist())) { PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(), hook.getName()); Util.log(null, Log.WARN, "Clearing cache for " + restriction); synchronized (mRestrictionCache) { for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) { Util.log(null, Log.WARN, "Removing " + key); mRestrictionCache.remove(key); } } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setSettingList(List<PSetting> listSetting) throws RemoteException { enforcePermission(); for (PSetting setting : listSetting) setSettingInternal(setting); } @Override @SuppressLint("DefaultLocale") public PSetting getSetting(PSetting setting) throws RemoteException { PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value); try { // No permissions enforced // Check cache if (mUseCache && setting.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) { result.value = mSettingCache.get(key).getValue(); return result; } } } // No persmissions required SQLiteDatabase db = getDb(); if (db == null) return result; // Fallback if (!PrivacyManager.cSettingMigrated.equals(setting.name) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (setting.uid == 0) result.value = PrivacyProvider.getSettingFallback(setting.name, null, false); if (result.value == null) { result.value = PrivacyProvider.getSettingFallback( String.format("%s.%d", setting.name, setting.uid), setting.value, false); return result; } } // Precompile statement when needed if (stmtGetSetting == null) { String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?"; stmtGetSetting = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetSetting) { stmtGetSetting.clearBindings(); stmtGetSetting.bindLong(1, setting.uid); stmtGetSetting.bindString(2, setting.type); stmtGetSetting.bindString(3, setting.name); String value = stmtGetSetting.simpleQueryForString(); if (value != null) result.value = value; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Add to cache if (mUseCache && result.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(result.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); mSettingCache.put(key, key); } } } catch (Throwable ex) { Util.bug(null, ex); } return result; } @Override public List<PSetting> getSettingList(int uid) throws RemoteException { List<PSetting> listSetting = new ArrayList<PSetting>(); try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return listSetting; mLock.readLock().lock(); db.beginTransaction(); try { Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null); if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (settings)"); else try { while (cursor.moveToNext()) listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor .getString(2))); } finally { cursor.close(); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return listSetting; } @Override public void deleteSettings(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Settings deleted uid=" + uid); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear cache if (mUseCache) synchronized (mSettingCache) { mSettingCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void clear() throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); SQLiteDatabase dbUsage = getDbUsage(); if (db == null || dbUsage == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM " + cTableRestriction); db.execSQL("DELETE FROM " + cTableSetting); Util.log(null, Log.WARN, "Database cleared"); // Reset migrated ContentValues values = new ContentValues(); values.put("uid", 0); values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) { synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } Util.log(null, Log.WARN, "Caches cleared"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("DELETE FROM " + cTableUsage); Util.log(null, Log.WARN, "Usage database cleared"); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void dump(int uid) throws RemoteException { if (uid == 0) { } else { synchronized (mRestrictionCache) { for (CRestriction crestriction : mRestrictionCache.keySet()) if (crestriction.getUid() == uid) Util.log(null, Log.WARN, "Dump crestriction=" + crestriction); } synchronized (mAskedOnceCache) { for (CRestriction crestriction : mAskedOnceCache.keySet()) if (crestriction.getUid() == uid && !crestriction.isExpired()) Util.log(null, Log.WARN, "Dump asked=" + crestriction); } synchronized (mSettingCache) { for (CSetting csetting : mSettingCache.keySet()) if (csetting.getUid() == uid) Util.log(null, Log.WARN, "Dump csetting=" + csetting); } } } // Helper methods private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) { try { // Without handler nothing can be done if (mHandler == null) return false; // Check for exceptions if (hook != null && !hook.canOnDemand()) return false; // Check if enabled if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true)) return false; if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false)) return false; // Skip dangerous methods final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); if (!dangerous && hook != null && hook.isDangerous() && hook.whitelist() == null) return false; // Get am context final Context context = getContext(); if (context == null) return false; long token = 0; try { token = Binder.clearCallingIdentity(); // Get application info final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid); // Check if system application if (!dangerous && appInfo.isSystem()) return false; // Check if activity manager agrees if (!XActivityManagerService.canOnDemand()) return false; // Go ask Util.log(null, Log.WARN, "On demand " + restriction); mOndemandSemaphore.acquireUninterruptibly(); try { // Check if activity manager still agrees if (!XActivityManagerService.canOnDemand()) return false; Util.log(null, Log.WARN, "On demanding " + restriction); // Check if not asked before CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) if (mRestrictionCache.get(key).asked) { Util.log(null, Log.WARN, "Already asked " + restriction); return false; } } synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) { Util.log(null, Log.WARN, "Already asked once " + restriction); return false; } } if (restriction.extra != null && hook != null && hook.whitelist() != null) { CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra); CSetting xkey = null; String xextra = getXExtra(restriction, hook); if (xextra != null) xkey = new CSetting(restriction.uid, hook.whitelist(), xextra); synchronized (mSettingCache) { if (mSettingCache.containsKey(skey) || (xkey != null && mSettingCache.containsKey(xkey))) { Util.log(null, Log.WARN, "Already asked " + skey); return false; } } } final AlertDialogHolder holder = new AlertDialogHolder(); final CountDownLatch latch = new CountDownLatch(1); // Run dialog in looper mHandler.post(new Runnable() { @Override public void run() { try { // Dialog AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo, dangerous, result, context, latch); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE); alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); alertDialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); holder.dialog = alertDialog; // Progress bar final ProgressBar mProgress = (ProgressBar) alertDialog .findViewById(R.id.pbProgress); mProgress.setMax(cMaxOnDemandDialog * 20); mProgress.setProgress(cMaxOnDemandDialog * 20); Runnable rProgress = new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) { mProgress.incrementProgressBy(-1); mHandler.postDelayed(this, 50); } } }; mHandler.postDelayed(rProgress, 50); } catch (Throwable ex) { Util.bug(null, ex); latch.countDown(); } } }); // Wait for dialog to complete if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) { Util.log(null, Log.WARN, "On demand dialog timeout " + restriction); mHandler.post(new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null) dialog.cancel(); } }); } } finally { mOndemandSemaphore.release(); } } finally { Binder.restoreCallingIdentity(token); } } catch (Throwable ex) { Util.bug(null, ex); } return true; } final class AlertDialogHolder { public AlertDialog dialog = null; } private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook, ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context, final CountDownLatch latch) throws NameNotFoundException { // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Reference views View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null); ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon); TextView tvUid = (TextView) view.findViewById(R.id.tvUid); TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName); TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt); TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory); TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction); TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters); TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters); final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory); final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce); final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist); final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra); // Set values if ((hook != null && hook.isDangerous()) || appInfo.isSystem()) view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark)); ivAppIcon.setImageDrawable(appInfo.getIcon(context)); tvUid.setText(Integer.toString(appInfo.getUid())); tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName())); String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow); tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")"); int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self); tvCategory.setText(resources.getString(catId)); tvFunction.setText(restriction.methodName); if (restriction.extra == null) rowParameters.setVisibility(View.GONE); else tvParameters.setText(restriction.extra); cbCategory.setChecked(mSelectCategory); cbOnce.setChecked(mSelectOnce); cbOnce.setText(String.format(resources.getString(R.string.title_once), PrivacyManager.cRestrictionCacheTimeoutMs / 1000)); if (hook != null && hook.whitelist() != null && restriction.extra != null) { cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra)); cbWhitelist.setVisibility(View.VISIBLE); String xextra = getXExtra(restriction, hook); if (xextra != null) { cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra)); cbWhitelistExtra.setVisibility(View.VISIBLE); } } // Category, once and whitelist exclude each other cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); } } }); // Ask AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(resources.getString(R.string.app_name)); alertDialogBuilder.setView(view); alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher)); alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Deny result.restricted = true; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), true); latch.countDown(); } }); alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Allow result.restricted = false; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), false); latch.countDown(); } }); return alertDialogBuilder; } private String getXExtra(PRestriction restriction, Hook hook) { if (hook != null) if (hook.whitelist().equals(Meta.cTypeFilename)) { String folder = new File(restriction.extra).getParent(); if (!TextUtils.isEmpty(folder)) return folder + File.separatorChar + "*"; } else if (hook.whitelist().equals(Meta.cTypeIPAddress)) { int semi = restriction.extra.lastIndexOf(':'); String address = (semi >= 0 ? restriction.extra.substring(0, semi) : restriction.extra); if (Patterns.IP_ADDRESS.matcher(address).matches()) { int dot = address.lastIndexOf('.'); return address.substring(0, dot + 1) + '*' + (semi >= 0 ? restriction.extra.substring(semi) : ""); } else { int dot = restriction.extra.indexOf('.'); if (dot > 0) return '*' + restriction.extra.substring(dot); } } return null; } private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result, Hook hook) { try { // Set the whitelist Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction + " xextra=" + xextra); setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra : xextra), Boolean.toString(!result.restricted))); } catch (Throwable ex) { Util.bug(null, ex); } } private void onDemandOnce(final PRestriction restriction, final PRestriction result) { Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction); result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key)) mAskedOnceCache.remove(key); mAskedOnceCache.put(key, key); } } private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) { try { PRestriction result = new PRestriction(restriction); // Get current category restriction state boolean prevRestricted = false; CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) prevRestricted = mRestrictionCache.get(key).restricted; } Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/" + prevRestricted + " restrict=" + restrict); if (category || (restrict && restrict != prevRestricted)) { // Set category restriction result.methodName = null; result.restricted = restrict; result.asked = category; setRestrictionInternal(result); // Clear category on change boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) { result.methodName = md.getName(); result.restricted = (md.isDangerous() && !dangerous ? false : restrict); result.asked = category; setRestrictionInternal(result); } } if (!category) { // Set method restriction result.methodName = restriction.methodName; result.restricted = restrict; result.asked = true; result.extra = restriction.extra; setRestrictionInternal(result); } // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } catch (Throwable ex) { Util.bug(null, ex); } } private void notifyRestricted(final PRestriction restriction) { final Context context = getContext(); if (context != null && mHandler != null) mHandler.post(new Runnable() { @Override public void run() { long token = 0; try { token = Binder.clearCallingIdentity(); // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Notify user String text = resources.getString(R.string.msg_restrictedby); text += " (" + restriction.uid + " " + restriction.restrictionName + "/" + restriction.methodName + ")"; Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException ex) { Util.bug(null, ex); } finally { Binder.restoreCallingIdentity(token); } } }); } private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException { return getSettingBool(uid, "", name, defaultValue); } private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException { String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value; return Boolean.parseBoolean(value); } private void enforcePermission() { int callingUid = Util.getAppId(Binder.getCallingUid()); if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid()); } private Context getContext() { // public static ActivityManagerService self() // frameworks/base/services/java/com/android/server/am/ActivityManagerService.java try { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); Object am = cam.getMethod("self").invoke(null); if (am == null) return null; return (Context) cam.getDeclaredField("mContext").get(am); } catch (Throwable ex) { Util.bug(null, ex); return null; } } private int getXUid() { if (mXUid < 0) try { Context context = getContext(); if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { String self = PrivacyService.class.getPackage().getName(); ApplicationInfo xInfo = pm.getApplicationInfo(self, 0); mXUid = xInfo.uid; } } } catch (Throwable ignored) { // The package manager may not be up-to-date yet } return mXUid; } private File getDbFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "xprivacy.db"); } private File getDbUsageFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "usage.db"); } private void setupDatabase() { try { File dbFile = getDbFile(); // Create database folder dbFile.getParentFile().mkdirs(); // Check database folder if (dbFile.getParentFile().isDirectory()) Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile()); else Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile()); // Move database from data/xprivacy folder File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy"); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Move database from data/application folder folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator + PrivacyService.class.getPackage().getName()); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Set database file permissions // Owner: rwx (system) // Group: rwx (system) // World: --- Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); File[] files = dbFile.getParentFile().listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); } catch (Throwable ex) { Util.bug(null, ex); } } private SQLiteDatabase getDb() { synchronized (this) { // Check current reference if (mDb != null && !mDb.isOpen()) { mDb = null; Util.log(null, Log.ERROR, "Database not open"); } mLock.readLock().lock(); try { if (mDb != null && mDb.getVersion() != 11) { mDb = null; Util.log(null, Log.ERROR, "Database wrong version=" + mDb.getVersion()); } } finally { mLock.readLock().unlock(); } if (mDb == null) try { setupDatabase(); // Create/upgrade database when needed File dbFile = getDbFile(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); // Check database integrity if (db.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Database integrity ok"); else { // http://www.sqlite.org/howtocorrupt.html Util.log(null, Log.ERROR, "Database corrupt"); Cursor cursor = db.rawQuery("PRAGMA integrity_check", null); try { while (cursor.moveToNext()) { String message = cursor.getString(0); Util.log(null, Log.ERROR, message); } } finally { cursor.close(); } db.close(); // Backup database file File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup"); dbBackup.delete(); dbFile.renameTo(dbBackup); File dbJournal = new File(dbFile.getAbsolutePath() + "-journal"); File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal"); dbJournalBackup.delete(); dbJournal.renameTo(dbJournalBackup); Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath()); // Create new database db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); Util.log(null, Log.ERROR, "New, empty database created"); } // Update migration status if (db.getVersion() > 1) { Util.log(null, Log.WARN, "Updating migration status"); mLock.writeLock().lock(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", 0); if (db.getVersion() > 9) values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } // Upgrade database if needed if (db.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating database"); mLock.writeLock().lock(); db.beginTransaction(); try { // http://www.sqlite.org/lang_createtable.html db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)"); db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)"); db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)"); db.setVersion(1); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); // Old migrated indication db.setVersion(2); } if (db.needUpgrade(3)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM usage WHERE method=''"); db.setVersion(3); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(4)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value IS NULL"); db.setVersion(4); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(5)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value = ''"); db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'"); db.setVersion(5); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(6)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'"); db.setVersion(6); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(7)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT"); db.setVersion(7); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(8)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP INDEX idx_usage"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); db.setVersion(8); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(9)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP TABLE usage"); db.setVersion(9); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(10)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT"); db.execSQL("DROP INDEX idx_setting"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)"); db.execSQL("UPDATE setting SET type=''"); db.setVersion(10); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(11)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { List<PSetting> listSetting = new ArrayList<PSetting>(); Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null, null, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { int uid = cursor.getInt(0); String name = cursor.getString(1); String value = cursor.getString(2); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); String type = name.substring(0, dot); listSetting .add(new PSetting(uid, type, name.substring(dot + 1), value)); listSetting.add(new PSetting(uid, "", name, null)); } else if (name.startsWith("Whitelist.")) { String[] component = name.split("\\."); listSetting.add(new PSetting(uid, component[1], name.replace( component[0] + "." + component[1] + ".", ""), value)); listSetting.add(new PSetting(uid, "", name, null)); } } } finally { cursor.close(); } for (PSetting setting : listSetting) { Util.log(null, Log.WARN, "Converting " + setting); if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } db.setVersion(11); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLock.writeLock().lock(); try { db.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLock.writeLock().unlock(); } Util.log(null, Log.WARN, "Database version=" + db.getVersion()); mDb = db; } catch (Throwable ex) { mDb = null; // retry Util.bug(null, ex); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream( "/cache/xprivacy.log", true)); outputStreamWriter.write(ex.toString()); outputStreamWriter.write("\n"); outputStreamWriter.write(Log.getStackTraceString(ex)); outputStreamWriter.write("\n"); outputStreamWriter.close(); } catch (Throwable exex) { Util.bug(null, exex); } } return mDb; } } private SQLiteDatabase getDbUsage() { synchronized (this) { // Check current reference if (mDbUsage != null && !mDbUsage.isOpen()) { mDbUsage = null; Util.log(null, Log.ERROR, "Usage database not open"); } if (mDbUsage == null) try { // Create/upgrade database when needed File dbUsageFile = getDbUsageFile(); SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); // Check database integrity if (dbUsage.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Usage database integrity ok"); else { dbUsage.close(); dbUsageFile.delete(); new File(dbUsageFile + "-journal").delete(); dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); Util.log(null, Log.ERROR, "Deleted corrupt usage data database"); } // Upgrade database if needed if (dbUsage.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating usage database"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); dbUsage.setVersion(1); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLockUsage.writeLock().lock(); try { dbUsage.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLockUsage.writeLock().unlock(); } Util.log(null, Log.WARN, "Changing to asynchronous mode"); try { dbUsage.rawQuery("PRAGMA synchronous=OFF", null); } catch (Throwable ex) { Util.bug(null, ex); } Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion()); mDbUsage = dbUsage; } catch (Throwable ex) { mDbUsage = null; // retry Util.bug(null, ex); } return mDbUsage; } } }; }
public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { Cursor cursor; if (uid == 0) { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, null, new String[] {}, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } else { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (usage data)"); else try { while (cursor.moveToNext()) { PRestriction data = new PRestriction(); data.uid = cursor.getInt(0); data.restrictionName = cursor.getString(1); data.methodName = cursor.getString(2); data.restricted = (cursor.getInt(3) > 0); data.time = cursor.getLong(4); data.extra = cursor.getString(5); result.add(data); } } finally { cursor.close(); } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteUsage(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { if (uid == 0) dbUsage.delete(cTableUsage, null, new String[] {}); else dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Usage data deleted uid=" + uid); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Settings @Override public void setSetting(PSetting setting) throws RemoteException { try { enforcePermission(); setSettingInternal(setting); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setSettingInternal(PSetting setting) throws RemoteException { try { SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(setting.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); if (setting.value != null) mSettingCache.put(key, key); } } // Clear restrictions for white list if (Meta.isWhitelist(setting.type)) for (String restrictionName : PrivacyManager.getRestrictions()) for (Hook hook : PrivacyManager.getHooks(restrictionName)) if (setting.type.equals(hook.whitelist())) { PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(), hook.getName()); Util.log(null, Log.WARN, "Clearing cache for " + restriction); synchronized (mRestrictionCache) { for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) { Util.log(null, Log.WARN, "Removing " + key); mRestrictionCache.remove(key); } } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setSettingList(List<PSetting> listSetting) throws RemoteException { enforcePermission(); for (PSetting setting : listSetting) setSettingInternal(setting); } @Override @SuppressLint("DefaultLocale") public PSetting getSetting(PSetting setting) throws RemoteException { PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value); try { // No permissions enforced // Check cache if (mUseCache && setting.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) { result.value = mSettingCache.get(key).getValue(); return result; } } } // No persmissions required SQLiteDatabase db = getDb(); if (db == null) return result; // Fallback if (!PrivacyManager.cSettingMigrated.equals(setting.name) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (setting.uid == 0) result.value = PrivacyProvider.getSettingFallback(setting.name, null, false); if (result.value == null) { result.value = PrivacyProvider.getSettingFallback( String.format("%s.%d", setting.name, setting.uid), setting.value, false); return result; } } // Precompile statement when needed if (stmtGetSetting == null) { String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?"; stmtGetSetting = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetSetting) { stmtGetSetting.clearBindings(); stmtGetSetting.bindLong(1, setting.uid); stmtGetSetting.bindString(2, setting.type); stmtGetSetting.bindString(3, setting.name); String value = stmtGetSetting.simpleQueryForString(); if (value != null) result.value = value; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Add to cache if (mUseCache && result.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(result.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); mSettingCache.put(key, key); } } } catch (Throwable ex) { Util.bug(null, ex); } return result; } @Override public List<PSetting> getSettingList(int uid) throws RemoteException { List<PSetting> listSetting = new ArrayList<PSetting>(); try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return listSetting; mLock.readLock().lock(); db.beginTransaction(); try { Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null); if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (settings)"); else try { while (cursor.moveToNext()) listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor .getString(2))); } finally { cursor.close(); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return listSetting; } @Override public void deleteSettings(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Settings deleted uid=" + uid); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear cache if (mUseCache) synchronized (mSettingCache) { mSettingCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void clear() throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); SQLiteDatabase dbUsage = getDbUsage(); if (db == null || dbUsage == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM " + cTableRestriction); db.execSQL("DELETE FROM " + cTableSetting); Util.log(null, Log.WARN, "Database cleared"); // Reset migrated ContentValues values = new ContentValues(); values.put("uid", 0); values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) { synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } Util.log(null, Log.WARN, "Caches cleared"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("DELETE FROM " + cTableUsage); Util.log(null, Log.WARN, "Usage database cleared"); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void dump(int uid) throws RemoteException { if (uid == 0) { } else { synchronized (mRestrictionCache) { for (CRestriction crestriction : mRestrictionCache.keySet()) if (crestriction.getUid() == uid) Util.log(null, Log.WARN, "Dump crestriction=" + crestriction); } synchronized (mAskedOnceCache) { for (CRestriction crestriction : mAskedOnceCache.keySet()) if (crestriction.getUid() == uid && !crestriction.isExpired()) Util.log(null, Log.WARN, "Dump asked=" + crestriction); } synchronized (mSettingCache) { for (CSetting csetting : mSettingCache.keySet()) if (csetting.getUid() == uid) Util.log(null, Log.WARN, "Dump csetting=" + csetting); } } } // Helper methods private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) { try { // Without handler nothing can be done if (mHandler == null) return false; // Check for exceptions if (hook != null && !hook.canOnDemand()) return false; // Check if enabled if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true)) return false; if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false)) return false; // Skip dangerous methods final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); if (!dangerous && hook != null && hook.isDangerous() && hook.whitelist() == null) return false; // Get am context final Context context = getContext(); if (context == null) return false; long token = 0; try { token = Binder.clearCallingIdentity(); // Get application info final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid); // Check if system application if (!dangerous && appInfo.isSystem()) return false; // Check if activity manager agrees if (!XActivityManagerService.canOnDemand()) return false; // Go ask Util.log(null, Log.WARN, "On demand " + restriction); mOndemandSemaphore.acquireUninterruptibly(); try { // Check if activity manager still agrees if (!XActivityManagerService.canOnDemand()) return false; Util.log(null, Log.WARN, "On demanding " + restriction); // Check if not asked before CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) if (mRestrictionCache.get(key).asked) { Util.log(null, Log.WARN, "Already asked " + restriction); return false; } } synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) { Util.log(null, Log.WARN, "Already asked once " + restriction); return false; } } if (restriction.extra != null && hook != null && hook.whitelist() != null) { CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra); CSetting xkey = null; String xextra = getXExtra(restriction, hook); if (xextra != null) xkey = new CSetting(restriction.uid, hook.whitelist(), xextra); synchronized (mSettingCache) { if (mSettingCache.containsKey(skey) || (xkey != null && mSettingCache.containsKey(xkey))) { Util.log(null, Log.WARN, "Already asked " + skey); return false; } } } final AlertDialogHolder holder = new AlertDialogHolder(); final CountDownLatch latch = new CountDownLatch(1); // Run dialog in looper mHandler.post(new Runnable() { @Override public void run() { try { // Dialog AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo, dangerous, result, context, latch); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE); alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); alertDialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); holder.dialog = alertDialog; // Progress bar final ProgressBar mProgress = (ProgressBar) alertDialog .findViewById(R.id.pbProgress); mProgress.setMax(cMaxOnDemandDialog * 20); mProgress.setProgress(cMaxOnDemandDialog * 20); Runnable rProgress = new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) { mProgress.incrementProgressBy(-1); mHandler.postDelayed(this, 50); } } }; mHandler.postDelayed(rProgress, 50); } catch (Throwable ex) { Util.bug(null, ex); latch.countDown(); } } }); // Wait for dialog to complete if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) { Util.log(null, Log.WARN, "On demand dialog timeout " + restriction); mHandler.post(new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null) dialog.cancel(); } }); } } finally { mOndemandSemaphore.release(); } } finally { Binder.restoreCallingIdentity(token); } } catch (Throwable ex) { Util.bug(null, ex); } return true; } final class AlertDialogHolder { public AlertDialog dialog = null; } private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook, ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context, final CountDownLatch latch) throws NameNotFoundException { // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Reference views View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null); ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon); TextView tvUid = (TextView) view.findViewById(R.id.tvUid); TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName); TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt); TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory); TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction); TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters); TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters); final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory); final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce); final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist); final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra); // Set values if ((hook != null && hook.isDangerous()) || appInfo.isSystem()) view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark)); ivAppIcon.setImageDrawable(appInfo.getIcon(context)); tvUid.setText(Integer.toString(appInfo.getUid())); tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName())); String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow); tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")"); int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self); tvCategory.setText(resources.getString(catId)); tvFunction.setText(restriction.methodName); if (restriction.extra == null) rowParameters.setVisibility(View.GONE); else tvParameters.setText(restriction.extra); cbCategory.setChecked(mSelectCategory); cbOnce.setChecked(mSelectOnce); cbOnce.setText(String.format(resources.getString(R.string.title_once), PrivacyManager.cRestrictionCacheTimeoutMs / 1000)); if (hook != null && hook.whitelist() != null && restriction.extra != null) { cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra)); cbWhitelist.setVisibility(View.VISIBLE); String xextra = getXExtra(restriction, hook); if (xextra != null) { cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra)); cbWhitelistExtra.setVisibility(View.VISIBLE); } } // Category, once and whitelist exclude each other cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); } } }); // Ask AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(resources.getString(R.string.app_name)); alertDialogBuilder.setView(view); alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher)); alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Deny result.restricted = true; if (cbCategory.isChecked() || cbOnce.isChecked()) { mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); } if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), true); latch.countDown(); } }); alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Allow result.restricted = false; if (cbCategory.isChecked() || cbOnce.isChecked()) { mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); } if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), false); latch.countDown(); } }); return alertDialogBuilder; } private String getXExtra(PRestriction restriction, Hook hook) { if (hook != null) if (hook.whitelist().equals(Meta.cTypeFilename)) { String folder = new File(restriction.extra).getParent(); if (!TextUtils.isEmpty(folder)) return folder + File.separatorChar + "*"; } else if (hook.whitelist().equals(Meta.cTypeIPAddress)) { int semi = restriction.extra.lastIndexOf(':'); String address = (semi >= 0 ? restriction.extra.substring(0, semi) : restriction.extra); if (Patterns.IP_ADDRESS.matcher(address).matches()) { int dot = address.lastIndexOf('.'); return address.substring(0, dot + 1) + '*' + (semi >= 0 ? restriction.extra.substring(semi) : ""); } else { int dot = restriction.extra.indexOf('.'); if (dot > 0) return '*' + restriction.extra.substring(dot); } } return null; } private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result, Hook hook) { try { // Set the whitelist Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction + " xextra=" + xextra); setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra : xextra), Boolean.toString(!result.restricted))); } catch (Throwable ex) { Util.bug(null, ex); } } private void onDemandOnce(final PRestriction restriction, final PRestriction result) { Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction); result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key)) mAskedOnceCache.remove(key); mAskedOnceCache.put(key, key); } } private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) { try { PRestriction result = new PRestriction(restriction); // Get current category restriction state boolean prevRestricted = false; CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) prevRestricted = mRestrictionCache.get(key).restricted; } Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/" + prevRestricted + " restrict=" + restrict); if (category || (restrict && restrict != prevRestricted)) { // Set category restriction result.methodName = null; result.restricted = restrict; result.asked = category; setRestrictionInternal(result); // Clear category on change boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) { result.methodName = md.getName(); result.restricted = (md.isDangerous() && !dangerous ? false : restrict); result.asked = category; setRestrictionInternal(result); } } if (!category) { // Set method restriction result.methodName = restriction.methodName; result.restricted = restrict; result.asked = true; result.extra = restriction.extra; setRestrictionInternal(result); } // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } catch (Throwable ex) { Util.bug(null, ex); } } private void notifyRestricted(final PRestriction restriction) { final Context context = getContext(); if (context != null && mHandler != null) mHandler.post(new Runnable() { @Override public void run() { long token = 0; try { token = Binder.clearCallingIdentity(); // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Notify user String text = resources.getString(R.string.msg_restrictedby); text += " (" + restriction.uid + " " + restriction.restrictionName + "/" + restriction.methodName + ")"; Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException ex) { Util.bug(null, ex); } finally { Binder.restoreCallingIdentity(token); } } }); } private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException { return getSettingBool(uid, "", name, defaultValue); } private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException { String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value; return Boolean.parseBoolean(value); } private void enforcePermission() { int callingUid = Util.getAppId(Binder.getCallingUid()); if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid()); } private Context getContext() { // public static ActivityManagerService self() // frameworks/base/services/java/com/android/server/am/ActivityManagerService.java try { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); Object am = cam.getMethod("self").invoke(null); if (am == null) return null; return (Context) cam.getDeclaredField("mContext").get(am); } catch (Throwable ex) { Util.bug(null, ex); return null; } } private int getXUid() { if (mXUid < 0) try { Context context = getContext(); if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { String self = PrivacyService.class.getPackage().getName(); ApplicationInfo xInfo = pm.getApplicationInfo(self, 0); mXUid = xInfo.uid; } } } catch (Throwable ignored) { // The package manager may not be up-to-date yet } return mXUid; } private File getDbFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "xprivacy.db"); } private File getDbUsageFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "usage.db"); } private void setupDatabase() { try { File dbFile = getDbFile(); // Create database folder dbFile.getParentFile().mkdirs(); // Check database folder if (dbFile.getParentFile().isDirectory()) Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile()); else Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile()); // Move database from data/xprivacy folder File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy"); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Move database from data/application folder folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator + PrivacyService.class.getPackage().getName()); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Set database file permissions // Owner: rwx (system) // Group: rwx (system) // World: --- Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); File[] files = dbFile.getParentFile().listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); } catch (Throwable ex) { Util.bug(null, ex); } } private SQLiteDatabase getDb() { synchronized (this) { // Check current reference if (mDb != null && !mDb.isOpen()) { mDb = null; Util.log(null, Log.ERROR, "Database not open"); } mLock.readLock().lock(); try { if (mDb != null && mDb.getVersion() != 11) { mDb = null; Util.log(null, Log.ERROR, "Database wrong version=" + mDb.getVersion()); } } finally { mLock.readLock().unlock(); } if (mDb == null) try { setupDatabase(); // Create/upgrade database when needed File dbFile = getDbFile(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); // Check database integrity if (db.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Database integrity ok"); else { // http://www.sqlite.org/howtocorrupt.html Util.log(null, Log.ERROR, "Database corrupt"); Cursor cursor = db.rawQuery("PRAGMA integrity_check", null); try { while (cursor.moveToNext()) { String message = cursor.getString(0); Util.log(null, Log.ERROR, message); } } finally { cursor.close(); } db.close(); // Backup database file File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup"); dbBackup.delete(); dbFile.renameTo(dbBackup); File dbJournal = new File(dbFile.getAbsolutePath() + "-journal"); File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal"); dbJournalBackup.delete(); dbJournal.renameTo(dbJournalBackup); Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath()); // Create new database db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); Util.log(null, Log.ERROR, "New, empty database created"); } // Update migration status if (db.getVersion() > 1) { Util.log(null, Log.WARN, "Updating migration status"); mLock.writeLock().lock(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", 0); if (db.getVersion() > 9) values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } // Upgrade database if needed if (db.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating database"); mLock.writeLock().lock(); db.beginTransaction(); try { // http://www.sqlite.org/lang_createtable.html db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)"); db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)"); db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)"); db.setVersion(1); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); // Old migrated indication db.setVersion(2); } if (db.needUpgrade(3)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM usage WHERE method=''"); db.setVersion(3); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(4)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value IS NULL"); db.setVersion(4); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(5)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value = ''"); db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'"); db.setVersion(5); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(6)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'"); db.setVersion(6); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(7)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT"); db.setVersion(7); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(8)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP INDEX idx_usage"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); db.setVersion(8); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(9)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP TABLE usage"); db.setVersion(9); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(10)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT"); db.execSQL("DROP INDEX idx_setting"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)"); db.execSQL("UPDATE setting SET type=''"); db.setVersion(10); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(11)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { List<PSetting> listSetting = new ArrayList<PSetting>(); Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null, null, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { int uid = cursor.getInt(0); String name = cursor.getString(1); String value = cursor.getString(2); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); String type = name.substring(0, dot); listSetting .add(new PSetting(uid, type, name.substring(dot + 1), value)); listSetting.add(new PSetting(uid, "", name, null)); } else if (name.startsWith("Whitelist.")) { String[] component = name.split("\\."); listSetting.add(new PSetting(uid, component[1], name.replace( component[0] + "." + component[1] + ".", ""), value)); listSetting.add(new PSetting(uid, "", name, null)); } } } finally { cursor.close(); } for (PSetting setting : listSetting) { Util.log(null, Log.WARN, "Converting " + setting); if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } db.setVersion(11); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLock.writeLock().lock(); try { db.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLock.writeLock().unlock(); } Util.log(null, Log.WARN, "Database version=" + db.getVersion()); mDb = db; } catch (Throwable ex) { mDb = null; // retry Util.bug(null, ex); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream( "/cache/xprivacy.log", true)); outputStreamWriter.write(ex.toString()); outputStreamWriter.write("\n"); outputStreamWriter.write(Log.getStackTraceString(ex)); outputStreamWriter.write("\n"); outputStreamWriter.close(); } catch (Throwable exex) { Util.bug(null, exex); } } return mDb; } } private SQLiteDatabase getDbUsage() { synchronized (this) { // Check current reference if (mDbUsage != null && !mDbUsage.isOpen()) { mDbUsage = null; Util.log(null, Log.ERROR, "Usage database not open"); } if (mDbUsage == null) try { // Create/upgrade database when needed File dbUsageFile = getDbUsageFile(); SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); // Check database integrity if (dbUsage.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Usage database integrity ok"); else { dbUsage.close(); dbUsageFile.delete(); new File(dbUsageFile + "-journal").delete(); dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); Util.log(null, Log.ERROR, "Deleted corrupt usage data database"); } // Upgrade database if needed if (dbUsage.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating usage database"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); dbUsage.setVersion(1); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLockUsage.writeLock().lock(); try { dbUsage.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLockUsage.writeLock().unlock(); } Util.log(null, Log.WARN, "Changing to asynchronous mode"); try { dbUsage.rawQuery("PRAGMA synchronous=OFF", null); } catch (Throwable ex) { Util.bug(null, ex); } Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion()); mDbUsage = dbUsage; } catch (Throwable ex) { mDbUsage = null; // retry Util.bug(null, ex); } return mDbUsage; } } }; }
diff --git a/apps/animaldb/test/AnimaldbSeleniumTest.java b/apps/animaldb/test/AnimaldbSeleniumTest.java index 564b4c153..5d1c5cf8f 100644 --- a/apps/animaldb/test/AnimaldbSeleniumTest.java +++ b/apps/animaldb/test/AnimaldbSeleniumTest.java @@ -1,496 +1,494 @@ package test; import java.util.Calendar; import org.molgenis.MolgenisOptions.MapperImplementation; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.jpa.JpaUtil; import org.openqa.selenium.server.RemoteControlConfiguration; import org.openqa.selenium.server.SeleniumServer; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import plugins.emptydb.emptyDatabase; import app.DatabaseFactory; import app.FillMetadata; import app.servlet.UsedMolgenisOptions; import boot.RunStandalone; import com.thoughtworks.selenium.DefaultSelenium; import com.thoughtworks.selenium.HttpCommandProcessor; import com.thoughtworks.selenium.Selenium; import core.Helper; public class AnimaldbSeleniumTest { Selenium selenium; Integer sleepTime = 1000; String pageLoadTimeout = "120000"; boolean tomcat = false; //String storagePath = new File(".").getAbsolutePath() + File.separator + "tmp_selenium_test_data"; @BeforeClass public void start() throws Exception { int webserverPort = 8080; if(!this.tomcat) webserverPort = Helper.getAvailablePort(11000, 10); String seleniumUrl = "http://localhost:" + webserverPort + "/"; String seleniumHost = "localhost"; String seleniumBrowser = "firefox"; int seleniumPort = Helper.getAvailablePort(11010, 10); RemoteControlConfiguration rcc = new RemoteControlConfiguration(); rcc.setSingleWindow(true); rcc.setPort(seleniumPort); try { SeleniumServer server = new SeleniumServer(false, rcc); server.boot(); } catch (Exception e) { throw new IllegalStateException("Cannot start selenium server: ", e); } HttpCommandProcessor proc = new HttpCommandProcessor(seleniumHost, seleniumPort, seleniumBrowser, seleniumUrl); selenium = new DefaultSelenium(proc); selenium.start(); selenium.setTimeout(pageLoadTimeout); if(new UsedMolgenisOptions().mapper_implementation == MapperImplementation.JPA) { Database db = DatabaseFactory.create(); JpaUtil.dropAndCreateTables(db, null); FillMetadata.fillMetadata(db, false); } else { // To be sure, empty db and don't add MolgenisUsers etc. new emptyDatabase(DatabaseFactory.create("apps/animaldb/org/molgenis/animaldb/animaldb.properties"), false); } if(!this.tomcat) new RunStandalone(webserverPort); } @Test public void startup() throws InterruptedException { selenium.open("/animaldb/molgenis.do"); selenium.waitForPageToLoad(pageLoadTimeout); sleepHelper("startup"); } @Test(dependsOnMethods={"startup"}) public void loginAdmin() throws InterruptedException { // Login Assert.assertEquals(selenium.getText("link=Register"), "Register"); selenium.type("id=username", "admin"); selenium.type("id=password", "admin"); selenium.click("id=Login"); selenium.waitForPageToLoad(pageLoadTimeout); // Now we get to the Welcome screen Assert.assertEquals(selenium.getTitle(), "AnimalDB"); Assert.assertTrue(selenium.isTextPresent("Welcome to AnimalDB!")); // Go to Import database plugin selenium.click("id=Admin_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("systemmenu_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("LoadLegacy_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Import database")); // First try and see if we're on Erik's laptop selenium.type("id=zip", "C:\\Users\\Erik\\Dropbox\\GCC\\AnimalDB\\Data\\legacy\\PrefillAnimalDB.zip"); selenium.click("id=source1"); selenium.click("id=load"); selenium.waitForPageToLoad(pageLoadTimeout); if (!selenium.isTextPresent("Pre-filling AnimalDB successful")) { // If not, let's assume we're on the Hudson server selenium.type("id=zip", "/data/home/erikroos/PrefillAnimalDB.zip"); selenium.click("id=source1"); selenium.click("id=load"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Pre-filling AnimalDB successful")); } sleepHelper("loginAdmin"); } @Test(dependsOnMethods={"loginAdmin"}) public void makeUser() throws InterruptedException { // Go to AnimalDB user mgmt. plugin (first item in Admin -> Security menu) selenium.click("securitymenu_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); // Make user 'test' selenium.click("link=Make new user"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.type("id=firstname", "test"); selenium.type("id=lastname", "test"); selenium.type("id=email", "[email protected]"); selenium.type("id=username", "test"); selenium.type("id=password1", "test"); selenium.type("id=password2", "test"); selenium.type("id=newinv", "testInv"); selenium.click("id=adduser"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("User test successfully added and assigned ownership of investigation testInv")); sleepHelper("makeUser"); } @Test(dependsOnMethods={"makeUser"}) public void logoutAdmin() throws InterruptedException { selenium.click("id=UserLogin_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=Logout"); selenium.waitForPageToLoad(pageLoadTimeout); sleepHelper("logoutAdmin"); } @Test(dependsOnMethods={"logoutAdmin"}) public void loginUser() throws InterruptedException { // Login Assert.assertEquals(selenium.getText("link=Register"), "Register"); selenium.type("id=username", "test"); selenium.type("id=password", "test"); selenium.click("id=Login"); selenium.waitForPageToLoad(pageLoadTimeout); // Now we get to the Welcome screen Assert.assertEquals(selenium.getTitle(), "AnimalDB"); Assert.assertTrue(selenium.isTextPresent("Welcome to AnimalDB!")); sleepHelper("loginUser"); } @Test(dependsOnMethods={"loginUser"}) public void addAnimals() throws Exception { // Go to Add Animal plugin selenium.click("id=animalmenu_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=AddAnimal_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Bring in animals")); // Add 10 female House mice selenium.select("id=species", "label=House mouse"); selenium.select("id=background", "label=C57BL/6j"); selenium.select("id=sex", "label=Female"); selenium.select("id=source", "label=Harlan"); selenium.select("id=animaltype", "label=A. Gewoon dier"); selenium.type("id=numberofanimals", "10"); selenium.click("id=Add"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("10 animal(s) successfully added")); // Add 10 male House mice selenium.select("id=species", "label=House mouse"); selenium.select("id=background", "label=C57BL/6j"); selenium.select("id=sex", "label=Male"); selenium.select("id=source", "label=Harlan"); selenium.select("id=animaltype", "label=A. Gewoon dier"); selenium.type("id=numberofanimals", "10"); selenium.click("id=Add"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("10 animal(s) successfully added")); sleepHelper("addAnimals"); } @Test(dependsOnMethods={"addAnimals"}) public void breedingWorkflow() throws Exception { // Go to Breeding line plugin selenium.click("id=Settings_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=ManageLines_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Breeding lines")); // Add a breeding line selenium.type("id=linename", "MyLine"); selenium.select("id=species", "label=House mouse"); selenium.click("id=add"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Line successfully added")); // Go to Parentgroup plugin selenium.click("id=animalmenu_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=breedingmodule_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=ManageParentgroups_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Existing parentgroups")); // Add a parent group selenium.click("id=createpg"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 1: line selenium.click("id=from1to2"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 2: mothers selenium.click("id=mothermatrix_removeFilter_3"); // remove filter on line (line is not set for new animals) // We have to wait here, but it's Ajax, so it's faster than a normal full page load // (however, 1 sec. is not (always) enough on Hudson, so set to 5 sec.) Thread.sleep(5000); selenium.click("id=mothermatrix_selected_0"); // toggle selectbox for first female in list selenium.click("id=from2to3"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 3: fathers selenium.click("id=fathermatrix_removeFilter_3"); // remove filter on line (line is not set for new animals) // We have to wait here, but it's Ajax, so it's faster than a normal full page load // (however, 1 sec. is not (always) enough on Hudson, so set to 5 sec.) Thread.sleep(5000); selenium.click("id=fathermatrix_selected_0"); // toggle selectbox for first male in list selenium.click("id=from3to4"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 4: start date and remarks selenium.click("id=addpg"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("successfully added")); // Go to Litter plugin selenium.click("ManageLitters_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Litters")); // Add a litter selenium.click("id=addlitter"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=matrix_selected_0"); // toggle selectbox for first parent group in list selenium.type("id=littersize", "5"); selenium.click("id=addlitter"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("successfully added")); // Wean litter selenium.click("link=Wean"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.type("id=weansizefemale", "2"); selenium.type("id=weansizemale", "3"); selenium.click("id=wean"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully weaned")); Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001")); // Check cage labels link selenium.click("link=Create temporary cage labels"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Download temporary wean labels as pdf")); selenium.click("link=Back to overview"); selenium.waitForPageToLoad(pageLoadTimeout); // Genotype litter // TODO: expand selenium.click("link=Genotype"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Parentgroup: PG_MyLine_000001")); Assert.assertTrue(selenium.isTextPresent("Line: MyLine")); selenium.click("id=save"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully genotyped")); // Check definitive cage labels link - selenium.click("id=showdone"); - selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001")); selenium.click("id=littermatrix_selected_0"); selenium.click("makedeflabels"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Download definitive cage labels as pdf")); - selenium.click("link=Back to overview of weaned and genotyped litters"); + selenium.click("link=Back to overview"); selenium.waitForPageToLoad(pageLoadTimeout); sleepHelper("breedingWorkflow"); } @Test(dependsOnMethods={"breedingWorkflow"}) public void decWorkflow() throws Exception { Calendar calendar = Calendar.getInstance(); //String[] months = new String[] {"January", "February", "March", "April", "May", "June", // "July", "August", "September", "October", "November", "December"}; // Go to DEC project plugin selenium.click("id=decmenu_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=AddProject_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("DEC applications")); // Make a DEC project selenium.click("link=Add"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.type("id=dectitle", "MyDEC"); selenium.type("id=decnumber", "12345"); selenium.type("id=decapppdf", "/home/test/app.pdf"); selenium.type("id=decapprovalpdf", "/home/test/app2.pdf"); int thisYear = calendar.get(Calendar.YEAR); selenium.type("id=startdate", thisYear + "-01-01"); selenium.type("id=enddate", thisYear + "-12-31"); selenium.click("id=addproject"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("DEC Project successfully added")); Assert.assertTrue(selenium.isTextPresent("MyDEC")); // Go to DEC subproject plugin selenium.click("id=AddSubproject_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("DEC subprojects")); // Make a DEC subproject selenium.click("link=Add"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.type("id=experimenttitle", "MyProject"); selenium.type("id=expnumber", "A"); selenium.type("id=decapppdf", "/home/test/subapp.pdf"); //int thisMonth = calendar.get(Calendar.MONTH); selenium.type("id=startdate", thisYear + "-01-01"); selenium.type("id=enddate", thisYear + "-02-01"); selenium.click("id=addsubproject"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("DEC subproject successfully added")); // Add animals to DEC selenium.click("link=Manage"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=startadd"); selenium.waitForPageToLoad(pageLoadTimeout); // toggle selectboxes for first five animals in list selenium.click("id=addanimalsmatrix_selected_0"); selenium.click("id=addanimalsmatrix_selected_1"); selenium.click("id=addanimalsmatrix_selected_2"); selenium.click("id=addanimalsmatrix_selected_3"); selenium.click("id=addanimalsmatrix_selected_4"); selenium.type("id=subprojectadditiondate", thisYear + "-01-01"); selenium.click("id=doadd"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Animal(s) successfully added")); selenium.click("link=Back to overview"); selenium.waitForPageToLoad(pageLoadTimeout); // Remove animals from DEC // toggle selectboxes for first two animals in list selenium.click("id=remanimalsmatrix_selected_0"); selenium.click("id=remanimalsmatrix_selected_1"); selenium.click("id=dorem"); // click Remove button selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=dorem"); // click Apply button selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Animal(s) successfully removed")); selenium.click("link=Back to overview"); selenium.waitForPageToLoad(pageLoadTimeout); // Check portal selenium.click("DecStatus_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("DEC status portal")); Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[1]/td[1]"), "12345"); Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[2]/td[4]"), "A"); Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[2]/td[7]"), "3"); Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[2]/td[8]"), "2"); sleepHelper("decWorkflow"); } @Test(dependsOnMethods={"decWorkflow"}) public void yearlyReports() throws Exception { // Go to Report plugin selenium.click("id=YearlyReportModule_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); // Report 4A (default) selenium.click("id=generate"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertEquals(selenium.getTable("css=#reporttablediv > table.2.0"), "Muizen"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[2]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[3]"), "5"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[4]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[5]/strong"), "20"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[6]/strong"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[7]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[8]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[9]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[10]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[11]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[12]"), "2"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[13]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[14]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[15]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[16]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[17]"), "0"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[18]"), "23"); // Report 5 selenium.select("id=form", "value=5"); selenium.click("id=generate"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[1]"), "12345A - DEC 12345"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[6]"), "2"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[15]"), "A. Dood in het kader van de proef"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[16]"), "12345A"); Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[17]"), "Mus musculus"); sleepHelper("yearlyReports"); } // @Test(dependsOnMethods={"yearlyReports"}) // public void applyProtocol() throws Exception { // // Go to Protocol plugin // selenium.click("id=Admin_tab_button"); // selenium.waitForPageToLoad(pageLoadTimeout); // selenium.click("id=systemmenu_tab_button"); // selenium.waitForPageToLoad(pageLoadTimeout); // selenium.click("id=ApplyProtocol_tab_button"); // selenium.waitForPageToLoad(pageLoadTimeout); // // Apply 'SetWeight' protocol on animal '000001' // selenium.select("id=Protocols", "label=SetWeight"); // selenium.click("id=targetmatrix_selected_0"); // toggle selectbox for first animal in matrix // selenium.click("id=TimeBox"); // selenium.click("id=Select"); // selenium.waitForPageToLoad(pageLoadTimeout); // Assert.assertEquals(selenium.getText("//div[@id='divValueTable']/table/thead/tr/th[2]"), "Weight"); // Assert.assertEquals(selenium.getText("//div[@id='divValueTable']/table/thead/tr/th[3]"), "Weight start"); // Assert.assertEquals(selenium.getText("//div[@id='divValueTable']/table/thead/tr/th[4]"), "Weight end"); // selenium.type("id=0_1_0", "200"); // selenium.click("id=ApplyStartTime_1"); // selenium.waitForPageToLoad(pageLoadTimeout); // selenium.click("id=Apply"); // selenium.waitForPageToLoad(pageLoadTimeout); // Assert.assertTrue(selenium.isTextPresent("Protocol applied successfully")); // // Check in Timeline value viewer // selenium.click("id=animalmenu_tab_button"); // selenium.waitForPageToLoad(pageLoadTimeout); // selenium.click("id=EventViewer_tab_button"); // selenium.waitForPageToLoad(pageLoadTimeout); // selenium.click("id=targetmatrix_selected_0"); // toggle radio button for first animal in list // selenium.click("id=select"); // selenium.waitForPageToLoad(pageLoadTimeout); // Assert.assertTrue(selenium.isTextPresent("Weight")); // Assert.assertTrue(selenium.isTextPresent("200")); // // sleepHelper("applyProtocol"); // } @Test(dependsOnMethods={"yearlyReports"}) public void logoutUser() throws InterruptedException { selenium.click("id=UserLogin_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=Logout"); selenium.waitForPageToLoad(pageLoadTimeout); sleepHelper("logout"); } @AfterClass(alwaysRun=true) public void stop() throws Exception { selenium.stop(); //added to fix TestDatabase which runs after this one... //see comment in TestDatabase! UsedMolgenisOptions usedMolgenisOptions = new UsedMolgenisOptions(); if(usedMolgenisOptions.mapper_implementation == MapperImplementation.JPA) { Database db = DatabaseFactory.create(); JpaUtil.dropAndCreateTables(db, null); FillMetadata.fillMetadata(db, false); } else { new emptyDatabase(DatabaseFactory.create("apps/animaldb/org/molgenis/animaldb/animaldb.properties"), false); } //Helper.deleteStorage(); //Helper.deleteDatabase(); } private void sleepHelper(String who) throws InterruptedException { System.out.println(who + " done, now sleeping for " + sleepTime + " msec"); Thread.sleep(sleepTime); } }
false
true
public void breedingWorkflow() throws Exception { // Go to Breeding line plugin selenium.click("id=Settings_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=ManageLines_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Breeding lines")); // Add a breeding line selenium.type("id=linename", "MyLine"); selenium.select("id=species", "label=House mouse"); selenium.click("id=add"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Line successfully added")); // Go to Parentgroup plugin selenium.click("id=animalmenu_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=breedingmodule_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=ManageParentgroups_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Existing parentgroups")); // Add a parent group selenium.click("id=createpg"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 1: line selenium.click("id=from1to2"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 2: mothers selenium.click("id=mothermatrix_removeFilter_3"); // remove filter on line (line is not set for new animals) // We have to wait here, but it's Ajax, so it's faster than a normal full page load // (however, 1 sec. is not (always) enough on Hudson, so set to 5 sec.) Thread.sleep(5000); selenium.click("id=mothermatrix_selected_0"); // toggle selectbox for first female in list selenium.click("id=from2to3"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 3: fathers selenium.click("id=fathermatrix_removeFilter_3"); // remove filter on line (line is not set for new animals) // We have to wait here, but it's Ajax, so it's faster than a normal full page load // (however, 1 sec. is not (always) enough on Hudson, so set to 5 sec.) Thread.sleep(5000); selenium.click("id=fathermatrix_selected_0"); // toggle selectbox for first male in list selenium.click("id=from3to4"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 4: start date and remarks selenium.click("id=addpg"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("successfully added")); // Go to Litter plugin selenium.click("ManageLitters_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Litters")); // Add a litter selenium.click("id=addlitter"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=matrix_selected_0"); // toggle selectbox for first parent group in list selenium.type("id=littersize", "5"); selenium.click("id=addlitter"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("successfully added")); // Wean litter selenium.click("link=Wean"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.type("id=weansizefemale", "2"); selenium.type("id=weansizemale", "3"); selenium.click("id=wean"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully weaned")); Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001")); // Check cage labels link selenium.click("link=Create temporary cage labels"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Download temporary wean labels as pdf")); selenium.click("link=Back to overview"); selenium.waitForPageToLoad(pageLoadTimeout); // Genotype litter // TODO: expand selenium.click("link=Genotype"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Parentgroup: PG_MyLine_000001")); Assert.assertTrue(selenium.isTextPresent("Line: MyLine")); selenium.click("id=save"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully genotyped")); // Check definitive cage labels link selenium.click("id=showdone"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001")); selenium.click("id=littermatrix_selected_0"); selenium.click("makedeflabels"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Download definitive cage labels as pdf")); selenium.click("link=Back to overview of weaned and genotyped litters"); selenium.waitForPageToLoad(pageLoadTimeout); sleepHelper("breedingWorkflow"); }
public void breedingWorkflow() throws Exception { // Go to Breeding line plugin selenium.click("id=Settings_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=ManageLines_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Breeding lines")); // Add a breeding line selenium.type("id=linename", "MyLine"); selenium.select("id=species", "label=House mouse"); selenium.click("id=add"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Line successfully added")); // Go to Parentgroup plugin selenium.click("id=animalmenu_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=breedingmodule_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=ManageParentgroups_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Existing parentgroups")); // Add a parent group selenium.click("id=createpg"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 1: line selenium.click("id=from1to2"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 2: mothers selenium.click("id=mothermatrix_removeFilter_3"); // remove filter on line (line is not set for new animals) // We have to wait here, but it's Ajax, so it's faster than a normal full page load // (however, 1 sec. is not (always) enough on Hudson, so set to 5 sec.) Thread.sleep(5000); selenium.click("id=mothermatrix_selected_0"); // toggle selectbox for first female in list selenium.click("id=from2to3"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 3: fathers selenium.click("id=fathermatrix_removeFilter_3"); // remove filter on line (line is not set for new animals) // We have to wait here, but it's Ajax, so it's faster than a normal full page load // (however, 1 sec. is not (always) enough on Hudson, so set to 5 sec.) Thread.sleep(5000); selenium.click("id=fathermatrix_selected_0"); // toggle selectbox for first male in list selenium.click("id=from3to4"); selenium.waitForPageToLoad(pageLoadTimeout); // Screen 4: start date and remarks selenium.click("id=addpg"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("successfully added")); // Go to Litter plugin selenium.click("ManageLitters_tab_button"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Litters")); // Add a litter selenium.click("id=addlitter"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.click("id=matrix_selected_0"); // toggle selectbox for first parent group in list selenium.type("id=littersize", "5"); selenium.click("id=addlitter"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("successfully added")); // Wean litter selenium.click("link=Wean"); selenium.waitForPageToLoad(pageLoadTimeout); selenium.type("id=weansizefemale", "2"); selenium.type("id=weansizemale", "3"); selenium.click("id=wean"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully weaned")); Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001")); // Check cage labels link selenium.click("link=Create temporary cage labels"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Download temporary wean labels as pdf")); selenium.click("link=Back to overview"); selenium.waitForPageToLoad(pageLoadTimeout); // Genotype litter // TODO: expand selenium.click("link=Genotype"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Parentgroup: PG_MyLine_000001")); Assert.assertTrue(selenium.isTextPresent("Line: MyLine")); selenium.click("id=save"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully genotyped")); // Check definitive cage labels link Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001")); selenium.click("id=littermatrix_selected_0"); selenium.click("makedeflabels"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("Download definitive cage labels as pdf")); selenium.click("link=Back to overview"); selenium.waitForPageToLoad(pageLoadTimeout); sleepHelper("breedingWorkflow"); }
diff --git a/src/main/java/de/groupon/hcktn/groupong/service/impl/ScoreServiceImpl.java b/src/main/java/de/groupon/hcktn/groupong/service/impl/ScoreServiceImpl.java index 2e0ec16..2fc4820 100644 --- a/src/main/java/de/groupon/hcktn/groupong/service/impl/ScoreServiceImpl.java +++ b/src/main/java/de/groupon/hcktn/groupong/service/impl/ScoreServiceImpl.java @@ -1,40 +1,40 @@ package de.groupon.hcktn.groupong.service.impl; import de.groupon.hcktn.groupong.domain.response.MatchDTO; import de.groupon.hcktn.groupong.model.dao.UserDAO; import de.groupon.hcktn.groupong.model.dao.impl.UserDAOImpl; import de.groupon.hcktn.groupong.model.entity.Match; import de.groupon.hcktn.groupong.model.entity.User; import de.groupon.hcktn.groupong.service.ScoreService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ScoreServiceImpl implements ScoreService { final Integer scoreMultiplier = 100; final Integer winBonus = 50; @Autowired private UserDAO myUserDAO; @Override public void score(Match match, MatchDTO matchDTO) { if ((match.getStatusId()==4 || match.getStatusId()==5) && matchDTO.getStatusId()==6) { - User user1 = myUserDAO.retrieve(matchDTO.getUser1Id()); - User user2 = myUserDAO.retrieve(matchDTO.getUser2Id()); + User user1 = myUserDAO.retrieve(match.getUser1Id()); + User user2 = myUserDAO.retrieve(match.getUser2Id()); Integer user1ActualScore = user1.getScore(); Integer user2ActualScore = user2.getScore(); - Integer user1NewScore = user1ActualScore + (matchDTO.getScoreUser1() * scoreMultiplier); - Integer user2NewScore = user2ActualScore + (matchDTO.getScoreUser2() * scoreMultiplier); - if (matchDTO.getScoreUser1() > matchDTO.getScoreUser2()) { + Integer user1NewScore = user1ActualScore + (match.getScoreUser1() * scoreMultiplier); + Integer user2NewScore = user2ActualScore + (match.getScoreUser2() * scoreMultiplier); + if (match.getScoreUser1() > match.getScoreUser2()) { user1NewScore += winBonus; - } else if (matchDTO.getScoreUser1() < matchDTO.getScoreUser2()) { + } else if (match.getScoreUser1() < match.getScoreUser2()) { user2NewScore += winBonus; } user1.setScore(user1NewScore); user2.setScore(user2NewScore); myUserDAO.update(user1); myUserDAO.update(user2); } } }
false
true
public void score(Match match, MatchDTO matchDTO) { if ((match.getStatusId()==4 || match.getStatusId()==5) && matchDTO.getStatusId()==6) { User user1 = myUserDAO.retrieve(matchDTO.getUser1Id()); User user2 = myUserDAO.retrieve(matchDTO.getUser2Id()); Integer user1ActualScore = user1.getScore(); Integer user2ActualScore = user2.getScore(); Integer user1NewScore = user1ActualScore + (matchDTO.getScoreUser1() * scoreMultiplier); Integer user2NewScore = user2ActualScore + (matchDTO.getScoreUser2() * scoreMultiplier); if (matchDTO.getScoreUser1() > matchDTO.getScoreUser2()) { user1NewScore += winBonus; } else if (matchDTO.getScoreUser1() < matchDTO.getScoreUser2()) { user2NewScore += winBonus; } user1.setScore(user1NewScore); user2.setScore(user2NewScore); myUserDAO.update(user1); myUserDAO.update(user2); } }
public void score(Match match, MatchDTO matchDTO) { if ((match.getStatusId()==4 || match.getStatusId()==5) && matchDTO.getStatusId()==6) { User user1 = myUserDAO.retrieve(match.getUser1Id()); User user2 = myUserDAO.retrieve(match.getUser2Id()); Integer user1ActualScore = user1.getScore(); Integer user2ActualScore = user2.getScore(); Integer user1NewScore = user1ActualScore + (match.getScoreUser1() * scoreMultiplier); Integer user2NewScore = user2ActualScore + (match.getScoreUser2() * scoreMultiplier); if (match.getScoreUser1() > match.getScoreUser2()) { user1NewScore += winBonus; } else if (match.getScoreUser1() < match.getScoreUser2()) { user2NewScore += winBonus; } user1.setScore(user1NewScore); user2.setScore(user2NewScore); myUserDAO.update(user1); myUserDAO.update(user2); } }
diff --git a/project/gncandroid/src/rednus/gncandroid/AccountsActivity.java b/project/gncandroid/src/rednus/gncandroid/AccountsActivity.java index 0f6dae8..f9e7601 100644 --- a/project/gncandroid/src/rednus/gncandroid/AccountsActivity.java +++ b/project/gncandroid/src/rednus/gncandroid/AccountsActivity.java @@ -1,279 +1,279 @@ /** GnuCash for Android. * * Copyright (C) 2010 Rednus Limited http://www.rednus.co.uk * Copyright (C) 2010,2011 John Gray * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package rednus.gncandroid; import java.text.NumberFormat; import java.util.Map; import java.util.TreeMap; import rednus.gncandroid.GNCDataHandler.Account; import rednus.gncandroid.GNCDataHandler.DataCollection; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; /** * @author shyam.avvari * */ public class AccountsActivity extends Activity implements OnItemClickListener { // TAG for this activity private static final String TAG = "AccountsActivity"; // Application data private GNCAndroid app; private String currRootGUID; private Map<String, Account> listData = new TreeMap<String, Account>(); private DataCollection dc; private SharedPreferences sp; private int dataChangeCount = 0; private AccountsListAdapter lstAdapter; /* * When activity is started, and if Data file is already read, then display * account information tree. * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "Creating activity..."); app = (GNCAndroid) getApplication(); sp = getSharedPreferences(GNCAndroid.SPN, MODE_PRIVATE); // First get first object of data dc = app.gncDataHandler.getGncData(); getListData(dc.book.rootAccountGUID); // set view setContentView(R.layout.accounts); // get list ListView lv = (ListView) findViewById(R.id.accounts); lstAdapter = new AccountsListAdapter(this); lv.setAdapter(lstAdapter); lv.setOnItemClickListener(this); Log.i(TAG, "Activity created."); } @Override protected void onResume() { super.onResume(); int cc = app.gncDataHandler.getChangeCount(); if ( cc != dataChangeCount ) { getListData(this.currRootGUID); dataChangeCount = cc; lstAdapter.notifyDataSetChanged(); } } /** * This method will get all the sub accounts of root and adds it to the list * for display. * * @param root */ private void getListData(String rootGUID) { // get root account listData = app.gncDataHandler.GetSubAccounts(rootGUID); if ( sp.getBoolean(app.res.getString(R.string.pref_include_subaccount_in_balance), false) ) app.gncDataHandler.getAccountBalanceWithChildren(rootGUID); currRootGUID = rootGUID; } /* * Event Handler for List item selection * * @see * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget * .AdapterView, android.view.View, int, long) */ public void onItemClick(AdapterView<?> parent, View child, int position, long id) { Log.i(TAG, "Account Selected"); // get adapter BaseAdapter b = (BaseAdapter) parent.getAdapter(); // get current item Account account = (Account) b.getItem(position); // depending on root or item get list if (account.GUID.equalsIgnoreCase(currRootGUID)) getListData(account.parentGUID); else getListData(account.GUID); // set refresh b.notifyDataSetChanged(); // reset list position to top parent.scrollTo(0, 0); Log.i(TAG, "Accounts Refreshed"); } /** * This class implements Adapter methods for displaying accounts in a list * view * * @author avvari.shyam * */ private class AccountsListAdapter extends BaseAdapter { private LayoutInflater mInflater; /** * Constructor - creates inflator's instance from context * * @param context */ public AccountsListAdapter(Context context) { mInflater = LayoutInflater.from(context); } /* * Returns the total number of items to be displayed * * @see android.widget.Adapter#getCount() */ public int getCount() { return listData.size(); } /* * Returns the Item in specific position * * @see android.widget.Adapter#getItem(int) */ public Object getItem(int i) { return listData.get(listData.keySet().toArray()[i]); } /* * Returns the id of the item in specific position. In this case its the * position itself. * * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int i) { return i; } /* * This method creates the list item for specific position passed. It * populates data from the list item at position. * * @see android.widget.Adapter#getView(int, android.view.View, * android.view.ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { AccountItem item; Account account; // always create new view convertView = mInflater.inflate(R.layout.account_item, null); item = new AccountItem(); item.btnExpand = (ImageView) convertView .findViewById(R.id.acc_more); item.txvAccName = (TextView) convertView .findViewById(R.id.acc_name); item.txvBalance = (TextView) convertView .findViewById(R.id.acc_balance); convertView.setTag(item); // set values for account line item account = (Account) getItem(position); item.txvAccName.setText(account.name); Double balance; if (sp.getBoolean(app.res.getString(R.string.pref_include_subaccount_in_balance), false)) balance = account.balanceWithChildren; else balance = account.balance; item.txvBalance.setText(String.valueOf(NumberFormat .getCurrencyInstance().format(balance))); // set amount colour if (balance < 0) item.txvBalance.setTextColor(app.res - .getColor(R.color.color_negetive)); + .getColor(R.color.color_negative)); else item.txvBalance.setTextColor(app.res .getColor(R.color.color_positive)); // set image properties if (account.GUID.equalsIgnoreCase(currRootGUID)) item.btnExpand.setImageResource(R.drawable.list_expanded); else if (account.hasChildren) item.btnExpand.setImageResource(R.drawable.list_collapsed); // return return convertView; } /* * When the data in list listData changed, it is necessary to redraw the * list view and fill it up with new data. * * @see android.widget.BaseAdapter#notifyDataSetChanged() */ @Override public void notifyDataSetChanged() { // first invalidate data set super.notifyDataSetInvalidated(); super.notifyDataSetChanged(); } /* * This methods tells the view layout that all the items in the list are * not enabled by default. * * @see android.widget.BaseAdapter#areAllItemsEnabled() */ @Override public boolean areAllItemsEnabled() { return false; } /* * This method checks if the list item has children and then return true * to enable the list item as clickable. * * @see android.widget.BaseAdapter#isEnabled(int) */ @Override public boolean isEnabled(int position) { Account account = (Account) getItem(position); return account.hasChildren; } /** * This is holder class for Account Summary Row * * @author shyam.avvari * */ private class AccountItem { ImageView btnExpand; TextView txvAccName; TextView txvBalance; } } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { AccountItem item; Account account; // always create new view convertView = mInflater.inflate(R.layout.account_item, null); item = new AccountItem(); item.btnExpand = (ImageView) convertView .findViewById(R.id.acc_more); item.txvAccName = (TextView) convertView .findViewById(R.id.acc_name); item.txvBalance = (TextView) convertView .findViewById(R.id.acc_balance); convertView.setTag(item); // set values for account line item account = (Account) getItem(position); item.txvAccName.setText(account.name); Double balance; if (sp.getBoolean(app.res.getString(R.string.pref_include_subaccount_in_balance), false)) balance = account.balanceWithChildren; else balance = account.balance; item.txvBalance.setText(String.valueOf(NumberFormat .getCurrencyInstance().format(balance))); // set amount colour if (balance < 0) item.txvBalance.setTextColor(app.res .getColor(R.color.color_negetive)); else item.txvBalance.setTextColor(app.res .getColor(R.color.color_positive)); // set image properties if (account.GUID.equalsIgnoreCase(currRootGUID)) item.btnExpand.setImageResource(R.drawable.list_expanded); else if (account.hasChildren) item.btnExpand.setImageResource(R.drawable.list_collapsed); // return return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { AccountItem item; Account account; // always create new view convertView = mInflater.inflate(R.layout.account_item, null); item = new AccountItem(); item.btnExpand = (ImageView) convertView .findViewById(R.id.acc_more); item.txvAccName = (TextView) convertView .findViewById(R.id.acc_name); item.txvBalance = (TextView) convertView .findViewById(R.id.acc_balance); convertView.setTag(item); // set values for account line item account = (Account) getItem(position); item.txvAccName.setText(account.name); Double balance; if (sp.getBoolean(app.res.getString(R.string.pref_include_subaccount_in_balance), false)) balance = account.balanceWithChildren; else balance = account.balance; item.txvBalance.setText(String.valueOf(NumberFormat .getCurrencyInstance().format(balance))); // set amount colour if (balance < 0) item.txvBalance.setTextColor(app.res .getColor(R.color.color_negative)); else item.txvBalance.setTextColor(app.res .getColor(R.color.color_positive)); // set image properties if (account.GUID.equalsIgnoreCase(currRootGUID)) item.btnExpand.setImageResource(R.drawable.list_expanded); else if (account.hasChildren) item.btnExpand.setImageResource(R.drawable.list_collapsed); // return return convertView; }
diff --git a/deployables/serviceengines/servicemix-cxf-se/src/test/java/org/apache/servicemix/cxfse/CxfSeClientProxyTest.java b/deployables/serviceengines/servicemix-cxf-se/src/test/java/org/apache/servicemix/cxfse/CxfSeClientProxyTest.java index d1d8c5b06..05780179f 100644 --- a/deployables/serviceengines/servicemix-cxf-se/src/test/java/org/apache/servicemix/cxfse/CxfSeClientProxyTest.java +++ b/deployables/serviceengines/servicemix-cxf-se/src/test/java/org/apache/servicemix/cxfse/CxfSeClientProxyTest.java @@ -1,143 +1,144 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicemix.cxfse; import java.io.File; import java.net.URL; import java.util.logging.Logger; import javax.jbi.messaging.InOut; import javax.naming.InitialContext; import javax.xml.namespace.QName; import junit.framework.TestCase; import org.apache.cxf.common.logging.LogUtils; import org.apache.servicemix.client.DefaultServiceMixClient; import org.apache.servicemix.jbi.container.JBIContainer; import org.apache.servicemix.jbi.jaxp.SourceTransformer; import org.apache.servicemix.jbi.jaxp.StringSource; public class CxfSeClientProxyTest extends TestCase { private static final Logger LOG = LogUtils.getL7dLogger(CxfSeClientProxyTest.class); private DefaultServiceMixClient client; private InOut io; private JBIContainer container; protected void setUp() throws Exception { container = new JBIContainer(); container.setUseMBeanServer(false); container.setCreateMBeanServer(false); container.setMonitorInstallationDirectory(false); container.setNamingContext(new InitialContext()); container.setEmbedded(true); container.init(); } public void testClientProxy() throws Exception { CxfSeComponent component = new CxfSeComponent(); container.activateComponent(component, "CxfSeComponent"); // Start container container.start(); // Deploy SU component.getServiceUnitManager().deploy("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); component.getServiceUnitManager().deploy("proxy", getServiceUnitPath("proxy")); component.getServiceUnitManager().init("proxy", getServiceUnitPath("proxy")); component.getServiceUnitManager().start("proxy"); //test redepoly su component.getServiceUnitManager().stop("target"); component.getServiceUnitManager().shutDown("target"); component.getServiceUnitManager().undeploy("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); client = new DefaultServiceMixClient(container); io = client.createInOutExchange(); io.setService(new QName("http://apache.org/hello_world_soap_http", "SOAPService")); io.setInterfaceName(new QName("http://apache.org/hello_world_soap_http", "Greeter")); io.setOperation(new QName("http://apache.org/hello_world_soap_http", "greetMe")); LOG.info("test clientProxy"); io.getInMessage().setContent(new StringSource( "<message xmlns='http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper'>" + "<part> " + "<greetMe xmlns='http://apache.org/hello_world_soap_http/types'><requestType>" + "ffang" + "</requestType></greetMe>" + "</part> " + "</message>")); client.sendSync(io); assertTrue(new SourceTransformer().contentToString( io.getOutMessage()).indexOf("Hello ffang 3") > 0); + client.done(io); // test restart component component.getServiceUnitManager().stop("target"); component.getServiceUnitManager().shutDown("target"); component.getServiceUnitManager().undeploy("target", getServiceUnitPath("proxytarget")); component.stop(); component.start(); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); client = new DefaultServiceMixClient(container); io = client.createInOutExchange(); io.setService(new QName("http://apache.org/hello_world_soap_http", "SOAPService")); io.setInterfaceName(new QName("http://apache.org/hello_world_soap_http", "Greeter")); io.setOperation(new QName("http://apache.org/hello_world_soap_http", "greetMe")); LOG.info("test clientProxy"); io.getInMessage().setContent(new StringSource( "<message xmlns='http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper'>" + "<part> " + "<greetMe xmlns='http://apache.org/hello_world_soap_http/types'><requestType>" + "ffang" + "</requestType></greetMe>" + "</part> " + "</message>")); client.sendSync(io); assertTrue(new SourceTransformer().contentToString( io.getOutMessage()).indexOf("Hello ffang 3") > 0); } protected void tearDown() throws Exception { if (container != null) { container.shutDown(); } } protected String getServiceUnitPath(String name) { URL url = getClass().getClassLoader().getResource("org/apache/servicemix/cxfse/" + name + "/xbean.xml"); File path = new File(url.getFile()); path = path.getParentFile(); return path.getAbsolutePath(); } }
true
true
public void testClientProxy() throws Exception { CxfSeComponent component = new CxfSeComponent(); container.activateComponent(component, "CxfSeComponent"); // Start container container.start(); // Deploy SU component.getServiceUnitManager().deploy("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); component.getServiceUnitManager().deploy("proxy", getServiceUnitPath("proxy")); component.getServiceUnitManager().init("proxy", getServiceUnitPath("proxy")); component.getServiceUnitManager().start("proxy"); //test redepoly su component.getServiceUnitManager().stop("target"); component.getServiceUnitManager().shutDown("target"); component.getServiceUnitManager().undeploy("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); client = new DefaultServiceMixClient(container); io = client.createInOutExchange(); io.setService(new QName("http://apache.org/hello_world_soap_http", "SOAPService")); io.setInterfaceName(new QName("http://apache.org/hello_world_soap_http", "Greeter")); io.setOperation(new QName("http://apache.org/hello_world_soap_http", "greetMe")); LOG.info("test clientProxy"); io.getInMessage().setContent(new StringSource( "<message xmlns='http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper'>" + "<part> " + "<greetMe xmlns='http://apache.org/hello_world_soap_http/types'><requestType>" + "ffang" + "</requestType></greetMe>" + "</part> " + "</message>")); client.sendSync(io); assertTrue(new SourceTransformer().contentToString( io.getOutMessage()).indexOf("Hello ffang 3") > 0); // test restart component component.getServiceUnitManager().stop("target"); component.getServiceUnitManager().shutDown("target"); component.getServiceUnitManager().undeploy("target", getServiceUnitPath("proxytarget")); component.stop(); component.start(); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); client = new DefaultServiceMixClient(container); io = client.createInOutExchange(); io.setService(new QName("http://apache.org/hello_world_soap_http", "SOAPService")); io.setInterfaceName(new QName("http://apache.org/hello_world_soap_http", "Greeter")); io.setOperation(new QName("http://apache.org/hello_world_soap_http", "greetMe")); LOG.info("test clientProxy"); io.getInMessage().setContent(new StringSource( "<message xmlns='http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper'>" + "<part> " + "<greetMe xmlns='http://apache.org/hello_world_soap_http/types'><requestType>" + "ffang" + "</requestType></greetMe>" + "</part> " + "</message>")); client.sendSync(io); assertTrue(new SourceTransformer().contentToString( io.getOutMessage()).indexOf("Hello ffang 3") > 0); }
public void testClientProxy() throws Exception { CxfSeComponent component = new CxfSeComponent(); container.activateComponent(component, "CxfSeComponent"); // Start container container.start(); // Deploy SU component.getServiceUnitManager().deploy("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); component.getServiceUnitManager().deploy("proxy", getServiceUnitPath("proxy")); component.getServiceUnitManager().init("proxy", getServiceUnitPath("proxy")); component.getServiceUnitManager().start("proxy"); //test redepoly su component.getServiceUnitManager().stop("target"); component.getServiceUnitManager().shutDown("target"); component.getServiceUnitManager().undeploy("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); client = new DefaultServiceMixClient(container); io = client.createInOutExchange(); io.setService(new QName("http://apache.org/hello_world_soap_http", "SOAPService")); io.setInterfaceName(new QName("http://apache.org/hello_world_soap_http", "Greeter")); io.setOperation(new QName("http://apache.org/hello_world_soap_http", "greetMe")); LOG.info("test clientProxy"); io.getInMessage().setContent(new StringSource( "<message xmlns='http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper'>" + "<part> " + "<greetMe xmlns='http://apache.org/hello_world_soap_http/types'><requestType>" + "ffang" + "</requestType></greetMe>" + "</part> " + "</message>")); client.sendSync(io); assertTrue(new SourceTransformer().contentToString( io.getOutMessage()).indexOf("Hello ffang 3") > 0); client.done(io); // test restart component component.getServiceUnitManager().stop("target"); component.getServiceUnitManager().shutDown("target"); component.getServiceUnitManager().undeploy("target", getServiceUnitPath("proxytarget")); component.stop(); component.start(); component.getServiceUnitManager().init("target", getServiceUnitPath("proxytarget")); component.getServiceUnitManager().start("target"); client = new DefaultServiceMixClient(container); io = client.createInOutExchange(); io.setService(new QName("http://apache.org/hello_world_soap_http", "SOAPService")); io.setInterfaceName(new QName("http://apache.org/hello_world_soap_http", "Greeter")); io.setOperation(new QName("http://apache.org/hello_world_soap_http", "greetMe")); LOG.info("test clientProxy"); io.getInMessage().setContent(new StringSource( "<message xmlns='http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper'>" + "<part> " + "<greetMe xmlns='http://apache.org/hello_world_soap_http/types'><requestType>" + "ffang" + "</requestType></greetMe>" + "</part> " + "</message>")); client.sendSync(io); assertTrue(new SourceTransformer().contentToString( io.getOutMessage()).indexOf("Hello ffang 3") > 0); }
diff --git a/servers/src/org/xtreemfs/new_mrc/operations/UpdateFileSizeOperation.java b/servers/src/org/xtreemfs/new_mrc/operations/UpdateFileSizeOperation.java index 3fa24a9f..04f04488 100644 --- a/servers/src/org/xtreemfs/new_mrc/operations/UpdateFileSizeOperation.java +++ b/servers/src/org/xtreemfs/new_mrc/operations/UpdateFileSizeOperation.java @@ -1,154 +1,160 @@ /* Copyright (c) 2008 Konrad-Zuse-Zentrum fuer Informationstechnik Berlin. This file is part of XtreemFS. XtreemFS is part of XtreemOS, a Linux-based Grid Operating System, see <http://www.xtreemos.eu> for more details. The XtreemOS project has been developed with the financial support of the European Commission's IST program under contract #FP6-033576. XtreemFS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. XtreemFS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XtreemFS. If not, see <http://www.gnu.org/licenses/>. */ /* * AUTHORS: Jan Stender (ZIB) */ package org.xtreemfs.new_mrc.operations; import org.xtreemfs.common.Capability; import org.xtreemfs.common.buffer.ReusableBuffer; import org.xtreemfs.common.logging.Logging; import org.xtreemfs.foundation.json.JSONParser; import org.xtreemfs.foundation.pinky.HTTPHeaders; import org.xtreemfs.new_mrc.ErrNo; import org.xtreemfs.new_mrc.ErrorRecord; import org.xtreemfs.new_mrc.MRCRequest; import org.xtreemfs.new_mrc.MRCRequestDispatcher; import org.xtreemfs.new_mrc.UserException; import org.xtreemfs.new_mrc.ErrorRecord.ErrorClass; import org.xtreemfs.new_mrc.dbaccess.AtomicDBUpdate; import org.xtreemfs.new_mrc.dbaccess.StorageManager; import org.xtreemfs.new_mrc.metadata.FileMetadata; /** * * @author stender */ public class UpdateFileSizeOperation extends MRCOperation { public static final String RPC_NAME = "updateFileSize"; public UpdateFileSizeOperation(MRCRequestDispatcher master) { super(master); } @Override public boolean hasArguments() { return false; } @Override public boolean isAuthRequired() { return true; } @Override public void startRequest(MRCRequest rq) { try { String capString = rq.getPinkyRequest().requestHeaders .getHeader(HTTPHeaders.HDR_XCAPABILITY); String newSizeString = rq.getPinkyRequest().requestHeaders .getHeader(HTTPHeaders.HDR_XNEWFILESIZE); if (capString == null) throw new UserException("missing " + HTTPHeaders.HDR_XCAPABILITY + " header"); if (newSizeString == null) throw new UserException("missing " + HTTPHeaders.HDR_XNEWFILESIZE + " header"); // create a capability object to verify the capability Capability cap = new Capability(capString, master.getConfig().getCapabilitySecret()); // check whether the received capability has a valid signature if (!cap.isValid()) throw new UserException(capString + " is invalid"); // parse volume and file ID from global file ID long fileId = 0; String volumeId = null; try { String globalFileId = cap.getFileId(); int i = globalFileId.indexOf(':'); volumeId = cap.getFileId().substring(0, i); fileId = Long.parseLong(cap.getFileId().substring(i + 1)); } catch (Exception exc) { throw new UserException("invalid global file ID: " + cap.getFileId() + "; expected pattern: <volume_ID>:<local_file_ID>"); } StorageManager sMan = master.getVolumeManager().getStorageManager(volumeId); FileMetadata file = sMan.getMetadata(fileId); if (file == null) throw new UserException(ErrNo.ENOENT, "file '" + fileId + "' does not exist"); int index = newSizeString.indexOf(','); if (index == -1) throw new UserException(ErrNo.EINVAL, "invalid " + HTTPHeaders.HDR_XNEWFILESIZE + " header"); // parse the file size and epoch number - long newFileSize = Long.parseLong(newSizeString.substring(1, index)); - int epochNo = Integer.parseInt(newSizeString.substring(index + 1, newSizeString - .length() - 1)); + long newFileSize = 0; + int epochNo = 0; + try { + newFileSize = Long.parseLong(newSizeString.substring(1, index)); + epochNo = Integer.parseInt(newSizeString.substring(index + 1, newSizeString + .length() - 1)); + } catch (NumberFormatException exc) { + throw new UserException("invalid file size/epoch: " + newSizeString); + } // FIXME: this line is needed due to a BUG in the client which // expects some useless return value rq.setData(ReusableBuffer.wrap(JSONParser.writeJSON(null).getBytes())); // discard outdated file size updates if (epochNo < file.getEpoch()) { finishRequest(rq); return; } // accept any file size in a new epoch but only larger file sizes in // the current epoch if (epochNo > file.getEpoch() || newFileSize > file.getSize()) { file.setSize(newFileSize); file.setEpoch(epochNo); AtomicDBUpdate update = sMan.createAtomicDBUpdate(master, rq); sMan.setMetadata(file, FileMetadata.FC_METADATA, update); // TODO: update POSIX time stamps // // update POSIX timestamps // MRCOpHelper.updateFileTimes(parentId, file, // !master.getConfig().isNoAtime(), false, // true, sMan, update); update.execute(); } else finishRequest(rq); } catch (UserException exc) { Logging.logMessage(Logging.LEVEL_TRACE, this, exc); finishRequest(rq, new ErrorRecord(ErrorClass.USER_EXCEPTION, exc.getErrno(), exc .getMessage(), exc)); } catch (Exception exc) { finishRequest(rq, new ErrorRecord(ErrorClass.INTERNAL_SERVER_ERROR, "an error has occurred", exc)); } } }
true
true
public void startRequest(MRCRequest rq) { try { String capString = rq.getPinkyRequest().requestHeaders .getHeader(HTTPHeaders.HDR_XCAPABILITY); String newSizeString = rq.getPinkyRequest().requestHeaders .getHeader(HTTPHeaders.HDR_XNEWFILESIZE); if (capString == null) throw new UserException("missing " + HTTPHeaders.HDR_XCAPABILITY + " header"); if (newSizeString == null) throw new UserException("missing " + HTTPHeaders.HDR_XNEWFILESIZE + " header"); // create a capability object to verify the capability Capability cap = new Capability(capString, master.getConfig().getCapabilitySecret()); // check whether the received capability has a valid signature if (!cap.isValid()) throw new UserException(capString + " is invalid"); // parse volume and file ID from global file ID long fileId = 0; String volumeId = null; try { String globalFileId = cap.getFileId(); int i = globalFileId.indexOf(':'); volumeId = cap.getFileId().substring(0, i); fileId = Long.parseLong(cap.getFileId().substring(i + 1)); } catch (Exception exc) { throw new UserException("invalid global file ID: " + cap.getFileId() + "; expected pattern: <volume_ID>:<local_file_ID>"); } StorageManager sMan = master.getVolumeManager().getStorageManager(volumeId); FileMetadata file = sMan.getMetadata(fileId); if (file == null) throw new UserException(ErrNo.ENOENT, "file '" + fileId + "' does not exist"); int index = newSizeString.indexOf(','); if (index == -1) throw new UserException(ErrNo.EINVAL, "invalid " + HTTPHeaders.HDR_XNEWFILESIZE + " header"); // parse the file size and epoch number long newFileSize = Long.parseLong(newSizeString.substring(1, index)); int epochNo = Integer.parseInt(newSizeString.substring(index + 1, newSizeString .length() - 1)); // FIXME: this line is needed due to a BUG in the client which // expects some useless return value rq.setData(ReusableBuffer.wrap(JSONParser.writeJSON(null).getBytes())); // discard outdated file size updates if (epochNo < file.getEpoch()) { finishRequest(rq); return; } // accept any file size in a new epoch but only larger file sizes in // the current epoch if (epochNo > file.getEpoch() || newFileSize > file.getSize()) { file.setSize(newFileSize); file.setEpoch(epochNo); AtomicDBUpdate update = sMan.createAtomicDBUpdate(master, rq); sMan.setMetadata(file, FileMetadata.FC_METADATA, update); // TODO: update POSIX time stamps // // update POSIX timestamps // MRCOpHelper.updateFileTimes(parentId, file, // !master.getConfig().isNoAtime(), false, // true, sMan, update); update.execute(); } else finishRequest(rq); } catch (UserException exc) { Logging.logMessage(Logging.LEVEL_TRACE, this, exc); finishRequest(rq, new ErrorRecord(ErrorClass.USER_EXCEPTION, exc.getErrno(), exc .getMessage(), exc)); } catch (Exception exc) { finishRequest(rq, new ErrorRecord(ErrorClass.INTERNAL_SERVER_ERROR, "an error has occurred", exc)); } }
public void startRequest(MRCRequest rq) { try { String capString = rq.getPinkyRequest().requestHeaders .getHeader(HTTPHeaders.HDR_XCAPABILITY); String newSizeString = rq.getPinkyRequest().requestHeaders .getHeader(HTTPHeaders.HDR_XNEWFILESIZE); if (capString == null) throw new UserException("missing " + HTTPHeaders.HDR_XCAPABILITY + " header"); if (newSizeString == null) throw new UserException("missing " + HTTPHeaders.HDR_XNEWFILESIZE + " header"); // create a capability object to verify the capability Capability cap = new Capability(capString, master.getConfig().getCapabilitySecret()); // check whether the received capability has a valid signature if (!cap.isValid()) throw new UserException(capString + " is invalid"); // parse volume and file ID from global file ID long fileId = 0; String volumeId = null; try { String globalFileId = cap.getFileId(); int i = globalFileId.indexOf(':'); volumeId = cap.getFileId().substring(0, i); fileId = Long.parseLong(cap.getFileId().substring(i + 1)); } catch (Exception exc) { throw new UserException("invalid global file ID: " + cap.getFileId() + "; expected pattern: <volume_ID>:<local_file_ID>"); } StorageManager sMan = master.getVolumeManager().getStorageManager(volumeId); FileMetadata file = sMan.getMetadata(fileId); if (file == null) throw new UserException(ErrNo.ENOENT, "file '" + fileId + "' does not exist"); int index = newSizeString.indexOf(','); if (index == -1) throw new UserException(ErrNo.EINVAL, "invalid " + HTTPHeaders.HDR_XNEWFILESIZE + " header"); // parse the file size and epoch number long newFileSize = 0; int epochNo = 0; try { newFileSize = Long.parseLong(newSizeString.substring(1, index)); epochNo = Integer.parseInt(newSizeString.substring(index + 1, newSizeString .length() - 1)); } catch (NumberFormatException exc) { throw new UserException("invalid file size/epoch: " + newSizeString); } // FIXME: this line is needed due to a BUG in the client which // expects some useless return value rq.setData(ReusableBuffer.wrap(JSONParser.writeJSON(null).getBytes())); // discard outdated file size updates if (epochNo < file.getEpoch()) { finishRequest(rq); return; } // accept any file size in a new epoch but only larger file sizes in // the current epoch if (epochNo > file.getEpoch() || newFileSize > file.getSize()) { file.setSize(newFileSize); file.setEpoch(epochNo); AtomicDBUpdate update = sMan.createAtomicDBUpdate(master, rq); sMan.setMetadata(file, FileMetadata.FC_METADATA, update); // TODO: update POSIX time stamps // // update POSIX timestamps // MRCOpHelper.updateFileTimes(parentId, file, // !master.getConfig().isNoAtime(), false, // true, sMan, update); update.execute(); } else finishRequest(rq); } catch (UserException exc) { Logging.logMessage(Logging.LEVEL_TRACE, this, exc); finishRequest(rq, new ErrorRecord(ErrorClass.USER_EXCEPTION, exc.getErrno(), exc .getMessage(), exc)); } catch (Exception exc) { finishRequest(rq, new ErrorRecord(ErrorClass.INTERNAL_SERVER_ERROR, "an error has occurred", exc)); } }
diff --git a/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/EclipseProxyGenerator.java b/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/EclipseProxyGenerator.java index f19e142b1..58e9a056d 100644 --- a/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/EclipseProxyGenerator.java +++ b/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/EclipseProxyGenerator.java @@ -1,313 +1,315 @@ /******************************************************************************* * Copyright (c) 2006-2012 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Berlin, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.resource.generators.util; import static org.emftext.sdk.codegen.composites.IClassNameConstants.ARRAY_LIST; import static org.emftext.sdk.codegen.composites.IClassNameConstants.LIST; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.COLLECTION; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.CONSTRAINT_STATUS; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.CORE_EXCEPTION; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.EMF_MODEL_VALIDATION_PLUGIN; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.EVALUATION_MODE; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_NOTIFICATION_IMPL; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_OBJECT; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.INTERNAL_E_OBJECT; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ITERATOR; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_BATCH_VALIDATOR; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_CONFIGURATION_ELEMENT; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_EXTENSION_REGISTRY; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_FILE; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_LIVE_VALIDATOR; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_RESOURCE; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_STATUS; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.MAP; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.MODEL_VALIDATION_SERVICE; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.NOTIFICATION; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.PLATFORM; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCES_PLUGIN; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE_FACTORY; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE_SET; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE_SET_IMPL; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.SET; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.URI; import org.emftext.sdk.OptionManager; import org.emftext.sdk.codegen.annotations.SyntaxDependent; import org.emftext.sdk.codegen.composites.JavaComposite; import org.emftext.sdk.codegen.parameters.ArtifactParameter; import org.emftext.sdk.codegen.resource.GenerationContext; import org.emftext.sdk.codegen.resource.generators.EProblemTypeGenerator; import org.emftext.sdk.codegen.resource.generators.JavaBaseGenerator; import org.emftext.sdk.concretesyntax.OptionTypes; @SyntaxDependent public class EclipseProxyGenerator extends JavaBaseGenerator<ArtifactParameter<GenerationContext>> { @Override public void generateJavaContents(JavaComposite sc) { sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.addJavadoc( "A utility class that bundles all dependencies to the Eclipse platform. " + "Clients of this class must check whether the Eclipse bundles are available " + "in the classpath. If they are not available, this class is not used, which " + "allows to run resource plug-in that are generated by EMFText in stand-alone mode. " + "In this case the EMF JARs are sufficient to parse and print resources." ); sc.add("public class " + getResourceClassName() + " {"); sc.addLineBreak(); OptionTypes option = OptionTypes.REMOVE_ECLIPSE_DEPENDENT_CODE; boolean removeEclipseDependentCode = OptionManager.INSTANCE.getBooleanOptionValue(getContext().getConcreteSyntax(), option); if (!removeEclipseDependentCode) { addMethods(sc); } else { sc.addComment("This class is intentionally left empty because option '" + option.getLiteral() + "' is set to true."); } sc.add("}"); } private void addMethods(JavaComposite sc) { addGetDefaultLoadOptionProviderExtensions(sc); addGetResourceFactoryExtensions(sc); addGetResourceMethod(sc); addCheckEMFValidationConstraints(sc); addCreateNotificationsMethod(sc); addCreateNotificationMethod(sc); addAddStatusMethod(sc); addGetPlatformResourceEncoding(sc); } private void addCreateNotificationMethod(JavaComposite sc) { sc.add("private void createNotification(" + E_OBJECT + " eObject, " + LIST + "<" + NOTIFICATION + "> notifications) {"); sc.add("if (eObject instanceof " + INTERNAL_E_OBJECT + ") {"); sc.add(INTERNAL_E_OBJECT + " internalEObject = (" + INTERNAL_E_OBJECT + ") eObject;"); sc.add(NOTIFICATION + " notification = new " + E_NOTIFICATION_IMPL + "(internalEObject, 0, " + E_NOTIFICATION_IMPL + ".NO_FEATURE_ID, null, null);"); sc.add("notifications.add(notification);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addCreateNotificationsMethod(JavaComposite sc) { sc.add("private " + COLLECTION + "<" + NOTIFICATION + "> createNotifications(" + E_OBJECT + " eObject) {"); sc.add(LIST + "<" + NOTIFICATION + "> notifications = new " + ARRAY_LIST + "<" + NOTIFICATION + ">();"); sc.add("createNotification(eObject, notifications);"); sc.add(ITERATOR + "<" + E_OBJECT + "> allContents = eObject.eAllContents();"); sc.add("while (allContents.hasNext()) {"); sc.add(E_OBJECT + " next = (" + E_OBJECT + ") allContents.next();"); sc.add("createNotification(next, notifications);"); sc.add("}"); sc.add("return notifications;"); sc.add("}"); sc.addLineBreak(); } private void addGetResourceFactoryExtensions(JavaComposite sc) { sc.addJavadoc( "Adds all registered resource factory extensions to the given map. " + "Such extensions can be used to register multiple resource factories " + "for the same file extension." ); sc.add("public void getResourceFactoryExtensions(" + MAP + "<String, " + RESOURCE_FACTORY + "> factories) {"); sc.add("if (" + PLATFORM + ".isRunning()) {"); sc.add(I_EXTENSION_REGISTRY + " extensionRegistry = " + PLATFORM + ".getExtensionRegistry();"); sc.add(I_CONFIGURATION_ELEMENT + " configurationElements[] = extensionRegistry.getConfigurationElementsFor(" + pluginActivatorClassName + ".EP_ADDITIONAL_EXTENSION_PARSER_ID);"); sc.add("for (" + I_CONFIGURATION_ELEMENT + " element : configurationElements) {"); sc.add("try {"); sc.add("String type = element.getAttribute(\"type\");"); sc.add(RESOURCE +".Factory factory = (" + RESOURCE + ".Factory) element.createExecutableExtension(\"class\");"); sc.add("if (type == null) {"); sc.add("type = \"\";"); sc.add("}"); sc.add(RESOURCE + ".Factory otherFactory = factories.get(type);"); sc.add("if (otherFactory != null) {"); sc.add("Class<?> superClass = factory.getClass().getSuperclass();"); sc.add("while(superClass != Object.class) {"); sc.add("if (superClass.equals(otherFactory.getClass())) {"); sc.add("factories.put(type, factory);"); sc.add("break;"); sc.add("}"); sc.add("superClass = superClass.getClass();"); sc.add("}"); sc.add("}"); sc.add("else {"); sc.add("factories.put(type, factory);"); sc.add("}"); sc.add("} catch (" + CORE_EXCEPTION + " ce) {"); sc.add("new " + runtimeUtilClassName + "().logError(\"Exception while getting default options.\", ce);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addGetDefaultLoadOptionProviderExtensions(JavaComposite sc) { sc.addJavadoc( "Adds all registered load option provider extension to the given map. " + "Load option providers can be used to set default options for loading resources " + "(e.g. input stream pre-processors)." ); sc.add("public void getDefaultLoadOptionProviderExtensions(" + MAP + "<Object, Object> optionsMap) {"); sc.add("if (" + PLATFORM + ".isRunning()) {"); sc.addComment("find default load option providers"); sc.add(I_EXTENSION_REGISTRY + " extensionRegistry = " + PLATFORM + ".getExtensionRegistry();"); sc.add(I_CONFIGURATION_ELEMENT + " configurationElements[] = extensionRegistry.getConfigurationElementsFor(" + pluginActivatorClassName + ".EP_DEFAULT_LOAD_OPTIONS_ID);"); sc.add("for (" + I_CONFIGURATION_ELEMENT + " element : configurationElements) {"); sc.add("try {"); sc.add(iOptionProviderClassName + " provider = (" + iOptionProviderClassName + ") element.createExecutableExtension(\"class\");"); sc.add("final " + MAP + "<?, ?> options = provider.getOptions();"); sc.add("final " + COLLECTION + "<?> keys = options.keySet();"); sc.add("for (Object key : keys) {"); sc.add(mapUtilClassName + ".putAndMergeKeys(optionsMap, key, options.get(key));"); sc.add("}"); sc.add("} catch (" + CORE_EXCEPTION + " ce) {"); sc.add("new " + runtimeUtilClassName + "().logError(\"Exception while getting default options.\", ce);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addGetResourceMethod(JavaComposite sc) { sc.addJavadoc("Gets the resource that is contained in the give file."); sc.add("public " + textResourceClassName + " getResource(" + I_FILE + " file) {"); sc.add(RESOURCE_SET + " rs = new " + RESOURCE_SET_IMPL + "();"); sc.add(RESOURCE + " resource = rs.getResource(" + URI + ".createPlatformResourceURI(file.getFullPath().toString(),true), true);"); sc.add("return (" + textResourceClassName + ") resource;"); sc.add("}"); sc.addLineBreak(); } private void addCheckEMFValidationConstraints(JavaComposite sc) { sc.addJavadoc( "Checks all registered EMF validation constraints. " + "Note: EMF validation does not work if OSGi is not running."); sc.add("@SuppressWarnings(\"restriction\")"); sc.addLineBreak(); sc.add("public void checkEMFValidationConstraints(" + iTextResourceClassName + " resource, " + E_OBJECT + " root, boolean includeBatchConstraints) {"); sc.addComment("The EMF validation framework code throws a NPE if the validation plug-in is not loaded. " + "This is a bug, which is fixed in the Helios release. Nonetheless, we need to catch the " + "exception here."); sc.add(runtimeUtilClassName + " runtimeUtil = new " + runtimeUtilClassName + "();"); sc.add("if (runtimeUtil.isEclipsePlatformRunning() && runtimeUtil.isEMFValidationAvailable()) {"); sc.addComment("The EMF validation framework code throws a NPE if the validation plug-in is not loaded. " + "This is a workaround for bug 322079."); sc.add("if (" + EMF_MODEL_VALIDATION_PLUGIN + ".getPlugin() != null) {"); sc.add("try {"); sc.add(MODEL_VALIDATION_SERVICE + " service = " + MODEL_VALIDATION_SERVICE + ".getInstance();"); sc.add(I_STATUS + " status;"); sc.addComment("Batch constraints are only evaluated if requested (e.g., when a resource is loaded for the first time)."); sc.add("if (includeBatchConstraints) {"); sc.add(I_BATCH_VALIDATOR + " validator = service.<" + E_OBJECT + ", " + I_BATCH_VALIDATOR + ">newValidator(" + EVALUATION_MODE + ".BATCH);"); sc.add("validator.setIncludeLiveConstraints(false);"); sc.add("status = validator.validate(root);"); sc.add("addStatus(status, resource, root, " + eProblemTypeClassName + "." + EProblemTypeGenerator.PROBLEM_TYPES.BATCH_CONSTRAINT_PROBLEM.name() + ");"); sc.add("}"); sc.addComment("Live constraints are always evaluated"); sc.add(I_LIVE_VALIDATOR + " validator = service.<" + NOTIFICATION + ", " + I_LIVE_VALIDATOR + ">newValidator(" + EVALUATION_MODE + ".LIVE);"); sc.add(COLLECTION + "<" + NOTIFICATION + "> notifications = createNotifications(root);"); sc.add("status = validator.validate(notifications);"); sc.add("addStatus(status, resource, root, " + eProblemTypeClassName + "." + EProblemTypeGenerator.PROBLEM_TYPES.LIVE_CONSTRAINT_PROBLEM.name() + ");"); sc.add("} catch (Throwable t) {"); sc.add("new " + runtimeUtilClassName + "().logError(\"Exception while checking contraints provided by EMF validator classes.\", t);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addAddStatusMethod(JavaComposite sc) { sc.add("public void addStatus(" + I_STATUS + " status, " + iTextResourceClassName + " resource, " + E_OBJECT + " root, " + eProblemTypeClassName + " problemType) {"); sc.add(LIST + "<" + E_OBJECT + "> causes = new " + ARRAY_LIST + "<" + E_OBJECT + ">();"); sc.add("causes.add(root);"); sc.add("if (status instanceof " + CONSTRAINT_STATUS + ") {"); sc.add(CONSTRAINT_STATUS + " constraintStatus = (" + CONSTRAINT_STATUS + ") status;"); sc.add(SET + "<" + E_OBJECT + "> resultLocus = constraintStatus.getResultLocus();"); sc.add("causes.clear();"); sc.add("causes.addAll(resultLocus);"); sc.add("}"); sc.add(I_STATUS + "[] children = status.getChildren();"); sc.add("boolean hasChildren = children != null && children.length > 0;"); sc.addComment("Ignore composite status objects that have children. " + "The actual status information is then contained in the child objects."); sc.add("if (!status.isMultiStatus() || !hasChildren) {"); sc.add("int severity = status.getSeverity();"); sc.add("if (severity == " + I_STATUS + ".ERROR) {"); sc.add("for (" + E_OBJECT + " cause : causes) {"); sc.add("resource.addError(status.getMessage(), problemType, cause);"); sc.add("}"); sc.add("}"); sc.add("if (severity == " + I_STATUS + ".WARNING) {"); sc.add("for (" + E_OBJECT + " cause : causes) {"); sc.add("resource.addWarning(status.getMessage(), problemType, cause);"); sc.add("}"); sc.add("}"); sc.add("}"); + sc.add("if (children != null) {"); sc.add("for (" + I_STATUS + " child : children) {"); sc.add("addStatus(child, resource, root, problemType);"); sc.add("}"); sc.add("}"); + sc.add("}"); sc.addLineBreak(); } private void addGetPlatformResourceEncoding(JavaComposite sc) { sc.addJavadoc( "Returns the encoding for this resource that is specified in the " + "workspace file properties or determined by the default workspace " + "encoding in Eclipse." ); sc.add("public String getPlatformResourceEncoding(" + URI +" uri) {"); sc.addComment("We can't determine the encoding if the platform is not running."); sc.add("if (!new " + runtimeUtilClassName + "().isEclipsePlatformRunning()) {"); sc.add("return null;"); sc.add("}"); sc.add("if (uri != null && uri.isPlatform()) {"); sc.add("String platformString = uri.toPlatformString(true);"); sc.add(I_RESOURCE + " platformResource = " + RESOURCES_PLUGIN + ".getWorkspace().getRoot().findMember(platformString);"); sc.add("if (platformResource instanceof " + I_FILE + ") {"); sc.add(I_FILE + " file = (" + I_FILE + ") platformResource;"); sc.add("try {"); sc.add("return file.getCharset();"); sc.add("} catch (" + CORE_EXCEPTION + " ce) {"); sc.add("new " + runtimeUtilClassName + "().logWarning(\"Could not determine encoding of platform resource: \" + uri.toString(), ce);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); } }
false
true
private void addAddStatusMethod(JavaComposite sc) { sc.add("public void addStatus(" + I_STATUS + " status, " + iTextResourceClassName + " resource, " + E_OBJECT + " root, " + eProblemTypeClassName + " problemType) {"); sc.add(LIST + "<" + E_OBJECT + "> causes = new " + ARRAY_LIST + "<" + E_OBJECT + ">();"); sc.add("causes.add(root);"); sc.add("if (status instanceof " + CONSTRAINT_STATUS + ") {"); sc.add(CONSTRAINT_STATUS + " constraintStatus = (" + CONSTRAINT_STATUS + ") status;"); sc.add(SET + "<" + E_OBJECT + "> resultLocus = constraintStatus.getResultLocus();"); sc.add("causes.clear();"); sc.add("causes.addAll(resultLocus);"); sc.add("}"); sc.add(I_STATUS + "[] children = status.getChildren();"); sc.add("boolean hasChildren = children != null && children.length > 0;"); sc.addComment("Ignore composite status objects that have children. " + "The actual status information is then contained in the child objects."); sc.add("if (!status.isMultiStatus() || !hasChildren) {"); sc.add("int severity = status.getSeverity();"); sc.add("if (severity == " + I_STATUS + ".ERROR) {"); sc.add("for (" + E_OBJECT + " cause : causes) {"); sc.add("resource.addError(status.getMessage(), problemType, cause);"); sc.add("}"); sc.add("}"); sc.add("if (severity == " + I_STATUS + ".WARNING) {"); sc.add("for (" + E_OBJECT + " cause : causes) {"); sc.add("resource.addWarning(status.getMessage(), problemType, cause);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("for (" + I_STATUS + " child : children) {"); sc.add("addStatus(child, resource, root, problemType);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); }
private void addAddStatusMethod(JavaComposite sc) { sc.add("public void addStatus(" + I_STATUS + " status, " + iTextResourceClassName + " resource, " + E_OBJECT + " root, " + eProblemTypeClassName + " problemType) {"); sc.add(LIST + "<" + E_OBJECT + "> causes = new " + ARRAY_LIST + "<" + E_OBJECT + ">();"); sc.add("causes.add(root);"); sc.add("if (status instanceof " + CONSTRAINT_STATUS + ") {"); sc.add(CONSTRAINT_STATUS + " constraintStatus = (" + CONSTRAINT_STATUS + ") status;"); sc.add(SET + "<" + E_OBJECT + "> resultLocus = constraintStatus.getResultLocus();"); sc.add("causes.clear();"); sc.add("causes.addAll(resultLocus);"); sc.add("}"); sc.add(I_STATUS + "[] children = status.getChildren();"); sc.add("boolean hasChildren = children != null && children.length > 0;"); sc.addComment("Ignore composite status objects that have children. " + "The actual status information is then contained in the child objects."); sc.add("if (!status.isMultiStatus() || !hasChildren) {"); sc.add("int severity = status.getSeverity();"); sc.add("if (severity == " + I_STATUS + ".ERROR) {"); sc.add("for (" + E_OBJECT + " cause : causes) {"); sc.add("resource.addError(status.getMessage(), problemType, cause);"); sc.add("}"); sc.add("}"); sc.add("if (severity == " + I_STATUS + ".WARNING) {"); sc.add("for (" + E_OBJECT + " cause : causes) {"); sc.add("resource.addWarning(status.getMessage(), problemType, cause);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("if (children != null) {"); sc.add("for (" + I_STATUS + " child : children) {"); sc.add("addStatus(child, resource, root, problemType);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.addLineBreak(); }
diff --git a/ttt2/src/java/capstone/server/util/GameRecorder.java b/ttt2/src/java/capstone/server/util/GameRecorder.java index 66027e4..09ebfac 100644 --- a/ttt2/src/java/capstone/server/util/GameRecorder.java +++ b/ttt2/src/java/capstone/server/util/GameRecorder.java @@ -1,71 +1,71 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package capstone.server.util; import capstone.player.GameRecord; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; public class GameRecorder { private static Map<String, List<String>> gameIDs = new ConcurrentHashMap<String, List<String>>(); //PlayerName -> GameID private static Map<String, GameRecord> players = new ConcurrentHashMap<String, GameRecord>(); //GameID -> GameRecord public static void record(String gameID, String player, String coords) { if (!gameIDs.containsKey(player)) { gameIDs.put(player, new ArrayList<String>()); //gameIDs.get(player).add(gameID); } if (gameIDs.get(player).indexOf(gameID) == -1) { GameRecord game; if(players.get(gameID) == null){ game = new GameRecord(); gameIDs.get(player).add(gameID); } else { game = players.get(gameID); } game.putCoords(coords); if (players.get(gameID) != game) { players.put(gameID, game); } - gameIDs.get(player).add(gameID); + //gameIDs.get(player).add(gameID); } else { players.get(gameID).putCoords(coords); } GameRecord game = players.get(gameID); if (game.getPlayer1().equals("")) { game.setGameID(gameID); game.setPlayer1(player); } else if (!player.equals(game.getPlayer1()) && game.getPlayer2().equals("")) { game.setPlayer2(player); } } public static List<String> getGames(String player){ List<String> games = gameIDs.get(player); List<String> gamePlayers = new ArrayList(); for (String e: games) { GameRecord temp = players.get(e); String playerTemp = "{" + "\"gid\": \""+temp.getGameID()+ "\" , \"p1\" :\"" + temp.getPlayer1() + "\" , \"p2\" :\"" + temp.getPlayer2()+"\"}"; gamePlayers.add(playerTemp); } return gamePlayers; } public static List<String> getGameCoords (String gameID){ GameRecord record = players.get(gameID); List temp = record.getCoords(); return temp; } }
true
true
public static void record(String gameID, String player, String coords) { if (!gameIDs.containsKey(player)) { gameIDs.put(player, new ArrayList<String>()); //gameIDs.get(player).add(gameID); } if (gameIDs.get(player).indexOf(gameID) == -1) { GameRecord game; if(players.get(gameID) == null){ game = new GameRecord(); gameIDs.get(player).add(gameID); } else { game = players.get(gameID); } game.putCoords(coords); if (players.get(gameID) != game) { players.put(gameID, game); } gameIDs.get(player).add(gameID); } else { players.get(gameID).putCoords(coords); } GameRecord game = players.get(gameID); if (game.getPlayer1().equals("")) { game.setGameID(gameID); game.setPlayer1(player); } else if (!player.equals(game.getPlayer1()) && game.getPlayer2().equals("")) { game.setPlayer2(player); } }
public static void record(String gameID, String player, String coords) { if (!gameIDs.containsKey(player)) { gameIDs.put(player, new ArrayList<String>()); //gameIDs.get(player).add(gameID); } if (gameIDs.get(player).indexOf(gameID) == -1) { GameRecord game; if(players.get(gameID) == null){ game = new GameRecord(); gameIDs.get(player).add(gameID); } else { game = players.get(gameID); } game.putCoords(coords); if (players.get(gameID) != game) { players.put(gameID, game); } //gameIDs.get(player).add(gameID); } else { players.get(gameID).putCoords(coords); } GameRecord game = players.get(gameID); if (game.getPlayer1().equals("")) { game.setGameID(gameID); game.setPlayer1(player); } else if (!player.equals(game.getPlayer1()) && game.getPlayer2().equals("")) { game.setPlayer2(player); } }
diff --git a/src/com/essiembre/eclipse/rbe/ui/editor/i18n/BundleEntryComposite.java b/src/com/essiembre/eclipse/rbe/ui/editor/i18n/BundleEntryComposite.java index f8158b1..e4a9b3b 100644 --- a/src/com/essiembre/eclipse/rbe/ui/editor/i18n/BundleEntryComposite.java +++ b/src/com/essiembre/eclipse/rbe/ui/editor/i18n/BundleEntryComposite.java @@ -1,439 +1,439 @@ /* * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc. * * This file is part of Essiembre ResourceBundle Editor. * * Essiembre ResourceBundle Editor is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Essiembre ResourceBundle Editor is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Essiembre ResourceBundle Editor; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package com.essiembre.eclipse.rbe.ui.editor.i18n; import java.util.Iterator; import java.util.Locale; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.texteditor.ITextEditor; import com.essiembre.eclipse.rbe.RBEPlugin; import com.essiembre.eclipse.rbe.model.bundle.BundleEntry; import com.essiembre.eclipse.rbe.model.bundle.BundleGroup; import com.essiembre.eclipse.rbe.model.bundle.visitors.DuplicateValuesVisitor; import com.essiembre.eclipse.rbe.model.bundle.visitors.SimilarValuesVisitor; import com.essiembre.eclipse.rbe.model.utils.LevenshteinDistanceAnalyzer; import com.essiembre.eclipse.rbe.model.utils.ProximityAnalyzer; import com.essiembre.eclipse.rbe.model.utils.WordCountAnalyzer; import com.essiembre.eclipse.rbe.model.workbench.RBEPreferences; import com.essiembre.eclipse.rbe.ui.UIUtils; import com.essiembre.eclipse.rbe.ui.editor.ResourceBundleEditor; import com.essiembre.eclipse.rbe.ui.editor.resources.ResourceManager; import com.essiembre.eclipse.rbe.ui.editor.resources.SourceEditor; /** * Represents a data entry section for a bundle entry. * @author Pascal Essiembre ([email protected]) * @version $Author$ $Revision$ $Date$ */ public class BundleEntryComposite extends Composite { /*default*/ final ResourceManager resourceManager; /*default*/ final Locale locale; private final Font boldFont; private final Font smallFont; /*default*/ Text textBox; private Button commentedCheckbox; private Button gotoButton; private Button duplButton; private Button simButton; /*default*/ String activeKey; /*default*/ String textBeforeUpdate; /*default*/ DuplicateValuesVisitor duplVisitor; /*default*/ SimilarValuesVisitor similarVisitor; /** * Constructor. * @param parent parent composite * @param resourceManager resource manager * @param locale locale for this bundle entry */ public BundleEntryComposite( final Composite parent, final ResourceManager resourceManager, final Locale locale) { super(parent, SWT.NONE); this.resourceManager = resourceManager; this.locale = locale; this.boldFont = UIUtils.createFont(this, SWT.BOLD, 0); this.smallFont = UIUtils.createFont(SWT.NONE, -1); GridLayout gridLayout = new GridLayout(1, false); gridLayout.horizontalSpacing = 0; gridLayout.verticalSpacing = 2; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; setLayout(gridLayout); setLayoutData(new GridData(GridData.FILL_BOTH)); createLabelRow(); createTextRow(); } /** * Update bundles if the value of the active key changed. */ public void updateBundleOnChanges(){ if (activeKey != null) { BundleGroup bundleGroup = resourceManager.getBundleGroup(); BundleEntry entry = bundleGroup.getBundleEntry(locale, activeKey); boolean commentedSelected = commentedCheckbox.getSelection(); if (entry == null || !textBox.getText().equals(entry.getValue()) || entry.isCommented() != commentedSelected) { String comment = null; if (entry != null) { comment = entry.getComment(); } bundleGroup.addBundleEntry(locale, new BundleEntry( activeKey, textBox.getText(), comment, commentedSelected)); } } } /** * @see org.eclipse.swt.widgets.Widget#dispose() */ public void dispose() { super.dispose(); boldFont.dispose(); smallFont.dispose(); } /** * Refreshes the text field value with value matching given key. * @param key key used to grab value */ public void refresh(String key) { activeKey = key; BundleGroup bundleGroup = resourceManager.getBundleGroup(); if (key != null && bundleGroup.isKey(key)) { BundleEntry bundleEntry = bundleGroup.getBundleEntry(locale, key); SourceEditor sourceEditor = resourceManager.getSourceEditor(locale); if (bundleEntry == null) { textBox.setText(""); //$NON-NLS-1$ commentedCheckbox.setSelection(false); } else { commentedCheckbox.setSelection(bundleEntry.isCommented()); textBox.setText(bundleEntry.getValue()); } commentedCheckbox.setEnabled(!sourceEditor.isReadOnly()); textBox.setEnabled(!sourceEditor.isReadOnly()); gotoButton.setEnabled(true); if (RBEPreferences.getReportDuplicateValues()) { findDuplicates(bundleEntry); } else { duplVisitor = null; } if (RBEPreferences.getReportSimilarValues()) { findSimilar(bundleEntry); } else { similarVisitor = null; } } else { commentedCheckbox.setSelection(false); commentedCheckbox.setEnabled(false); textBox.setText(""); //$NON-NLS-1$ textBox.setEnabled(false); gotoButton.setEnabled(false); duplButton.setVisible(false); simButton.setVisible(false); } resetCommented(); } private void findSimilar(BundleEntry bundleEntry) { ProximityAnalyzer analyzer; if (RBEPreferences.getReportSimilarValuesLevensthein()) { analyzer = LevenshteinDistanceAnalyzer.getInstance(); } else { analyzer = WordCountAnalyzer.getInstance(); } BundleGroup bundleGroup = resourceManager.getBundleGroup(); if (similarVisitor == null) { similarVisitor = new SimilarValuesVisitor(); } similarVisitor.setProximityAnalyzer(analyzer); similarVisitor.clear(); bundleGroup.getBundle(locale).accept(similarVisitor, bundleEntry); if (duplVisitor != null) { similarVisitor.getSimilars().removeAll(duplVisitor.getDuplicates()); } simButton.setVisible(similarVisitor.getSimilars().size() > 0); } private void findDuplicates(BundleEntry bundleEntry) { BundleGroup bundleGroup = resourceManager.getBundleGroup(); if (duplVisitor == null) { duplVisitor = new DuplicateValuesVisitor(); } duplVisitor.clear(); bundleGroup.getBundle(locale).accept(duplVisitor, bundleEntry); duplButton.setVisible(duplVisitor.getDuplicates().size() > 0); } /** * Creates the text field label, icon, and commented check box. */ private void createLabelRow() { Composite labelComposite = new Composite(this, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 6; gridLayout.horizontalSpacing = 5; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; labelComposite.setLayout(gridLayout); labelComposite.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); // Locale text Label txtLabel = new Label(labelComposite, SWT.NONE); txtLabel.setText(" " + //$NON-NLS-1$ UIUtils.getDisplayName(locale) + " "); //$NON-NLS-1$ txtLabel.setFont(boldFont); GridData gridData = new GridData(); // Similar button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gridData.grabExcessHorizontalSpace = true; simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); simButton.setImage(UIUtils.getImage("similar.gif")); //$NON-NLS-1$ simButton.setLayoutData(gridData); simButton.setVisible(false); simButton.setToolTipText( RBEPlugin.getString("value.similar.tooltip")); //$NON-NLS-1$ simButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.similar.head"); //$NON-NLS-1$ String body = RBEPlugin.getString( "dialog.similar.body", activeKey, //$NON-NLS-1$ UIUtils.getDisplayName(locale)); - body += "\":\n\n"; //$NON-NLS-1$ + body += "\n\n"; //$NON-NLS-1$ for (Iterator iter = similarVisitor.getSimilars().iterator(); iter.hasNext();) { body += " " //$NON-NLS-1$ + ((BundleEntry) iter.next()).getKey() + "\n"; //$NON-NLS-1$ } MessageDialog.openInformation(getShell(), head, body); } }); // Duplicate button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); duplButton.setImage(UIUtils.getImage("duplicate.gif")); //$NON-NLS-1$ duplButton.setLayoutData(gridData); duplButton.setVisible(false); duplButton.setToolTipText( RBEPlugin.getString("value.duplicate.tooltip")); //$NON-NLS-1$ duplButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.identical.head"); //$NON-NLS-1$ String body = RBEPlugin.getString( "dialog.identical.body", activeKey, //$NON-NLS-1$ UIUtils.getDisplayName(locale)); - body += "\":\n\n"; //$NON-NLS-1$ + body += "\n\n"; //$NON-NLS-1$ for (Iterator iter = duplVisitor.getDuplicates().iterator(); iter.hasNext();) { body += " " //$NON-NLS-1$ + ((BundleEntry) iter.next()).getKey() + "\n"; //$NON-NLS-1$ } MessageDialog.openInformation(getShell(), head, body); } }); // Commented checkbox gridData = new GridData(); gridData.horizontalAlignment = GridData.END; //gridData.grabExcessHorizontalSpace = true; commentedCheckbox = new Button( labelComposite, SWT.CHECK); commentedCheckbox.setText("#"); //$NON-NLS-1$ commentedCheckbox.setFont(smallFont); commentedCheckbox.setLayoutData(gridData); commentedCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { resetCommented(); updateBundleOnChanges(); } }); commentedCheckbox.setEnabled(false); // Country flag gridData = new GridData(); gridData.horizontalAlignment = GridData.END; Label imgLabel = new Label(labelComposite, SWT.NONE); imgLabel.setLayoutData(gridData); imgLabel.setImage(loadCountryIcon(locale)); // Goto button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gotoButton = new Button( labelComposite, SWT.ARROW | SWT.RIGHT); gotoButton.setToolTipText( RBEPlugin.getString("value.goto.tooltip")); //$NON-NLS-1$ gotoButton.setEnabled(false); gotoButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); Object activeEditor = editor.getSite().getPage().getActiveEditor(); if (activeEditor instanceof ResourceBundleEditor) { ((ResourceBundleEditor) activeEditor).setActivePage(locale); } } }); gotoButton.setLayoutData(gridData); } /** * Creates the text row. */ private void createTextRow() { textBox = new Text(this, SWT.MULTI | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); textBox.setEnabled(false); GridData gridData = new GridData(); gridData.verticalAlignment = GridData.FILL; gridData.grabExcessVerticalSpace = true; gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; textBox.setLayoutData(gridData); textBox.addFocusListener(new FocusListener() { public void focusGained(FocusEvent event) { textBeforeUpdate = textBox.getText(); } public void focusLost(FocusEvent event) { updateBundleOnChanges(); } }); //TODO add a preference property listener and add/remove this listener textBox.addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent event) { if (!RBEPreferences.getFieldTabInserts() && event.character == SWT.TAB) { event.doit = true; } } }); textBox.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { Text eventBox = (Text) event.widget; final ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); // Text field has changed: make editor dirty if not already if (textBeforeUpdate != null && !textBeforeUpdate.equals(eventBox.getText())) { // Make the editor dirty if not already. If it is, // we wait until field focus lost (or save) to // update it completely. if (!editor.isDirty()) { int caretPosition = eventBox.getCaretPosition(); updateBundleOnChanges(); eventBox.setSelection(caretPosition); } // Text field is the same as original (make non-dirty) } else { if (editor.isDirty()) { getShell().getDisplay().asyncExec(new Runnable() { public void run() { editor.doRevertToSaved(); } }); } } } }); } /** * Loads country icon based on locale country. * @param countryLocale the locale on which to grab the country * @return an image, or <code>null</code> if no match could be made */ private Image loadCountryIcon(Locale countryLocale) { Image image = null; String countryCode = null; if (countryLocale != null && countryLocale.getCountry() != null) { countryCode = countryLocale.getCountry().toLowerCase(); } if (countryCode != null && countryCode.length() > 0) { String imageName = "countries/" + //$NON-NLS-1$ countryCode.toLowerCase() + ".gif"; //$NON-NLS-1$ image = UIUtils.getImage(imageName); } if (image == null) { image = UIUtils.getImage("countries/blank.gif"); //$NON-NLS-1$ } return image; } /*default*/ void resetCommented() { if (commentedCheckbox.getSelection()) { commentedCheckbox.setToolTipText( RBEPlugin.getString("value.uncomment.tooltip"));//$NON-NLS-1$ textBox.setForeground( getDisplay().getSystemColor(SWT.COLOR_GRAY)); } else { commentedCheckbox.setToolTipText( RBEPlugin.getString("value.comment.tooltip"));//$NON-NLS-1$ textBox.setForeground(null); } } }
false
true
private void createLabelRow() { Composite labelComposite = new Composite(this, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 6; gridLayout.horizontalSpacing = 5; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; labelComposite.setLayout(gridLayout); labelComposite.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); // Locale text Label txtLabel = new Label(labelComposite, SWT.NONE); txtLabel.setText(" " + //$NON-NLS-1$ UIUtils.getDisplayName(locale) + " "); //$NON-NLS-1$ txtLabel.setFont(boldFont); GridData gridData = new GridData(); // Similar button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gridData.grabExcessHorizontalSpace = true; simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); simButton.setImage(UIUtils.getImage("similar.gif")); //$NON-NLS-1$ simButton.setLayoutData(gridData); simButton.setVisible(false); simButton.setToolTipText( RBEPlugin.getString("value.similar.tooltip")); //$NON-NLS-1$ simButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.similar.head"); //$NON-NLS-1$ String body = RBEPlugin.getString( "dialog.similar.body", activeKey, //$NON-NLS-1$ UIUtils.getDisplayName(locale)); body += "\":\n\n"; //$NON-NLS-1$ for (Iterator iter = similarVisitor.getSimilars().iterator(); iter.hasNext();) { body += " " //$NON-NLS-1$ + ((BundleEntry) iter.next()).getKey() + "\n"; //$NON-NLS-1$ } MessageDialog.openInformation(getShell(), head, body); } }); // Duplicate button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); duplButton.setImage(UIUtils.getImage("duplicate.gif")); //$NON-NLS-1$ duplButton.setLayoutData(gridData); duplButton.setVisible(false); duplButton.setToolTipText( RBEPlugin.getString("value.duplicate.tooltip")); //$NON-NLS-1$ duplButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.identical.head"); //$NON-NLS-1$ String body = RBEPlugin.getString( "dialog.identical.body", activeKey, //$NON-NLS-1$ UIUtils.getDisplayName(locale)); body += "\":\n\n"; //$NON-NLS-1$ for (Iterator iter = duplVisitor.getDuplicates().iterator(); iter.hasNext();) { body += " " //$NON-NLS-1$ + ((BundleEntry) iter.next()).getKey() + "\n"; //$NON-NLS-1$ } MessageDialog.openInformation(getShell(), head, body); } }); // Commented checkbox gridData = new GridData(); gridData.horizontalAlignment = GridData.END; //gridData.grabExcessHorizontalSpace = true; commentedCheckbox = new Button( labelComposite, SWT.CHECK); commentedCheckbox.setText("#"); //$NON-NLS-1$ commentedCheckbox.setFont(smallFont); commentedCheckbox.setLayoutData(gridData); commentedCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { resetCommented(); updateBundleOnChanges(); } }); commentedCheckbox.setEnabled(false); // Country flag gridData = new GridData(); gridData.horizontalAlignment = GridData.END; Label imgLabel = new Label(labelComposite, SWT.NONE); imgLabel.setLayoutData(gridData); imgLabel.setImage(loadCountryIcon(locale)); // Goto button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gotoButton = new Button( labelComposite, SWT.ARROW | SWT.RIGHT); gotoButton.setToolTipText( RBEPlugin.getString("value.goto.tooltip")); //$NON-NLS-1$ gotoButton.setEnabled(false); gotoButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); Object activeEditor = editor.getSite().getPage().getActiveEditor(); if (activeEditor instanceof ResourceBundleEditor) { ((ResourceBundleEditor) activeEditor).setActivePage(locale); } } }); gotoButton.setLayoutData(gridData); }
private void createLabelRow() { Composite labelComposite = new Composite(this, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 6; gridLayout.horizontalSpacing = 5; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; labelComposite.setLayout(gridLayout); labelComposite.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); // Locale text Label txtLabel = new Label(labelComposite, SWT.NONE); txtLabel.setText(" " + //$NON-NLS-1$ UIUtils.getDisplayName(locale) + " "); //$NON-NLS-1$ txtLabel.setFont(boldFont); GridData gridData = new GridData(); // Similar button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gridData.grabExcessHorizontalSpace = true; simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); simButton.setImage(UIUtils.getImage("similar.gif")); //$NON-NLS-1$ simButton.setLayoutData(gridData); simButton.setVisible(false); simButton.setToolTipText( RBEPlugin.getString("value.similar.tooltip")); //$NON-NLS-1$ simButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.similar.head"); //$NON-NLS-1$ String body = RBEPlugin.getString( "dialog.similar.body", activeKey, //$NON-NLS-1$ UIUtils.getDisplayName(locale)); body += "\n\n"; //$NON-NLS-1$ for (Iterator iter = similarVisitor.getSimilars().iterator(); iter.hasNext();) { body += " " //$NON-NLS-1$ + ((BundleEntry) iter.next()).getKey() + "\n"; //$NON-NLS-1$ } MessageDialog.openInformation(getShell(), head, body); } }); // Duplicate button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); duplButton.setImage(UIUtils.getImage("duplicate.gif")); //$NON-NLS-1$ duplButton.setLayoutData(gridData); duplButton.setVisible(false); duplButton.setToolTipText( RBEPlugin.getString("value.duplicate.tooltip")); //$NON-NLS-1$ duplButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.identical.head"); //$NON-NLS-1$ String body = RBEPlugin.getString( "dialog.identical.body", activeKey, //$NON-NLS-1$ UIUtils.getDisplayName(locale)); body += "\n\n"; //$NON-NLS-1$ for (Iterator iter = duplVisitor.getDuplicates().iterator(); iter.hasNext();) { body += " " //$NON-NLS-1$ + ((BundleEntry) iter.next()).getKey() + "\n"; //$NON-NLS-1$ } MessageDialog.openInformation(getShell(), head, body); } }); // Commented checkbox gridData = new GridData(); gridData.horizontalAlignment = GridData.END; //gridData.grabExcessHorizontalSpace = true; commentedCheckbox = new Button( labelComposite, SWT.CHECK); commentedCheckbox.setText("#"); //$NON-NLS-1$ commentedCheckbox.setFont(smallFont); commentedCheckbox.setLayoutData(gridData); commentedCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { resetCommented(); updateBundleOnChanges(); } }); commentedCheckbox.setEnabled(false); // Country flag gridData = new GridData(); gridData.horizontalAlignment = GridData.END; Label imgLabel = new Label(labelComposite, SWT.NONE); imgLabel.setLayoutData(gridData); imgLabel.setImage(loadCountryIcon(locale)); // Goto button gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gotoButton = new Button( labelComposite, SWT.ARROW | SWT.RIGHT); gotoButton.setToolTipText( RBEPlugin.getString("value.goto.tooltip")); //$NON-NLS-1$ gotoButton.setEnabled(false); gotoButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); Object activeEditor = editor.getSite().getPage().getActiveEditor(); if (activeEditor instanceof ResourceBundleEditor) { ((ResourceBundleEditor) activeEditor).setActivePage(locale); } } }); gotoButton.setLayoutData(gridData); }
diff --git a/src/watson/glen/pseudocode/constructs/MethodSignature.java b/src/watson/glen/pseudocode/constructs/MethodSignature.java index 0ec0501..7dddc62 100644 --- a/src/watson/glen/pseudocode/constructs/MethodSignature.java +++ b/src/watson/glen/pseudocode/constructs/MethodSignature.java @@ -1,93 +1,93 @@ package watson.glen.pseudocode.constructs; import java.util.LinkedList; import java.util.List; public class MethodSignature { private AccessModifier modifier; private boolean isStatic; private String returnType; private String methodName; private List<VariableDeclaration> parameters; public MethodSignature(AccessModifier modifier, boolean isStatic, String returnType, String methodName, List<VariableDeclaration> parameters) { super(); this.modifier = modifier; this.isStatic = isStatic; this.returnType = returnType; this.methodName = methodName; this.parameters = parameters; } public MethodSignature(AccessModifier modifier, boolean isStatic, String returnType, String methodName) { super(); this.modifier = modifier; this.isStatic = isStatic; this.returnType = returnType; this.methodName = methodName; this.parameters = new LinkedList<>(); } public AccessModifier getModifier() { return modifier; } public void setModifier(AccessModifier modifier) { this.modifier = modifier; } public boolean isStatic() { return isStatic; } public void setStatic(boolean isStatic) { this.isStatic = isStatic; } public String getReturnType() { return returnType; } public void setReturnType(String returnType) { this.returnType = returnType; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public List<VariableDeclaration> getParameters() { return parameters; } public void setParameters(List<VariableDeclaration> parameters) { this.parameters = parameters; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\t"); sb.append(modifier); if(isStatic) { sb.append("static "); } sb.append(returnType); sb.append(" "); sb.append(methodName); sb.append("("); int beforeLength = sb.length(); sb.append(parameters); sb.delete(beforeLength, beforeLength+1); - sb.delete(sb.length()-2, sb.length()); + sb.delete(sb.length()-1, sb.length()); sb.append(")"); return sb.toString(); } }
true
true
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\t"); sb.append(modifier); if(isStatic) { sb.append("static "); } sb.append(returnType); sb.append(" "); sb.append(methodName); sb.append("("); int beforeLength = sb.length(); sb.append(parameters); sb.delete(beforeLength, beforeLength+1); sb.delete(sb.length()-2, sb.length()); sb.append(")"); return sb.toString(); }
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\t"); sb.append(modifier); if(isStatic) { sb.append("static "); } sb.append(returnType); sb.append(" "); sb.append(methodName); sb.append("("); int beforeLength = sb.length(); sb.append(parameters); sb.delete(beforeLength, beforeLength+1); sb.delete(sb.length()-1, sb.length()); sb.append(")"); return sb.toString(); }
diff --git a/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java b/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java index eeab8057..dd1a023c 100644 --- a/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java +++ b/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java @@ -1,172 +1,174 @@ /* * This file is part of Vanilla. * * Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/> * Vanilla is licensed under the SpoutDev License Version 1. * * Vanilla is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Vanilla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spout.vanilla.protocol.handler; import org.spout.api.Spout; import org.spout.api.event.player.PlayerInteractEvent; import org.spout.api.event.player.PlayerInteractEvent.Action; import org.spout.api.geo.World; import org.spout.api.geo.cuboid.Block; import org.spout.api.geo.discrete.Point; import org.spout.api.inventory.Inventory; import org.spout.api.inventory.ItemStack; import org.spout.api.material.BlockMaterial; import org.spout.api.material.basic.BasicAir; import org.spout.api.material.block.BlockFace; import org.spout.api.player.Player; import org.spout.api.protocol.MessageHandler; import org.spout.api.protocol.Session; import org.spout.vanilla.controller.living.player.VanillaPlayer; import org.spout.vanilla.material.Mineable; import org.spout.vanilla.material.VanillaMaterial; import org.spout.vanilla.material.VanillaMaterials; import org.spout.vanilla.material.item.MiningTool; import org.spout.vanilla.protocol.VanillaNetworkSynchronizer; import org.spout.vanilla.protocol.msg.PlayEffectMessage; import org.spout.vanilla.protocol.msg.PlayEffectMessage.Messages; import org.spout.vanilla.protocol.msg.PlayerDiggingMessage; import org.spout.vanilla.util.VanillaMessageHandlerUtils; public final class PlayerDiggingMessageHandler extends MessageHandler<PlayerDiggingMessage> { @Override public void handleServer(Session session, Player player, PlayerDiggingMessage message) { if (player == null || player.getEntity() == null) { return; } int x = message.getX(); int y = message.getY(); int z = message.getZ(); World w = player.getEntity().getWorld(); Block block = w.getBlock(x, y, z, player.getEntity()); BlockMaterial blockMaterial = block.getSubMaterial(); BlockFace clickedFace = VanillaMessageHandlerUtils.messageToBlockFace(message.getFace()); if (x == 0 && y == 0 && z == 0 && message.getFace() == 0 && message.getState() == 4) { ((VanillaPlayer) player.getEntity().getController()).dropItem(); return; } boolean isInteractable = true; //FIXME: How so not interactable? I am pretty sure I can interact with water to place a boat, no? if (blockMaterial == VanillaMaterials.AIR || blockMaterial == BasicAir.AIR || blockMaterial == VanillaMaterials.WATER || blockMaterial == VanillaMaterials.LAVA) { isInteractable = false; } Inventory inv = player.getEntity().getInventory(); ItemStack heldItem = inv.getCurrentItem(); VanillaPlayer vp = ((VanillaPlayer) player.getEntity().getController()); if (message.getState() == PlayerDiggingMessage.STATE_START_DIGGING) { PlayerInteractEvent event = new PlayerInteractEvent(player, block.getPosition(), heldItem, Action.LEFT_CLICK, isInteractable); if (Spout.getEngine().getEventManager().callEvent(event).isCancelled()) { return; } //Perform interactions if (!isInteractable && heldItem == null) { //interacting with nothing using fist return; } else if (heldItem == null) { //interacting with block using fist blockMaterial.onInteractBy(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); } else if (!isInteractable) { //interacting with nothing using item heldItem.getSubMaterial().onInteract(player.getEntity(), Action.LEFT_CLICK); } else { //interacting with block using item heldItem.getSubMaterial().onInteract(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); blockMaterial.onInteractBy(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); } if (isInteractable) { Block neigh = block.translate(clickedFace); boolean fire = neigh.getMaterial().equals(VanillaMaterials.FIRE); if (fire) { //put out fire VanillaMaterials.FIRE.onDestroy(neigh); VanillaNetworkSynchronizer.playBlockEffect(block, player.getEntity(), PlayEffectMessage.Messages.RANDOM_FIZZ); } else if (vp.isSurvival() && blockMaterial.getHardness() != 0.0f) { vp.startDigging(new Point(w, x, y, z)); } else { //insta-break blockMaterial.onDestroy(block); PlayEffectMessage pem = new PlayEffectMessage(Messages.PARTICLE_BREAKBLOCK.getId(), block, blockMaterial.getId()); VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers(player.getEntity(), player.getEntity().getViewDistance(), pem); } } } else if (message.getState() == PlayerDiggingMessage.STATE_DONE_DIGGING) { if (!vp.stopDigging(new Point(w, x, y, z))) { return; } long diggingTicks = vp.getDiggingTicks(); int damageDone = 0; int totalDamage = 0; if (heldItem != null) { if (heldItem.getMaterial() instanceof MiningTool && blockMaterial instanceof Mineable) { MiningTool tool = (MiningTool) heldItem.getMaterial(); Mineable mineable = (Mineable) blockMaterial; - if (tool.getDamage() < 0) { - player.getEntity().getInventory().getCurrentItem().setMaterial(null); + if (tool.getDurability() < 1) { + player.getEntity().getInventory().setCurrentItem(null); } else { - inv.addCurrentItemData(mineable.getDurabilityPenalty(tool)); + short penalty = mineable.getDurabilityPenalty(tool); + inv.addCurrentItemData(penalty); + tool.setDurability((short) (tool.getDurability() - penalty)); } } } if (isInteractable) { if (heldItem == null) { damageDone = ((int) diggingTicks * 1); } else { damageDone = ((int) diggingTicks * ((VanillaMaterial) heldItem.getMaterial()).getDamage()); } // TODO: Take into account enchantments totalDamage = ((int) blockMaterial.getHardness() - damageDone); if (totalDamage <= 40) { //Yes, this is a very high allowance - this is because this is only over a single block, and this will spike due to varying latency. if (!(blockMaterial instanceof Mineable)) { player.kick("The block you tried to dig is not MINEABLE. No blocks for you."); return; } if (totalDamage < -30) {// This can be removed after VANILLA-97 is fixed. System.out.println("[DEBUG] Player spent much more time mining than expected: " + (-totalDamage) + " damage more. Block: " + blockMaterial.getClass().getName()); } if (!vp.addAndCheckMiningSpeed(totalDamage)) { player.kick("Stop speed-mining!"); return; } blockMaterial.onDestroy(block); PlayEffectMessage pem = new PlayEffectMessage(Messages.PARTICLE_BREAKBLOCK.getId(), block, blockMaterial.getId()); VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers(player.getEntity(), player.getEntity().getViewDistance(), pem); } } } } }
false
true
public void handleServer(Session session, Player player, PlayerDiggingMessage message) { if (player == null || player.getEntity() == null) { return; } int x = message.getX(); int y = message.getY(); int z = message.getZ(); World w = player.getEntity().getWorld(); Block block = w.getBlock(x, y, z, player.getEntity()); BlockMaterial blockMaterial = block.getSubMaterial(); BlockFace clickedFace = VanillaMessageHandlerUtils.messageToBlockFace(message.getFace()); if (x == 0 && y == 0 && z == 0 && message.getFace() == 0 && message.getState() == 4) { ((VanillaPlayer) player.getEntity().getController()).dropItem(); return; } boolean isInteractable = true; //FIXME: How so not interactable? I am pretty sure I can interact with water to place a boat, no? if (blockMaterial == VanillaMaterials.AIR || blockMaterial == BasicAir.AIR || blockMaterial == VanillaMaterials.WATER || blockMaterial == VanillaMaterials.LAVA) { isInteractable = false; } Inventory inv = player.getEntity().getInventory(); ItemStack heldItem = inv.getCurrentItem(); VanillaPlayer vp = ((VanillaPlayer) player.getEntity().getController()); if (message.getState() == PlayerDiggingMessage.STATE_START_DIGGING) { PlayerInteractEvent event = new PlayerInteractEvent(player, block.getPosition(), heldItem, Action.LEFT_CLICK, isInteractable); if (Spout.getEngine().getEventManager().callEvent(event).isCancelled()) { return; } //Perform interactions if (!isInteractable && heldItem == null) { //interacting with nothing using fist return; } else if (heldItem == null) { //interacting with block using fist blockMaterial.onInteractBy(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); } else if (!isInteractable) { //interacting with nothing using item heldItem.getSubMaterial().onInteract(player.getEntity(), Action.LEFT_CLICK); } else { //interacting with block using item heldItem.getSubMaterial().onInteract(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); blockMaterial.onInteractBy(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); } if (isInteractable) { Block neigh = block.translate(clickedFace); boolean fire = neigh.getMaterial().equals(VanillaMaterials.FIRE); if (fire) { //put out fire VanillaMaterials.FIRE.onDestroy(neigh); VanillaNetworkSynchronizer.playBlockEffect(block, player.getEntity(), PlayEffectMessage.Messages.RANDOM_FIZZ); } else if (vp.isSurvival() && blockMaterial.getHardness() != 0.0f) { vp.startDigging(new Point(w, x, y, z)); } else { //insta-break blockMaterial.onDestroy(block); PlayEffectMessage pem = new PlayEffectMessage(Messages.PARTICLE_BREAKBLOCK.getId(), block, blockMaterial.getId()); VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers(player.getEntity(), player.getEntity().getViewDistance(), pem); } } } else if (message.getState() == PlayerDiggingMessage.STATE_DONE_DIGGING) { if (!vp.stopDigging(new Point(w, x, y, z))) { return; } long diggingTicks = vp.getDiggingTicks(); int damageDone = 0; int totalDamage = 0; if (heldItem != null) { if (heldItem.getMaterial() instanceof MiningTool && blockMaterial instanceof Mineable) { MiningTool tool = (MiningTool) heldItem.getMaterial(); Mineable mineable = (Mineable) blockMaterial; if (tool.getDamage() < 0) { player.getEntity().getInventory().getCurrentItem().setMaterial(null); } else { inv.addCurrentItemData(mineable.getDurabilityPenalty(tool)); } } } if (isInteractable) { if (heldItem == null) { damageDone = ((int) diggingTicks * 1); } else { damageDone = ((int) diggingTicks * ((VanillaMaterial) heldItem.getMaterial()).getDamage()); } // TODO: Take into account enchantments totalDamage = ((int) blockMaterial.getHardness() - damageDone); if (totalDamage <= 40) { //Yes, this is a very high allowance - this is because this is only over a single block, and this will spike due to varying latency. if (!(blockMaterial instanceof Mineable)) { player.kick("The block you tried to dig is not MINEABLE. No blocks for you."); return; } if (totalDamage < -30) {// This can be removed after VANILLA-97 is fixed. System.out.println("[DEBUG] Player spent much more time mining than expected: " + (-totalDamage) + " damage more. Block: " + blockMaterial.getClass().getName()); } if (!vp.addAndCheckMiningSpeed(totalDamage)) { player.kick("Stop speed-mining!"); return; } blockMaterial.onDestroy(block); PlayEffectMessage pem = new PlayEffectMessage(Messages.PARTICLE_BREAKBLOCK.getId(), block, blockMaterial.getId()); VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers(player.getEntity(), player.getEntity().getViewDistance(), pem); } } } }
public void handleServer(Session session, Player player, PlayerDiggingMessage message) { if (player == null || player.getEntity() == null) { return; } int x = message.getX(); int y = message.getY(); int z = message.getZ(); World w = player.getEntity().getWorld(); Block block = w.getBlock(x, y, z, player.getEntity()); BlockMaterial blockMaterial = block.getSubMaterial(); BlockFace clickedFace = VanillaMessageHandlerUtils.messageToBlockFace(message.getFace()); if (x == 0 && y == 0 && z == 0 && message.getFace() == 0 && message.getState() == 4) { ((VanillaPlayer) player.getEntity().getController()).dropItem(); return; } boolean isInteractable = true; //FIXME: How so not interactable? I am pretty sure I can interact with water to place a boat, no? if (blockMaterial == VanillaMaterials.AIR || blockMaterial == BasicAir.AIR || blockMaterial == VanillaMaterials.WATER || blockMaterial == VanillaMaterials.LAVA) { isInteractable = false; } Inventory inv = player.getEntity().getInventory(); ItemStack heldItem = inv.getCurrentItem(); VanillaPlayer vp = ((VanillaPlayer) player.getEntity().getController()); if (message.getState() == PlayerDiggingMessage.STATE_START_DIGGING) { PlayerInteractEvent event = new PlayerInteractEvent(player, block.getPosition(), heldItem, Action.LEFT_CLICK, isInteractable); if (Spout.getEngine().getEventManager().callEvent(event).isCancelled()) { return; } //Perform interactions if (!isInteractable && heldItem == null) { //interacting with nothing using fist return; } else if (heldItem == null) { //interacting with block using fist blockMaterial.onInteractBy(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); } else if (!isInteractable) { //interacting with nothing using item heldItem.getSubMaterial().onInteract(player.getEntity(), Action.LEFT_CLICK); } else { //interacting with block using item heldItem.getSubMaterial().onInteract(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); blockMaterial.onInteractBy(player.getEntity(), block, Action.LEFT_CLICK, clickedFace); } if (isInteractable) { Block neigh = block.translate(clickedFace); boolean fire = neigh.getMaterial().equals(VanillaMaterials.FIRE); if (fire) { //put out fire VanillaMaterials.FIRE.onDestroy(neigh); VanillaNetworkSynchronizer.playBlockEffect(block, player.getEntity(), PlayEffectMessage.Messages.RANDOM_FIZZ); } else if (vp.isSurvival() && blockMaterial.getHardness() != 0.0f) { vp.startDigging(new Point(w, x, y, z)); } else { //insta-break blockMaterial.onDestroy(block); PlayEffectMessage pem = new PlayEffectMessage(Messages.PARTICLE_BREAKBLOCK.getId(), block, blockMaterial.getId()); VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers(player.getEntity(), player.getEntity().getViewDistance(), pem); } } } else if (message.getState() == PlayerDiggingMessage.STATE_DONE_DIGGING) { if (!vp.stopDigging(new Point(w, x, y, z))) { return; } long diggingTicks = vp.getDiggingTicks(); int damageDone = 0; int totalDamage = 0; if (heldItem != null) { if (heldItem.getMaterial() instanceof MiningTool && blockMaterial instanceof Mineable) { MiningTool tool = (MiningTool) heldItem.getMaterial(); Mineable mineable = (Mineable) blockMaterial; if (tool.getDurability() < 1) { player.getEntity().getInventory().setCurrentItem(null); } else { short penalty = mineable.getDurabilityPenalty(tool); inv.addCurrentItemData(penalty); tool.setDurability((short) (tool.getDurability() - penalty)); } } } if (isInteractable) { if (heldItem == null) { damageDone = ((int) diggingTicks * 1); } else { damageDone = ((int) diggingTicks * ((VanillaMaterial) heldItem.getMaterial()).getDamage()); } // TODO: Take into account enchantments totalDamage = ((int) blockMaterial.getHardness() - damageDone); if (totalDamage <= 40) { //Yes, this is a very high allowance - this is because this is only over a single block, and this will spike due to varying latency. if (!(blockMaterial instanceof Mineable)) { player.kick("The block you tried to dig is not MINEABLE. No blocks for you."); return; } if (totalDamage < -30) {// This can be removed after VANILLA-97 is fixed. System.out.println("[DEBUG] Player spent much more time mining than expected: " + (-totalDamage) + " damage more. Block: " + blockMaterial.getClass().getName()); } if (!vp.addAndCheckMiningSpeed(totalDamage)) { player.kick("Stop speed-mining!"); return; } blockMaterial.onDestroy(block); PlayEffectMessage pem = new PlayEffectMessage(Messages.PARTICLE_BREAKBLOCK.getId(), block, blockMaterial.getId()); VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers(player.getEntity(), player.getEntity().getViewDistance(), pem); } } } }
diff --git a/contentconnector-core/src/main/java/com/gentics/cr/monitoring/MonitorFactory.java b/contentconnector-core/src/main/java/com/gentics/cr/monitoring/MonitorFactory.java index ed75f374..d312fbd7 100644 --- a/contentconnector-core/src/main/java/com/gentics/cr/monitoring/MonitorFactory.java +++ b/contentconnector-core/src/main/java/com/gentics/cr/monitoring/MonitorFactory.java @@ -1,28 +1,28 @@ package com.gentics.cr.monitoring; import com.gentics.cr.configuration.GenericConfiguration; public class MonitorFactory { private static boolean monitorenabled = false; private static final String MONITOR_ENABLE_KEY="monitoring"; public static synchronized void init(GenericConfiguration config) { String s_mon = config.getString(MONITOR_ENABLE_KEY); if(s_mon!=null) { monitorenabled = Boolean.parseBoolean(s_mon); } } public static UseCase startUseCase(String identifyer) { if(monitorenabled) { return new UseCase(com.jamonapi.MonitorFactory.start(identifyer),monitorenabled); } - return null; + return new UseCase(null,monitorenabled); } }
true
true
public static UseCase startUseCase(String identifyer) { if(monitorenabled) { return new UseCase(com.jamonapi.MonitorFactory.start(identifyer),monitorenabled); } return null; }
public static UseCase startUseCase(String identifyer) { if(monitorenabled) { return new UseCase(com.jamonapi.MonitorFactory.start(identifyer),monitorenabled); } return new UseCase(null,monitorenabled); }
diff --git a/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java b/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java index 1f832b3a5..84f0708d1 100644 --- a/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java +++ b/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java @@ -1,62 +1,64 @@ package edu.northwestern.bioinformatics.studycalendar.web; import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.Site; import edu.northwestern.bioinformatics.studycalendar.domain.Fixtures; import edu.northwestern.bioinformatics.studycalendar.service.TemplateService; import edu.northwestern.bioinformatics.studycalendar.service.SiteService; import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.ApplicationSecurityManager; import org.easymock.classextension.EasyMock; import static org.easymock.classextension.EasyMock.*; import org.springframework.web.servlet.ModelAndView; import java.util.List; import java.util.ArrayList; import java.util.Arrays; /** * @author Rhett Sutphin */ public class StudyListControllerTest extends ControllerTestCase { private StudyListController controller; private StudyDao studyDao; private TemplateService templateService; private SiteService siteService; protected void setUp() throws Exception { super.setUp(); controller = new StudyListController(); studyDao = registerDaoMockFor(StudyDao.class); templateService = registerMockFor(TemplateService.class); siteService = registerMockFor(SiteService.class); controller.setStudyDao(studyDao); controller.setTemplateService(templateService); controller.setSiteService(siteService); } public void testModelAndView() throws Exception { Study complete = Fixtures.createSingleEpochStudy("Complete", "E1"); + complete.setAmended(false); complete.getPlannedCalendar().setComplete(true); Study incomplete = Fixtures.createSingleEpochStudy("Incomplete", "E1"); + incomplete.setAmended(false); incomplete.getPlannedCalendar().setComplete(false); List<Study> studies = Arrays.asList(incomplete, complete); List<Site> sites = new ArrayList<Site>(); ApplicationSecurityManager.setUser(request, "jimbo"); expect(studyDao.getAll()).andReturn(studies); expect(templateService.checkOwnership("jimbo", studies)).andReturn(studies); expect(siteService.getSitesForSiteCd("jimbo")).andReturn(sites); replayMocks(); ModelAndView mv = controller.handleRequest(request, response); verifyMocks(); assertEquals("Complete studies list missing or wrong", Arrays.asList(complete), mv.getModel().get("completeStudies")); assertEquals("Incomplete studies list missing or wrong", Arrays.asList(incomplete), mv.getModel().get("incompleteStudies")); assertSame("Sites list missing or wrong", sites, mv.getModel().get("sites")); assertEquals("studyList", mv.getViewName()); } }
false
true
public void testModelAndView() throws Exception { Study complete = Fixtures.createSingleEpochStudy("Complete", "E1"); complete.getPlannedCalendar().setComplete(true); Study incomplete = Fixtures.createSingleEpochStudy("Incomplete", "E1"); incomplete.getPlannedCalendar().setComplete(false); List<Study> studies = Arrays.asList(incomplete, complete); List<Site> sites = new ArrayList<Site>(); ApplicationSecurityManager.setUser(request, "jimbo"); expect(studyDao.getAll()).andReturn(studies); expect(templateService.checkOwnership("jimbo", studies)).andReturn(studies); expect(siteService.getSitesForSiteCd("jimbo")).andReturn(sites); replayMocks(); ModelAndView mv = controller.handleRequest(request, response); verifyMocks(); assertEquals("Complete studies list missing or wrong", Arrays.asList(complete), mv.getModel().get("completeStudies")); assertEquals("Incomplete studies list missing or wrong", Arrays.asList(incomplete), mv.getModel().get("incompleteStudies")); assertSame("Sites list missing or wrong", sites, mv.getModel().get("sites")); assertEquals("studyList", mv.getViewName()); }
public void testModelAndView() throws Exception { Study complete = Fixtures.createSingleEpochStudy("Complete", "E1"); complete.setAmended(false); complete.getPlannedCalendar().setComplete(true); Study incomplete = Fixtures.createSingleEpochStudy("Incomplete", "E1"); incomplete.setAmended(false); incomplete.getPlannedCalendar().setComplete(false); List<Study> studies = Arrays.asList(incomplete, complete); List<Site> sites = new ArrayList<Site>(); ApplicationSecurityManager.setUser(request, "jimbo"); expect(studyDao.getAll()).andReturn(studies); expect(templateService.checkOwnership("jimbo", studies)).andReturn(studies); expect(siteService.getSitesForSiteCd("jimbo")).andReturn(sites); replayMocks(); ModelAndView mv = controller.handleRequest(request, response); verifyMocks(); assertEquals("Complete studies list missing or wrong", Arrays.asList(complete), mv.getModel().get("completeStudies")); assertEquals("Incomplete studies list missing or wrong", Arrays.asList(incomplete), mv.getModel().get("incompleteStudies")); assertSame("Sites list missing or wrong", sites, mv.getModel().get("sites")); assertEquals("studyList", mv.getViewName()); }
diff --git a/Flags/src/alshain01/Flags/Registrar.java b/Flags/src/alshain01/Flags/Registrar.java index a2332e0..13a6f45 100644 --- a/Flags/src/alshain01/Flags/Registrar.java +++ b/Flags/src/alshain01/Flags/Registrar.java @@ -1,146 +1,146 @@ package alshain01.Flags; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Bukkit; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import alshain01.Flags.Flag; public class Registrar { ConcurrentHashMap<String, Flag> flagStore = new ConcurrentHashMap<String, Flag>(); protected Registrar() { } /** * Registers a non-player flag * * @param name The name of the flag * @param description A brief description of the flag * @param def The flag's default state * @param group The group the flag belongs in. * @return The flag if the flag was successfully registered. Null otherwise. */ public Flag register(String name, String description, boolean def, String group) { if(!flagStore.containsKey(name)) { Flag flag = new Flag(name, description, def, group, false, null, null); flagStore.put(name, flag); //Add the permission for the flag to the server Permission perm = new Permission(flag.getPermission(), "Allows players to set the flag " + flag.getName(), PermissionDefault.OP); perm.addParent("flags.flagtype.*", true); Bukkit.getServer().getPluginManager().addPermission(perm); return flag; } return null; } /** * Registers a player flag * * @param name The name of the flag * @param description A brief description of the flag * @param def The flag's default state * @param group The group the flag belongs in. * @param areaMessage The default message for areas. * @param worldMessage The default message for worlds. * @return The flag if the flag was successfully registered. Null otherwise. */ public Flag register(String name, String description, boolean def, String group, String areaMessage, String worldMessage) { if(!flagStore.containsKey(name)) { Flag flag = new Flag(name, description, def, group, true, areaMessage, worldMessage); flagStore.put(name, flag); //Add the permission for the flag to the server Permission perm = new Permission(flag.getPermission(), "Allows players to set the flag " + flag.getName(), PermissionDefault.OP); perm.addParent("flags.flagtype.*", true); Bukkit.getServer().getPluginManager().addPermission(perm); //Add the permission for the flag bypass to the server - perm = new Permission(flag.getBypassPermission(), "Allows players to bypass the effects of the flag " + flag.getName(), PermissionDefault.OP); + perm = new Permission(flag.getBypassPermission(), "Allows players to bypass the effects of the flag " + flag.getName(), PermissionDefault.FALSE); perm.addParent("flags.bypass.*", true); Bukkit.getServer().getPluginManager().addPermission(perm); return flag; } return null; } /** * Informs whether or not a flag name has been registered. * * @param flag The flag name * @return True if the flag name has been registered */ public boolean isFlag(String flag) { return flagStore.containsKey(flag); } /** * Retrieves a flag based on it's case sensitive name. * * @param flag The flag to retrieve. * @return The flag requested or null if it does not exist. */ public Flag getFlag(String flag) { if(isFlag(flag)) { return flagStore.get(flag); } return null; } /** * Gets a flag, ignoring the case. * This is an inefficient method, use it * only when absolutely necessary. * * @param flag The flag to retrieve. * @return The flag requested or null if it does not exist. */ public Flag getFlagIgnoreCase(String flag) { for(Flag f : getFlags()) if(f.getName().equalsIgnoreCase(flag)) { return f; } return null; } /** * Gets a collection of all registered flags. * * @return A collection of all the flags registered. */ public Collection<Flag> getFlags() { return flagStore.values(); } /** * Gets a set of all registered flag names. * * @return A list of names of all the flags registered. */ public Set<String> getFlagNames() { return new HashSet<String>(Collections.list(flagStore.keys())); } /** * Gets a set of all registered flag group names. * * @return A list of names of all the flags registered. */ public Set<String> getFlagGroups() { Set<String> groups = new HashSet<String>(); for(Flag flag : flagStore.values()) { if(!groups.contains(flag.getGroup())) { groups.add(flag.getGroup()); } } return new HashSet<String>(Collections.list(flagStore.keys())); } }
true
true
public Flag register(String name, String description, boolean def, String group, String areaMessage, String worldMessage) { if(!flagStore.containsKey(name)) { Flag flag = new Flag(name, description, def, group, true, areaMessage, worldMessage); flagStore.put(name, flag); //Add the permission for the flag to the server Permission perm = new Permission(flag.getPermission(), "Allows players to set the flag " + flag.getName(), PermissionDefault.OP); perm.addParent("flags.flagtype.*", true); Bukkit.getServer().getPluginManager().addPermission(perm); //Add the permission for the flag bypass to the server perm = new Permission(flag.getBypassPermission(), "Allows players to bypass the effects of the flag " + flag.getName(), PermissionDefault.OP); perm.addParent("flags.bypass.*", true); Bukkit.getServer().getPluginManager().addPermission(perm); return flag; } return null; }
public Flag register(String name, String description, boolean def, String group, String areaMessage, String worldMessage) { if(!flagStore.containsKey(name)) { Flag flag = new Flag(name, description, def, group, true, areaMessage, worldMessage); flagStore.put(name, flag); //Add the permission for the flag to the server Permission perm = new Permission(flag.getPermission(), "Allows players to set the flag " + flag.getName(), PermissionDefault.OP); perm.addParent("flags.flagtype.*", true); Bukkit.getServer().getPluginManager().addPermission(perm); //Add the permission for the flag bypass to the server perm = new Permission(flag.getBypassPermission(), "Allows players to bypass the effects of the flag " + flag.getName(), PermissionDefault.FALSE); perm.addParent("flags.bypass.*", true); Bukkit.getServer().getPluginManager().addPermission(perm); return flag; } return null; }
diff --git a/maven-aidl-plugin/src/main/java/org/jvending/masa/plugin/aidl/AidlGeneratorMojo.java b/maven-aidl-plugin/src/main/java/org/jvending/masa/plugin/aidl/AidlGeneratorMojo.java index 4cb76cf..d3058bf 100644 --- a/maven-aidl-plugin/src/main/java/org/jvending/masa/plugin/aidl/AidlGeneratorMojo.java +++ b/maven-aidl-plugin/src/main/java/org/jvending/masa/plugin/aidl/AidlGeneratorMojo.java @@ -1,82 +1,83 @@ /* * Copyright (C) 2007-2008 JVending Masa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jvending.masa.plugin.aidl; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.DirectoryScanner; import org.jvending.masa.CommandExecutor; import org.jvending.masa.ExecutionException; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @goal generate * @requiresProject true * @description */ public class AidlGeneratorMojo extends AbstractMojo { /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; public void execute() throws MojoExecutionException, MojoFailureException { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(project.getBuild().getSourceDirectory()); List<String> excludeList = new ArrayList<String>(); //target files excludeList.add("target/**"); List<String> includeList = new ArrayList<String>(); includeList.add("**/*.aidl"); String[] includes = new String[includeList.size()]; directoryScanner.setIncludes((includeList.toArray(includes))); directoryScanner.addDefaultExcludes(); directoryScanner.scan(); String[] files = directoryScanner.getIncludedFiles(); getLog().info("ANDROID-904-002: Found aidl files: Count = " + files.length); if (files.length == 0) { return; } CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); for (String file : files) { List<String> commands = new ArrayList<String>(); + commands.add("-p" + System.getenv().get("ANDROID_SDK") + "/tools/lib/framework.aidl"); commands.add("-I" + project.getBuild().getSourceDirectory()); commands.add((new File(project.getBuild().getSourceDirectory(), file).getAbsolutePath())); try { executor.executeCommand("aidl", commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } } } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(project.getBuild().getSourceDirectory()); List<String> excludeList = new ArrayList<String>(); //target files excludeList.add("target/**"); List<String> includeList = new ArrayList<String>(); includeList.add("**/*.aidl"); String[] includes = new String[includeList.size()]; directoryScanner.setIncludes((includeList.toArray(includes))); directoryScanner.addDefaultExcludes(); directoryScanner.scan(); String[] files = directoryScanner.getIncludedFiles(); getLog().info("ANDROID-904-002: Found aidl files: Count = " + files.length); if (files.length == 0) { return; } CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); for (String file : files) { List<String> commands = new ArrayList<String>(); commands.add("-I" + project.getBuild().getSourceDirectory()); commands.add((new File(project.getBuild().getSourceDirectory(), file).getAbsolutePath())); try { executor.executeCommand("aidl", commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } } }
public void execute() throws MojoExecutionException, MojoFailureException { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(project.getBuild().getSourceDirectory()); List<String> excludeList = new ArrayList<String>(); //target files excludeList.add("target/**"); List<String> includeList = new ArrayList<String>(); includeList.add("**/*.aidl"); String[] includes = new String[includeList.size()]; directoryScanner.setIncludes((includeList.toArray(includes))); directoryScanner.addDefaultExcludes(); directoryScanner.scan(); String[] files = directoryScanner.getIncludedFiles(); getLog().info("ANDROID-904-002: Found aidl files: Count = " + files.length); if (files.length == 0) { return; } CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); for (String file : files) { List<String> commands = new ArrayList<String>(); commands.add("-p" + System.getenv().get("ANDROID_SDK") + "/tools/lib/framework.aidl"); commands.add("-I" + project.getBuild().getSourceDirectory()); commands.add((new File(project.getBuild().getSourceDirectory(), file).getAbsolutePath())); try { executor.executeCommand("aidl", commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } } }
diff --git a/src/test/java/com/grayjay/javaUtilities/javaUtilities/UpgradableLockPerformance.java b/src/test/java/com/grayjay/javaUtilities/javaUtilities/UpgradableLockPerformance.java index ea35cf1..c532343 100644 --- a/src/test/java/com/grayjay/javaUtilities/javaUtilities/UpgradableLockPerformance.java +++ b/src/test/java/com/grayjay/javaUtilities/javaUtilities/UpgradableLockPerformance.java @@ -1,257 +1,257 @@ package javaUtilities; import java.util.concurrent.*; import java.util.concurrent.locks.*; import javaUtilities.UpgradableLock.Mode; public class UpgradableLockPerformance { private static final int N_TRIALS = 10; private static final int N_THREADS = Runtime.getRuntime().availableProcessors() + 1; private static final int N_LOCKS = 1_000_000; private static final int COLUMN_WIDTH = 25; private int myCount = 0; public static void main(String[] aArgs) throws InterruptedException { printColumn("ReentrantReadWriteLock"); printColumn("UpgradableLock"); - printColumn("ReentrantLock)"); + printColumn("ReentrantLock"); System.out.println(); System.out.println(); System.out.printf("%,d trials with %,d threads and %,d total locks per trial (ns/lock)", N_TRIALS, N_THREADS, N_LOCKS); long mReadWriteNanos = 0; long mUpgradableNanos = 0; long mReentrantLockNanos = 0; for (int i = 0; i < N_TRIALS; i++) { long mReadWriteTime = new UpgradableLockPerformance().timeNanos(new ReadWriteLockTest()); long mUpgradableTime = new UpgradableLockPerformance().timeNanos(new UpgradableLockTest()); long mReentrantLockTime = new UpgradableLockPerformance().timeNanos(new ReentrantLockTest()); System.out.println(); printTrial(mReadWriteTime); printTrial(mUpgradableTime); printTrial(mReentrantLockTime); mReadWriteNanos += mReadWriteTime; mUpgradableNanos += mUpgradableTime; mReentrantLockNanos += mReentrantLockTime; } System.out.println(); System.out.println(); long[] mTotals = {mReadWriteNanos, mUpgradableNanos, mReentrantLockNanos}; System.out.println("Average (ns/lock)"); for (long mTotal : mTotals) { printTrial(mTotal / N_TRIALS); } System.out.println(); System.out.println(); System.out.println("Total / ReentrantReadWriteLock:"); for (long mTotal : mTotals) { double mRatio = (double) mTotal / mReadWriteNanos; printColumn(formatFloating(mRatio)); } System.out.println(); } private static void printTrial(long aNanos) { double mAvg = (double) aNanos / N_LOCKS; printColumn(formatFloating(mAvg)); } private static void printColumn(String aString) { System.out.printf("%-" + COLUMN_WIDTH + "s", aString); } private static String formatFloating(double aFloating) { return String.format("%.4f", aFloating); } private long timeNanos(LockTest aTest) throws InterruptedException { assert myCount == 0; ExecutorService mPool = Executors.newFixedThreadPool(N_THREADS); long mStart = System.nanoTime(); for (int i = 0; i < N_THREADS; i++) { Runnable mTask = newTask(aTest); mPool.execute(mTask); } mPool.shutdown(); mPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); return System.nanoTime() - mStart; } private Runnable newTask(final LockTest aTest) { return new Runnable() { @Override public void run() { for (int i = 0; i < N_LOCKS / N_THREADS; i++) { switch (i % 4) { case 0: aTest.lockWrite(); myCount++; aTest.unlockWrite(); break; case 1: aTest.lockUpgradable(); if (myCount % 2 == 0) { aTest.upgrade(); myCount++; aTest.downgrade(); } aTest.unlockUpgradable(); break; case 2: case 3: aTest.lockRead(); if (myCount == 0.375 * N_LOCKS) { System.out.print(" "); } aTest.unlockRead(); break; default: throw new AssertionError(); } } } }; } private static interface LockTest { void lockRead(); void unlockRead(); void lockWrite(); void unlockWrite(); void lockUpgradable(); void unlockUpgradable(); void upgrade(); void downgrade(); } private static final class ReadWriteLockTest implements LockTest { private final ReadWriteLock mReadWrite = new ReentrantReadWriteLock(); private final Lock myReadLock = mReadWrite.readLock(); private final Lock myWriteLock = mReadWrite.writeLock(); @Override public void lockRead() { myReadLock.lock(); } @Override public void unlockRead() { myReadLock.unlock(); } @Override public void lockWrite() { myWriteLock.lock(); } @Override public void unlockWrite() { myWriteLock.unlock(); } @Override public void lockUpgradable() { myWriteLock.lock(); } @Override public void unlockUpgradable() { myWriteLock.unlock(); } @Override public void upgrade() { } @Override public void downgrade() { } } private static final class UpgradableLockTest implements LockTest { private final UpgradableLock myUpgradableLock = new UpgradableLock(); @Override public void lockRead() { myUpgradableLock.lock(Mode.READ); } @Override public void unlockRead() { myUpgradableLock.unlock(); } @Override public void lockWrite() { myUpgradableLock.lock(Mode.WRITE); } @Override public void unlockWrite() { myUpgradableLock.unlock(); } @Override public void lockUpgradable() { myUpgradableLock.lock(Mode.UPGRADABLE); } @Override public void unlockUpgradable() { myUpgradableLock.unlock(); } @Override public void upgrade() { myUpgradableLock.upgrade(); } @Override public void downgrade() { myUpgradableLock.downgrade(); } } private static final class ReentrantLockTest implements LockTest { private final Lock myReentrantLock = new ReentrantLock(); @Override public void lockRead() { myReentrantLock.lock(); } @Override public void unlockRead() { myReentrantLock.unlock(); } @Override public void lockWrite() { myReentrantLock.lock(); } @Override public void unlockWrite() { myReentrantLock.unlock(); } @Override public void lockUpgradable() { myReentrantLock.lock(); } @Override public void unlockUpgradable() { myReentrantLock.unlock(); } @Override public void upgrade() { } @Override public void downgrade() { } } }
true
true
public static void main(String[] aArgs) throws InterruptedException { printColumn("ReentrantReadWriteLock"); printColumn("UpgradableLock"); printColumn("ReentrantLock)"); System.out.println(); System.out.println(); System.out.printf("%,d trials with %,d threads and %,d total locks per trial (ns/lock)", N_TRIALS, N_THREADS, N_LOCKS); long mReadWriteNanos = 0; long mUpgradableNanos = 0; long mReentrantLockNanos = 0; for (int i = 0; i < N_TRIALS; i++) { long mReadWriteTime = new UpgradableLockPerformance().timeNanos(new ReadWriteLockTest()); long mUpgradableTime = new UpgradableLockPerformance().timeNanos(new UpgradableLockTest()); long mReentrantLockTime = new UpgradableLockPerformance().timeNanos(new ReentrantLockTest()); System.out.println(); printTrial(mReadWriteTime); printTrial(mUpgradableTime); printTrial(mReentrantLockTime); mReadWriteNanos += mReadWriteTime; mUpgradableNanos += mUpgradableTime; mReentrantLockNanos += mReentrantLockTime; } System.out.println(); System.out.println(); long[] mTotals = {mReadWriteNanos, mUpgradableNanos, mReentrantLockNanos}; System.out.println("Average (ns/lock)"); for (long mTotal : mTotals) { printTrial(mTotal / N_TRIALS); } System.out.println(); System.out.println(); System.out.println("Total / ReentrantReadWriteLock:"); for (long mTotal : mTotals) { double mRatio = (double) mTotal / mReadWriteNanos; printColumn(formatFloating(mRatio)); } System.out.println(); }
public static void main(String[] aArgs) throws InterruptedException { printColumn("ReentrantReadWriteLock"); printColumn("UpgradableLock"); printColumn("ReentrantLock"); System.out.println(); System.out.println(); System.out.printf("%,d trials with %,d threads and %,d total locks per trial (ns/lock)", N_TRIALS, N_THREADS, N_LOCKS); long mReadWriteNanos = 0; long mUpgradableNanos = 0; long mReentrantLockNanos = 0; for (int i = 0; i < N_TRIALS; i++) { long mReadWriteTime = new UpgradableLockPerformance().timeNanos(new ReadWriteLockTest()); long mUpgradableTime = new UpgradableLockPerformance().timeNanos(new UpgradableLockTest()); long mReentrantLockTime = new UpgradableLockPerformance().timeNanos(new ReentrantLockTest()); System.out.println(); printTrial(mReadWriteTime); printTrial(mUpgradableTime); printTrial(mReentrantLockTime); mReadWriteNanos += mReadWriteTime; mUpgradableNanos += mUpgradableTime; mReentrantLockNanos += mReentrantLockTime; } System.out.println(); System.out.println(); long[] mTotals = {mReadWriteNanos, mUpgradableNanos, mReentrantLockNanos}; System.out.println("Average (ns/lock)"); for (long mTotal : mTotals) { printTrial(mTotal / N_TRIALS); } System.out.println(); System.out.println(); System.out.println("Total / ReentrantReadWriteLock:"); for (long mTotal : mTotals) { double mRatio = (double) mTotal / mReadWriteNanos; printColumn(formatFloating(mRatio)); } System.out.println(); }
diff --git a/src/main/org/python/core/ImportHelper.java b/src/main/org/python/core/ImportHelper.java index 5c46b5d4e..0aeaf3434 100644 --- a/src/main/org/python/core/ImportHelper.java +++ b/src/main/org/python/core/ImportHelper.java @@ -1,111 +1,106 @@ // ImportHelper.java package org.python.core; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class ImportHelper { // Java class protection mechanisms suck, but at least they're // easy to defeat public static PyObject loadFromSource(PySystemState sys, String name, String modName, String entry){ return imp.loadFromSource(sys, name, modName, entry); } private static final String IMPORT_LOG = "import"; // copy-pasted from imp.java's "loadFromSource", seasoned to taste public static PyObject loadFromDirectory(PySystemState sys, String name, String modName, String entry){ String sourceName = "__init__.py"; String compiledName = "__init__$py.class"; String directoryName = sys.getPath(entry); // displayDirName is for identification purposes (e.g. // __file__): when null it forces java.io.File to be a // relative path (e.g. foo/bar.py instead of /tmp/foo/bar.py) String displayDirName = entry.equals("") ? null : entry.toString(); // First check for packages File dir = new File(directoryName); File sourceFile = new File(dir, sourceName); File compiledFile = new File(dir, compiledName); boolean pkg = dir.isDirectory() && (sourceFile.isFile() || compiledFile.isFile()); if (!pkg) { Py.writeDebug(IMPORT_LOG, "trying source " + dir.getPath()); sourceName = name + ".py"; compiledName = name + "$py.class"; sourceFile = new File(directoryName, sourceName); compiledFile = new File(directoryName, compiledName); } else { PyModule m = imp.addModule(modName); PyObject filename = new PyString(dir.getPath()); m.__dict__.__setitem__("__path__", new PyList( new PyObject[] { filename })); m.__dict__.__setitem__("__file__", filename); } if (sourceFile.isFile() && imp.caseok(sourceFile, sourceName)) { - String filename; - if (pkg) { - filename = new File(new File(displayDirName, name), sourceName).getPath(); - } else { - filename = new File(displayDirName, sourceName).getPath(); - } + String filename = new File(dir, sourceName).getPath(); if(compiledFile.isFile() && imp.caseok(compiledFile, compiledName)) { Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath()); long pyTime = sourceFile.lastModified(); long classTime = compiledFile.lastModified(); if(classTime >= pyTime) { // XXX: filename should use compiledName here (not // sourceName), but this currently breaks source // code printed out in tracebacks PyObject ret = imp.createFromPyClass(modName, makeStream(compiledFile), true, filename); if(ret != null) { return ret; } } } return imp.createFromSource(modName, makeStream(sourceFile), filename, compiledFile.getPath()); } // If no source, try loading precompiled Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " + compiledFile.getPath()); if(compiledFile.isFile() && imp.caseok(compiledFile, compiledName)) { String filename = new File(displayDirName, compiledName).getPath(); return imp.createFromPyClass(modName, makeStream(compiledFile), true, filename); } return null; } // Support functions I had to copy private static InputStream makeStream(File file) { try { return new FileInputStream(file); } catch (IOException ioe) { throw Py.IOError(ioe); } } }
true
true
public static PyObject loadFromDirectory(PySystemState sys, String name, String modName, String entry){ String sourceName = "__init__.py"; String compiledName = "__init__$py.class"; String directoryName = sys.getPath(entry); // displayDirName is for identification purposes (e.g. // __file__): when null it forces java.io.File to be a // relative path (e.g. foo/bar.py instead of /tmp/foo/bar.py) String displayDirName = entry.equals("") ? null : entry.toString(); // First check for packages File dir = new File(directoryName); File sourceFile = new File(dir, sourceName); File compiledFile = new File(dir, compiledName); boolean pkg = dir.isDirectory() && (sourceFile.isFile() || compiledFile.isFile()); if (!pkg) { Py.writeDebug(IMPORT_LOG, "trying source " + dir.getPath()); sourceName = name + ".py"; compiledName = name + "$py.class"; sourceFile = new File(directoryName, sourceName); compiledFile = new File(directoryName, compiledName); } else { PyModule m = imp.addModule(modName); PyObject filename = new PyString(dir.getPath()); m.__dict__.__setitem__("__path__", new PyList( new PyObject[] { filename })); m.__dict__.__setitem__("__file__", filename); } if (sourceFile.isFile() && imp.caseok(sourceFile, sourceName)) { String filename; if (pkg) { filename = new File(new File(displayDirName, name), sourceName).getPath(); } else { filename = new File(displayDirName, sourceName).getPath(); } if(compiledFile.isFile() && imp.caseok(compiledFile, compiledName)) { Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath()); long pyTime = sourceFile.lastModified(); long classTime = compiledFile.lastModified(); if(classTime >= pyTime) { // XXX: filename should use compiledName here (not // sourceName), but this currently breaks source // code printed out in tracebacks PyObject ret = imp.createFromPyClass(modName, makeStream(compiledFile), true, filename); if(ret != null) { return ret; } } } return imp.createFromSource(modName, makeStream(sourceFile), filename, compiledFile.getPath()); } // If no source, try loading precompiled Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " + compiledFile.getPath()); if(compiledFile.isFile() && imp.caseok(compiledFile, compiledName)) { String filename = new File(displayDirName, compiledName).getPath(); return imp.createFromPyClass(modName, makeStream(compiledFile), true, filename); } return null; }
public static PyObject loadFromDirectory(PySystemState sys, String name, String modName, String entry){ String sourceName = "__init__.py"; String compiledName = "__init__$py.class"; String directoryName = sys.getPath(entry); // displayDirName is for identification purposes (e.g. // __file__): when null it forces java.io.File to be a // relative path (e.g. foo/bar.py instead of /tmp/foo/bar.py) String displayDirName = entry.equals("") ? null : entry.toString(); // First check for packages File dir = new File(directoryName); File sourceFile = new File(dir, sourceName); File compiledFile = new File(dir, compiledName); boolean pkg = dir.isDirectory() && (sourceFile.isFile() || compiledFile.isFile()); if (!pkg) { Py.writeDebug(IMPORT_LOG, "trying source " + dir.getPath()); sourceName = name + ".py"; compiledName = name + "$py.class"; sourceFile = new File(directoryName, sourceName); compiledFile = new File(directoryName, compiledName); } else { PyModule m = imp.addModule(modName); PyObject filename = new PyString(dir.getPath()); m.__dict__.__setitem__("__path__", new PyList( new PyObject[] { filename })); m.__dict__.__setitem__("__file__", filename); } if (sourceFile.isFile() && imp.caseok(sourceFile, sourceName)) { String filename = new File(dir, sourceName).getPath(); if(compiledFile.isFile() && imp.caseok(compiledFile, compiledName)) { Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath()); long pyTime = sourceFile.lastModified(); long classTime = compiledFile.lastModified(); if(classTime >= pyTime) { // XXX: filename should use compiledName here (not // sourceName), but this currently breaks source // code printed out in tracebacks PyObject ret = imp.createFromPyClass(modName, makeStream(compiledFile), true, filename); if(ret != null) { return ret; } } } return imp.createFromSource(modName, makeStream(sourceFile), filename, compiledFile.getPath()); } // If no source, try loading precompiled Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " + compiledFile.getPath()); if(compiledFile.isFile() && imp.caseok(compiledFile, compiledName)) { String filename = new File(displayDirName, compiledName).getPath(); return imp.createFromPyClass(modName, makeStream(compiledFile), true, filename); } return null; }
diff --git a/src/me/corriekay/pppopp3/utils/PSCmdExe.java b/src/me/corriekay/pppopp3/utils/PSCmdExe.java index 2f45e82..4bb7fdc 100644 --- a/src/me/corriekay/pppopp3/utils/PSCmdExe.java +++ b/src/me/corriekay/pppopp3/utils/PSCmdExe.java @@ -1,310 +1,310 @@ package me.corriekay.pppopp3.utils; import java.io.File; import java.io.FileNotFoundException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import me.corriekay.pppopp3.Mane; import me.corriekay.pppopp3.ponyville.Pony; import me.corriekay.pppopp3.ponyville.Ponyville; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventException; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.plugin.EventExecutor; public abstract class PSCmdExe implements EventExecutor, CommandExecutor, Listener { public final String name; protected final String pinkieSays = ChatColor.LIGHT_PURPLE+"Pinkie Pie: "; protected final HashMap<Class<? extends Event>, Method> methodMap = new HashMap<Class<? extends Event>, Method>(); protected final ConsoleCommandSender console = Bukkit.getConsoleSender(); protected final String notPlayer = pinkieSays+"Silly console, You need to be a player to do that!"; protected final String notEnoughArgs = pinkieSays+"Uh oh, youre gonna need to provide more arguments for that command than that!"; protected final String cantFindPlayer = pinkieSays+"I looked high and low, but I couldnt find that pony! :C"; @SuppressWarnings("unchecked") public PSCmdExe(String name, String[] cmds){ this.name = name; for(Method method : this.getClass().getMethods()){ method.setAccessible(true); Annotation eh = method.getAnnotation(EventHandler.class); if(eh != null){ Class<?>[] params = method.getParameterTypes(); if(params.length == 1){ registerEvent((Class<? extends Event>)params[0], ((EventHandler)eh).priority(),method); } } } if (cmds != null) { registerCommands(cmds); } } private void registerEvent(Class<? extends Event> event, EventPriority priority,Method method){ try { Bukkit.getPluginManager().registerEvent(event, this, priority,this, Mane.getInstance()); methodMap.put(event, method); } catch (NullPointerException e) { Bukkit.getLogger().severe("Illegal event registration!"); } } private void registerCommands(String[] cmds){ for(String cmd : cmds){ Mane.getInstance().getCommand(cmd).setExecutor(this); Mane.getInstance().getCommand(cmd).setPermissionMessage(pinkieSays+"Oh no! You cant do this :c"); } } @Override public void execute(Listener arg0, Event arg1) throws EventException { Method method = methodMap.get(arg1.getClass()); if(method == null){ return; } try{ method.invoke(this,arg1); } catch(Exception e){ if(e instanceof InvocationTargetException){ InvocationTargetException ite = (InvocationTargetException)e; e.setStackTrace(ite.getCause().getStackTrace()); } String eventName = arg1.getClass().getCanonicalName(); PonyLogger.logListenerException(e, "Error on event: "+e.getMessage(), name, eventName); sendMessage(console,"Unhandled exception in listener! Please check the error logs for more information: "+name+":"+e.getClass().getCanonicalName()); } } @Override public final boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { try{ return handleCommand(sender,cmd,label,args); } catch (Exception e){ String message = "Exception thrown on command: "+cmd.getName()+"\nLabel: "+label; message +="\nArgs: "; for(String arg : args){ message+= arg+" "; } PonyLogger.logCmdException(e, message, name); sendMessage(console,"Unhandled exception on Command! Please check the error log for more information!"); sendMessage(sender,"OH SWEET CELESTIA SOMETHING WENT HORRIBLY HORRIBLY WRONG! YOU GOTTA TELL THE SERVER ADMINS AS SOON AS YOU CAN D:"); return false; } } public boolean handleCommand(CommandSender sender, Command cmd, String label, String[] args){ return false; } public void logAdmin(CommandSender sender, String message){ String name = ""; if(sender instanceof Player){ name = ((Player)sender).getName(); } else if(sender instanceof ConsoleCommandSender){ name = "Console"; } PonyLogger.logAdmin(name, message); } /** * Sends a message to a CommandSender prepended with "Pinkie Pie: ". * @param sender CommandSender object to issue a command to. * @param message Message to send to sender. */ public void sendMessage(CommandSender sender, String message){ sender.sendMessage(pinkieSays+message); } /*methods for getting players*/ private void tooManyMatches(ArrayList<String> playerNames, CommandSender requester){ String message = pinkieSays+"There were too many matches!!"; for(String string : playerNames){ message+= string+ChatColor.LIGHT_PURPLE+" "; } requester.sendMessage(message); } private void tooManyMatches(List<Player> playerNames, CommandSender requester){ String message = pinkieSays+"There were too many matches!!"; for(Player derp : playerNames){ message+= derp.getName()+ChatColor.LIGHT_PURPLE+" "; } requester.sendMessage(message); } /** * Player get methods */ protected Pony getSingleOnlinePony(String pName, CommandSender requester){ Player target = getSingleOnlinePlayer(pName,requester); if(target == null){ return null; } Pony pony = Ponyville.getPony(target); if (pony == null){ Mane.getInstance().getLogger().severe("PONYVILLE OUT OF SYNC WITH ONLINE PLAYERS. PONY NOT FOUND IN PONYVILLE"); StackTraceElement[] ste = Thread.getAllStackTraces().get(Thread.currentThread()); StringBuilder e = new StringBuilder(); for(StackTraceElement s : ste){ e.append(s.toString()+"\n"); } System.out.println(e); return null; } return pony; } protected Player getSingleOnlinePlayer(String pName, CommandSender requester){ pName = pName.toLowerCase(); ArrayList<String> players = new ArrayList<String>(); for(Player player : Bukkit.getOnlinePlayers()){ String playername = player.getName().toLowerCase(); String playerDname = ChatColor.stripColor(player.getDisplayName()).toLowerCase(); if(playername.equals(pName)||playerDname.equals(pName)){ return player; } else { if(playername.contains(pName)||playerDname.contains(pName)){ //if(!InvisibilityHandler.ih.isHidden(player.getName())||requester.hasPermission("pppopp2.seehidden")){ players.add(player.getName()); //TODO add invis check //} } } } if(players.size()>1){ tooManyMatches(players,requester); return null; } else if(players.size()<1){ sendMessage(requester,"I looked high and low, but I couldnt find that pony! :C"); return null; } else { return Bukkit.getPlayerExact(players.get(0)); } } protected Pony getOnlinePonyCanNull(String pName, CommandSender requester){ ArrayList<Player> players = getOnlinePlayerCanNull(pName,requester); if(players.size()<1){ return null; } else { try { Pony pony = new Pony(players.get(0)); return pony; } catch (FileNotFoundException e) { return null; } } } protected ArrayList<Player> getOnlinePlayerCanNull(String pName, CommandSender requester){ pName = pName.toLowerCase(); ArrayList<Player> players = new ArrayList<Player>(); for(Player player : Bukkit.getOnlinePlayers()){ if(player.getName().toLowerCase().equals(pName)||ChatColor.stripColor(player.getDisplayName()).toLowerCase().equals(pName)){ players = new ArrayList<Player>(); players.add(player); return players; } if (player.getName().toLowerCase().contains(pName)||ChatColor.stripColor(player.getDisplayName()).toLowerCase().contains(pName)) { //if (InvisibilityHandler.ih.isHidden(player.getName())) { if (requester.hasPermission("pppopp2.seehidden")) { players.add(player); } //} else { players.add(player);//TODO add invis check //} } } if(players.size()>1){ tooManyMatches(players,requester); return null; } else { return players; } } /** * Works like {@link * #getSinglePlayer(String, CommandSender) getSinglePlayer}, * except it returns a Pony object rather than a String. * @param pName Full or partial String of a username to find. * @param requester Reference to the issuer of the command. * @return Pony object that would be returned by getSinglePlayer. * @see #getSinglePlayer(String, CommandSender) */ protected Pony getSinglePony(String pName, CommandSender requester){ String target = getSinglePlayer(pName,requester); if(target == null){ return null; } try { Pony pony = new Pony(target); return pony; } catch (FileNotFoundException e) { return null; } } /** * Returns a String object based on the parameters given that returns * null should more than one player file contain pName. This will only * work using account names, rather than nicknames. * @param pName Full or partial String of a username to find. * @param requester Reference to the issuer of the command. * @return If only one match is found, this returns a String containing * the extensionless filename of the player's file that contains * pName. Otherwise, this returns <code>null</code>. */ protected String getSinglePlayer(String pName, CommandSender requester){ pName = pName.toLowerCase(); ArrayList<String> player = new ArrayList<String>(); File dir = new File(Mane.getInstance().getDataFolder()+File.separator+"Players"); if(!dir.isDirectory()){ sendMessage(requester,"I looked high and low, but I couldnt find that pony! :C"); return null; } File[] files = dir.listFiles(); for(File file : files){ - String fname = file.getName().substring(0,file.getName().length()-4); + String fname = file.getName(); if(fname.toLowerCase().equals(pName)){ return fname; } if(fname.toLowerCase().contains(pName)){ player.add(fname); } } if(player.size()==0){ sendMessage(requester,"I looked high and low, but I couldnt find that pony! :C"); return null; } if(player.size()>1){ tooManyMatches(player,requester); return null; } return player.get(0); } /** * Sends a message to all Players connected, including the console. * @param message Message to send. */ protected void broadcastMessage(String message){ for(Player p : Bukkit.getOnlinePlayers()){ p.sendMessage(message); } console.sendMessage(message); //RemotePonyAdmin.rpa.message(message); //TODO } public void deactivate(){ } public void reload(){ } }
true
true
protected String getSinglePlayer(String pName, CommandSender requester){ pName = pName.toLowerCase(); ArrayList<String> player = new ArrayList<String>(); File dir = new File(Mane.getInstance().getDataFolder()+File.separator+"Players"); if(!dir.isDirectory()){ sendMessage(requester,"I looked high and low, but I couldnt find that pony! :C"); return null; } File[] files = dir.listFiles(); for(File file : files){ String fname = file.getName().substring(0,file.getName().length()-4); if(fname.toLowerCase().equals(pName)){ return fname; } if(fname.toLowerCase().contains(pName)){ player.add(fname); } } if(player.size()==0){ sendMessage(requester,"I looked high and low, but I couldnt find that pony! :C"); return null; } if(player.size()>1){ tooManyMatches(player,requester); return null; } return player.get(0); }
protected String getSinglePlayer(String pName, CommandSender requester){ pName = pName.toLowerCase(); ArrayList<String> player = new ArrayList<String>(); File dir = new File(Mane.getInstance().getDataFolder()+File.separator+"Players"); if(!dir.isDirectory()){ sendMessage(requester,"I looked high and low, but I couldnt find that pony! :C"); return null; } File[] files = dir.listFiles(); for(File file : files){ String fname = file.getName(); if(fname.toLowerCase().equals(pName)){ return fname; } if(fname.toLowerCase().contains(pName)){ player.add(fname); } } if(player.size()==0){ sendMessage(requester,"I looked high and low, but I couldnt find that pony! :C"); return null; } if(player.size()>1){ tooManyMatches(player,requester); return null; } return player.get(0); }
diff --git a/src/xutil/src/com/vangent/hieos/xutil/hl7/date/Hl7Date.java b/src/xutil/src/com/vangent/hieos/xutil/hl7/date/Hl7Date.java index 9827274e..f00716d4 100644 --- a/src/xutil/src/com/vangent/hieos/xutil/hl7/date/Hl7Date.java +++ b/src/xutil/src/com/vangent/hieos/xutil/hl7/date/Hl7Date.java @@ -1,127 +1,127 @@ /* * This code is subject to the HIEOS License, Version 1.0 * * Copyright(c) 2008-2009 Vangent, Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package com.vangent.hieos.xutil.hl7.date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Formatter; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; /** * Class to produce dates in HL7 format. * */ public class Hl7Date { /** * Do not allow instances to be created. */ private Hl7Date() { } /** * Return current time in HL7 format as: YYYYMMDDHHMMSS. * * @return HL7 date as string. */ static public String now() { StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); Calendar c = new GregorianCalendar(); formatter.format("%s%02d%02d%02d%02d%02d", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND)); return sb.toString(); } /** * Return current time (minus 1 year) in HL7 format as YYYYMMDDHHMMSS. This method * has no practical purpose beyond for test support. * * @return Current time (minus 1 year) in HL7 format. */ static public String lastyear() { StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); Calendar c = new GregorianCalendar(); formatter.format("%s%02d%02d%02d%02d%02d", c.get(Calendar.YEAR) - 1, c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND)); return sb.toString(); } /** * Convert a Java date to HL7 format. * * @param date Java date. * @return String In HL7 format. */ static public String toHL7format(Date date) { String hl7DateFormat = "yyyyMMdd"; SimpleDateFormat formatter = new SimpleDateFormat(hl7DateFormat); Calendar c = Calendar.getInstance(); c.setTime(date); TimeZone timeZone = TimeZone.getTimeZone("UTC"); formatter.setTimeZone(timeZone); String hl7formattedDate = formatter.format(date); hl7formattedDate.replaceAll("UTC", "Z"); return hl7formattedDate; } /** * Return a Java Date instance given an HL7 formatted date string. * * @param hl7date HL7 formatted date. * @return A Java Date. */ public static Date getDateFromHL7Format(String hl7date) { // TBD: FIXUP/MOVE CODE Date date = null; if (hl7date != null) { String formatString = "yyyyMMdd"; int len = hl7date.length(); - if (len > 12) { + if (len >= 12) { hl7date = hl7date.substring(0, 12); - formatString = "yyyyMMddhhmm"; + formatString = "yyyyMMddHHmm"; } else if (len > 8) { - hl7date.substring(0, 8); + hl7date = hl7date.substring(0, 8); } else if (len < 8) { hl7date = "00000101"; // FIXME: HACK TO STAND OUT } SimpleDateFormat sdf = new SimpleDateFormat(formatString); try { date = sdf.parse(hl7date); } catch (ParseException ex) { // Do nothing. } } else { // TBD: EMIT WARNING OF SOME SORT. } return date; } }
false
true
public static Date getDateFromHL7Format(String hl7date) { // TBD: FIXUP/MOVE CODE Date date = null; if (hl7date != null) { String formatString = "yyyyMMdd"; int len = hl7date.length(); if (len > 12) { hl7date = hl7date.substring(0, 12); formatString = "yyyyMMddhhmm"; } else if (len > 8) { hl7date.substring(0, 8); } else if (len < 8) { hl7date = "00000101"; // FIXME: HACK TO STAND OUT } SimpleDateFormat sdf = new SimpleDateFormat(formatString); try { date = sdf.parse(hl7date); } catch (ParseException ex) { // Do nothing. } } else { // TBD: EMIT WARNING OF SOME SORT. } return date; }
public static Date getDateFromHL7Format(String hl7date) { // TBD: FIXUP/MOVE CODE Date date = null; if (hl7date != null) { String formatString = "yyyyMMdd"; int len = hl7date.length(); if (len >= 12) { hl7date = hl7date.substring(0, 12); formatString = "yyyyMMddHHmm"; } else if (len > 8) { hl7date = hl7date.substring(0, 8); } else if (len < 8) { hl7date = "00000101"; // FIXME: HACK TO STAND OUT } SimpleDateFormat sdf = new SimpleDateFormat(formatString); try { date = sdf.parse(hl7date); } catch (ParseException ex) { // Do nothing. } } else { // TBD: EMIT WARNING OF SOME SORT. } return date; }
diff --git a/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/listeners/PSPlayerListener.java b/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/listeners/PSPlayerListener.java index 17b4be4..d616040 100644 --- a/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/listeners/PSPlayerListener.java +++ b/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/listeners/PSPlayerListener.java @@ -1,1942 +1,1942 @@ package net.sacredlabyrinth.Phaed.PreciousStones.listeners; import net.sacredlabyrinth.Phaed.PreciousStones.*; import net.sacredlabyrinth.Phaed.PreciousStones.entries.BlockTypeEntry; import net.sacredlabyrinth.Phaed.PreciousStones.entries.FieldSign; import net.sacredlabyrinth.Phaed.PreciousStones.entries.PlayerEntry; import net.sacredlabyrinth.Phaed.PreciousStones.vectors.Field; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.player.*; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.Collection; import java.util.List; /** * PreciousStones player listener * * @author Phaed */ public class PSPlayerListener implements Listener { private final PreciousStones plugin; /** * */ public PSPlayerListener() { plugin = PreciousStones.getInstance(); } @EventHandler(priority = EventPriority.HIGHEST) public void onCommand(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.ALL); if (field != null) { if (field.getSettings().isCanceledCommand(event.getMessage()) || field.isBlacklistedCommand(event.getMessage())) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.commandblacklist")) { ChatBlock.send(player, "commandCanceled"); event.setCancelled(true); } } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerLogin(PlayerLoginEvent event) { final String playerName = event.getPlayer().getName(); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { plugin.getPlayerManager().playerLogin(playerName); plugin.getStorageManager().offerPlayer(playerName); plugin.getForceFieldManager().enableFieldsOnLogon(playerName); plugin.getForceFieldManager().removeFieldsIfNoPermission(playerName); } }, 10); } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerQuit(PlayerQuitEvent event) { plugin.getPlayerManager().playerLogoff(event.getPlayer()); plugin.getStorageManager().offerPlayer(event.getPlayer().getName()); plugin.getEntryManager().leaveAllFields(event.getPlayer()); plugin.getForceFieldManager().disableFieldsOnLogoff(event.getPlayer().getName()); } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerSneak(PlayerToggleSneakEvent event) { Player player = event.getPlayer(); Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.TELEPORT_ON_SNEAK); if (field != null) { if (FieldFlag.TELEPORT_ON_SNEAK.applies(field, player)) { plugin.getTeleportationManager().teleport(player, field); } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerRespawn(PlayerRespawnEvent event) { handlePlayerSpawn(event.getPlayer()); } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerJoin(final PlayerJoinEvent event) { handlePlayerSpawn(event.getPlayer()); } private void handlePlayerSpawn(Player player) { // refund confiscated items if not in confiscation fields Field confField = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.CONFISCATE_ITEMS); if (confField == null) { plugin.getConfiscationManager().returnItems(player); } // undo a player's visualization if it exists if (plugin.getSettingsManager().isVisualizeEndOnMove()) { if (!plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize")) { if (!plugin.getCuboidManager().hasOpenCuboid(player)) { plugin.getVisualizationManager().revert(player); } } } // remove player from any entry field he is not currently in List<Field> entryFields = plugin.getEntryManager().getPlayerEntryFields(player); if (entryFields != null) { for (Field entryField : entryFields) { if (!entryField.envelops(player.getLocation())) { plugin.getEntryManager().leaveField(player, entryField); if (!plugin.getEntryManager().containsSameNameOwnedField(player, entryField)) { plugin.getEntryManager().leaveOverlappedArea(player, entryField); } } } } // get all the fields the player is currently standing in List<Field> currentFields = plugin.getForceFieldManager().getEnabledSourceFields(player.getLocation(), FieldFlag.ALL); // check for prevent-entry fields and teleport him away if hes not allowed in it if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.entry")) { for (Field field : currentFields) { if (FieldFlag.PREVENT_ENTRY.applies(field, player)) { Location loc = plugin.getPlayerManager().getOutsideFieldLocation(field, player); Location outside = plugin.getPlayerManager().getOutsideLocation(player); if (outside != null) { Field f = plugin.getForceFieldManager().getEnabledSourceField(outside, FieldFlag.PREVENT_ENTRY); if (f != null) { loc = outside; } } player.teleport(loc); plugin.getCommunicationManager().warnEntry(player, field); return; } } } // did not get teleported out so now we update his last known outside location plugin.getPlayerManager().updateOutsideLocation(player); // enter all fields hes is not currently entered into yet for (Field currentField : currentFields) { if (!plugin.getEntryManager().enteredField(player, currentField)) { if (!plugin.getEntryManager().containsSameNameOwnedField(player, currentField)) { plugin.getEntryManager().enterOverlappedArea(player, currentField); } plugin.getEntryManager().enterField(player, currentField); } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerTeleport(PlayerTeleportEvent event) { if (event.isCancelled()) { return; } if (event.getFrom() == null || event.getTo() == null) { return; } if (Helper.isSameLocation(event.getFrom(), event.getTo())) { return; } Player player = event.getPlayer(); Field field = plugin.getForceFieldManager().getEnabledSourceField(event.getTo(), FieldFlag.PREVENT_TELEPORT); if (field != null) { if (FieldFlag.PREVENT_TELEPORT.applies(field, player)) { if (!plugin.getPermissionsManager().has(event.getPlayer(), "preciousstones.bypass.teleport")) { event.setCancelled(true); ChatBlock.send(player, "cannotTeleportInsideField"); return; } } } // undo a player's visualization if it exists if (!Helper.isSameBlock(event.getFrom(), event.getTo())) { if (plugin.getSettingsManager().isVisualizeEndOnMove()) { if (!plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize")) { if (!plugin.getCuboidManager().hasOpenCuboid(player)) { plugin.getVisualizationManager().revert(player); } } } } // remove player from any entry field he is currently in that he is not going to be standing in List<Field> currentFields = plugin.getEntryManager().getPlayerEntryFields(player); if (currentFields != null) { for (Field entryField : currentFields) { if (!entryField.envelops(event.getTo())) { plugin.getEntryManager().leaveField(player, entryField); if (!plugin.getEntryManager().containsSameNameOwnedField(player, entryField)) { plugin.getEntryManager().leaveOverlappedArea(player, entryField); } } } } // get all the fields the player is going to be standing in List<Field> futureFields = plugin.getForceFieldManager().getEnabledSourceFields(event.getTo(), FieldFlag.ALL); // check for prevent-entry fields and teleport him away if hes not allowed in it if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.entry")) { for (Field futureField : futureFields) { if (FieldFlag.PREVENT_ENTRY.applies(futureField, player)) { Location loc = plugin.getPlayerManager().getOutsideFieldLocation(futureField, player); Location outside = plugin.getPlayerManager().getOutsideLocation(player); if (outside != null) { Field f = plugin.getForceFieldManager().getEnabledSourceField(outside, FieldFlag.PREVENT_ENTRY); if (f != null) { loc = outside; } } event.setTo(loc); plugin.getCommunicationManager().warnEntry(player, field); return; } } } // did not get teleported out so now we update his last known outside location plugin.getPlayerManager().updateOutsideLocation(player); // enter all future fields hes is not currently entered into yet for (Field futureField : futureFields) { if (!plugin.getEntryManager().enteredField(player, futureField)) { if (!plugin.getEntryManager().containsSameNameOwnedField(player, futureField)) { plugin.getEntryManager().enterOverlappedArea(player, futureField); } plugin.getEntryManager().enterField(player, futureField); } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerMove(PlayerMoveEvent event) { if (event.isCancelled()) { return; } if (event.getFrom() == null || event.getTo() == null) { return; } if (Helper.isSameLocation(event.getFrom(), event.getTo())) { return; } if (plugin.getSettingsManager().isOncePerBlockOnMove()) { if (Helper.isSameBlock(event.getFrom(), event.getTo())) { return; } } if (plugin.getSettingsManager().isBlacklistedWorld(event.getPlayer().getLocation().getWorld())) { return; } final Player player = event.getPlayer(); // undo a player's visualization if it exists if (!Helper.isSameBlock(event.getFrom(), event.getTo())) { if (plugin.getSettingsManager().isVisualizeEndOnMove()) { if (!plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize")) { if (!plugin.getCuboidManager().hasOpenCuboid(player)) { plugin.getVisualizationManager().revert(player); } } } } // remove player from any entry field he is currently in that he is not going to be standing in List<Field> currentFields = plugin.getEntryManager().getPlayerEntryFields(player); if (currentFields != null) { for (Field entryField : currentFields) { if (!entryField.envelops(event.getTo())) { plugin.getEntryManager().leaveField(player, entryField); if (!plugin.getEntryManager().containsSameNameOwnedField(player, entryField)) { plugin.getEntryManager().leaveOverlappedArea(player, entryField); } } } } // get all the fields the player is going to be standing in List<Field> futureFields = plugin.getForceFieldManager().getEnabledSourceFields(event.getTo(), FieldFlag.ALL); // check for prevent-entry fields and teleport him away if hes not allowed in it if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.entry")) { for (Field field : futureFields) { if (FieldFlag.PREVENT_ENTRY.applies(field, player)) { Location loc = plugin.getPlayerManager().getOutsideFieldLocation(field, player); Location outside = plugin.getPlayerManager().getOutsideLocation(player); if (outside != null) { Field f = plugin.getForceFieldManager().getEnabledSourceField(outside, FieldFlag.PREVENT_ENTRY); if (f != null) { loc = outside; } } event.setTo(loc); plugin.getCommunicationManager().warnEntry(player, field); return; } } } // teleport due to walking on blocks for (Field field : futureFields) { if (field.hasFlag(FieldFlag.TELEPORT_IF_NOT_WALKING_ON) || field.hasFlag(FieldFlag.TELEPORT_IF_WALKING_ON)) { if (field.getSettings().teleportDueToWalking(event.getTo(), field, player)) { plugin.getTeleportationManager().teleport(player, field, "teleportAnnounceWalking"); } } } // did not get teleported out so now we update his last known outside location plugin.getPlayerManager().updateOutsideLocation(player); // enter all future fields hes is not currently entered into yet for (final Field futureField : futureFields) { if (!plugin.getEntryManager().enteredField(player, futureField)) { if (!plugin.getEntryManager().containsSameNameOwnedField(player, futureField)) { plugin.getEntryManager().enterOverlappedArea(player, futureField); } plugin.getEntryManager().enterField(player, futureField); } if (futureField.hasFlag(FieldFlag.TELEPORT_IF_HAS_ITEMS) || futureField.hasFlag(FieldFlag.TELEPORT_IF_NOT_HAS_ITEMS)) { PlayerInventory inventory = player.getInventory(); ItemStack[] contents = inventory.getContents(); boolean hasItem = false; for (ItemStack stack : contents) { if (stack == null || stack.getTypeId() == 0) { continue; } if (futureField.getSettings().isTeleportHasItem(stack.getTypeId())) { if (FieldFlag.TELEPORT_IF_HAS_ITEMS.applies(futureField, player)) { PlayerEntry entry = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (!entry.isTeleporting()) { entry.setTeleporting(true); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.getTeleportationManager().teleport(player, futureField, "teleportAnnounceHasItems"); } }, 0); } return; } } if (FieldFlag.TELEPORT_IF_NOT_HAS_ITEMS.applies(futureField, player)) { if (futureField.getSettings().isTeleportHasNotItem(stack.getTypeId())) { hasItem = true; } } } if (!hasItem) { if (FieldFlag.TELEPORT_IF_NOT_HAS_ITEMS.applies(futureField, player)) { PlayerEntry entry = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (!entry.isTeleporting()) { entry.setTeleporting(true); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.getTeleportationManager().teleport(player, futureField, "teleportAnnounceNotHasItems"); } }, 0); } return; } } } ItemStack itemInHand = player.getItemInHand(); if (itemInHand != null && itemInHand.getTypeId() != 0) { if (futureField.getSettings().isTeleportHoldingItem(itemInHand.getTypeId())) { if (FieldFlag.TELEPORT_IF_HOLDING_ITEMS.applies(futureField, player)) { PlayerEntry entry = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (!entry.isTeleporting()) { entry.setTeleporting(true); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.getTeleportationManager().teleport(player, futureField, "teleportAnnounceHoldingItems"); } }, 0); } return; } } } itemInHand = player.getItemInHand(); if (itemInHand != null && itemInHand.getTypeId() != 0) { if (!futureField.getSettings().isTeleportNotHoldingItem(itemInHand.getTypeId())) { if (FieldFlag.TELEPORT_IF_NOT_HOLDING_ITEMS.applies(futureField, player)) { PlayerEntry entry = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (!entry.isTeleporting()) { entry.setTeleporting(true); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.getTeleportationManager().teleport(player, futureField, "teleportAnnounceNotHoldingItems"); } }, 0); return; } } } } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { if (plugin.getSettingsManager().isBlacklistedWorld(event.getPlayer().getLocation().getWorld())) { return; } final Player player = event.getPlayer(); Entity entity = event.getRightClicked(); if (entity.getType().equals(EntityType.ITEM_FRAME)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.item-frame-take")) { Field field = plugin.getForceFieldManager().getEnabledSourceField(entity.getLocation(), FieldFlag.PREVENT_ITEM_FRAME_TAKE); if (field != null) { if (FieldFlag.PREVENT_ITEM_FRAME_TAKE.applies(field, player)) { event.setCancelled(true); } } } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerInteract(PlayerInteractEvent event) { if (plugin.getSettingsManager().isBlacklistedWorld(event.getPlayer().getLocation().getWorld())) { return; } final Player player = event.getPlayer(); Block block = event.getClickedBlock(); ItemStack is = player.getItemInHand(); if (player == null) { return; } // -------------------------------------------------------------------------------- interacting with use protected block if (block != null) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.use")) { Field useField = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_USE); if (useField != null) { if (FieldFlag.PREVENT_USE.applies(useField, player)) { if (!useField.getSettings().canUse(block.getTypeId())) { plugin.getCommunicationManager().warnUse(player, block, useField); event.setCancelled(true); return; } } } } } // -------------------------------------------------------------------------------- renting time if (block != null) { if (SignHelper.isSign(block)) { FieldSign s = new FieldSign(block); if (s.isValid()) { Field field = s.getField(); if (!field.isOwner(player.getName())) { if (field.isDisabled()) { ChatBlock.send(player, "fieldSignCannotRentDisabled"); event.setCancelled(true); return; } if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (s.isRentable() || s.isShareable()) { if (s.isRentable()) { if (field.isRented()) { if (!field.isRenter(player.getName())) { ChatBlock.send(player, "fieldSignAlreadyRented"); plugin.getCommunicationManager().showRenterInfo(player, field); event.setCancelled(true); return; } else { if (player.isSneaking()) { field.abandonRent(player); ChatBlock.send(player, "fieldSignRentAbandoned"); event.setCancelled(true); return; } } } } if (field.rent(player, s)) { if (s.isRentable()) { s.setRentedColor(); } else if (s.isShareable()) { s.setSharedColor(); } event.setCancelled(true); return; } return; } if (s.isBuyable()) { if (field.hasPendingPurchase()) { ChatBlock.send(player, "fieldSignAlreadyBought"); } else if (field.buy(player, s)) { s.setBoughtColor(player); PreciousStones.getInstance().getForceFieldManager().addAllowed(field, player.getName()); ChatBlock.send(player, "fieldSignBoughtAndAllowed"); } event.setCancelled(true); return; } } if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (s.isRentable()) { if (field.isRented() && !field.isRenter(player.getName())) { ChatBlock.send(player, "fieldSignAlreadyRented"); plugin.getCommunicationManager().showRenterInfo(player, field); event.setCancelled(true); return; } } plugin.getVisualizationManager().visualizeSingleOutline(player, field, true); plugin.getCommunicationManager().showFieldDetails(player, field); plugin.getCommunicationManager().showRenterInfo(player, field); } event.setCancelled(true); return; } else { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (field.hasPendingPurchase()) { field.retrievePurchase(player); s.eject(); event.setCancelled(true); return; } if (field.isRented()) { if (field.hasPendingPayments()) { field.retrievePayment(player); } else { plugin.getCommunicationManager().showRenterInfo(player, field); } } else { ChatBlock.send(player, "fieldSignNoTennant"); } event.setCancelled(true); return; } } } } } // -------------------------------------------------------------------------------- soil interaction if (block != null) { if (plugin.getSettingsManager().isCrop(block)) { Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.PROTECT_CROPS); if (field != null) { if (FieldFlag.PROTECT_CROPS.applies(field, player)) { event.setCancelled(true); } } } } // -------------------------------------------------------------------------------- actions during an open cuboid boolean hasCuboidHand = is == null || is.getTypeId() == 0 || plugin.getSettingsManager().isToolItemType(is.getTypeId()) || plugin.getSettingsManager().isFieldType(new BlockTypeEntry(is.getTypeId(), is.getData().getData())); if (hasCuboidHand) { if (plugin.getCuboidManager().hasOpenCuboid(player)) { if (player.isSneaking()) { // handle cuboid undo if (event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { plugin.getCuboidManager().revertLastSelection(player); return; } } // handle cuboid expand if (event.getAction().equals(Action.RIGHT_CLICK_AIR)) { plugin.getCuboidManager().expandDirection(player); return; } // handle open cuboid commands if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block target = aiming.getTargetBlock(); if (target == null) { return; } // close the cuboid if the player shift clicks any block if (player.isSneaking()) { plugin.getCuboidManager().closeCuboid(player); return; } // close the cuboid when clicking back to the origin block if (plugin.getCuboidManager().isOpenCuboid(player, target)) { plugin.getCuboidManager().closeCuboid(player); return; } // do not select field blocks if (plugin.getForceFieldManager().getField(target) != null) { return; } // or add to the cuboid selection Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.PREVENT_DESTROY); if (field == null) { field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.GRIEF_REVERT); } if (field != null) { boolean applies = FieldFlag.PROTECT_CROPS.applies(field, player); boolean applies2 = FieldFlag.GRIEF_REVERT.applies(field, player); if (applies || applies2) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { return; } } } // add to the cuboid if (plugin.getCuboidManager().processSelectedBlock(player, target)) { event.setCancelled(true); } return; } } else { // -------------------------------------------------------------------------------- creating a cuboid if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { try { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block target = aiming.getTargetBlock(); if (target == null) { return; } if (player.isSneaking()) { Field field = plugin.getForceFieldManager().getField(target); if (field != null) { if (field.getBlock().getType().equals(Material.AIR)) { return; } if (field.hasFlag(FieldFlag.CUBOID)) { if (field.getParent() != null) { field = field.getParent(); } if (field.isOwner(player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.bypass.cuboid")) { if (field.hasFlag(FieldFlag.TRANSLOCATION)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.cuboid")) { if (field.isNamed()) { if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner())) { ChatBlock.send(player, "cannotReshapeWhileCuboid"); return; } } } } if (plugin.getForceFieldManager().hasSubFields(field)) { ChatBlock.send(player, "cannotRedefineWhileCuboid"); return; } if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled")) { if (field.hasFlag(FieldFlag.REDEFINE_ON_DISABLED)) { if (!field.isDisabled()) { ChatBlock.send(player, "redefineWhileDisabled"); return; } } } if (field.isRented()) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { ChatBlock.send(player, "fieldSignCannotChange"); return; } } plugin.getCuboidManager().openCuboid(player, field); } return; } } } } catch (Exception ex) { } } } } // -------------------------------------------------------------------------------- super pickaxes if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (is != null) { if (is.getTypeId() == 270 || is.getTypeId() == 274 || is.getTypeId() == 278 || is.getTypeId() == 285) { PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (data.isSuperduperpickaxe()) { boolean canDestroy = true; // if superduper then get target block if (data.isSuperduperpickaxe()) { if (event.getAction().equals(Action.LEFT_CLICK_AIR)) { try { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block targetBlock = aiming.getTargetBlock(); if (targetBlock != null) { block = targetBlock; } } catch (Exception ex) { } } } if (block != null) { // check for protections Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_DESTROY); if (field != null) { if (!field.getSettings().inDestroyBlacklist(block)) { if (FieldFlag.PREVENT_DESTROY.applies(field, player)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { canDestroy = false; } } } } field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.GRIEF_REVERT); if (field != null && !field.getSettings().canGrief(block.getTypeId())) { if (FieldFlag.GRIEF_REVERT.applies(field, player)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { canDestroy = false; } } else { plugin.getStorageManager().deleteBlockGrief(block); } } if (!plugin.getWorldGuardManager().canBuild(player, block.getLocation())) { canDestroy = false; } if (plugin.getPermissionsManager().lwcProtected(player, block)) { canDestroy = false; } if (plugin.getPermissionsManager().locketteProtected(player, block)) { canDestroy = false; } // go ahead and do the block destruction if (canDestroy) { // if block is a field then remove it if (plugin.getForceFieldManager().isField(block)) { field = plugin.getForceFieldManager().getField(block); FieldSettings fs = field.getSettings(); if (field == null) { return; } boolean release = false; if (field.isOwner(player.getName())) { plugin.getCommunicationManager().notifyDestroyFF(player, block); release = true; } else if (field.hasFlag(FieldFlag.BREAKABLE)) { plugin.getCommunicationManager().notifyDestroyBreakableFF(player, block); release = true; } else if (field.hasFlag(FieldFlag.ALLOWED_CAN_BREAK)) { if (plugin.getForceFieldManager().isAllowed(block, player.getName())) { plugin.getCommunicationManager().notifyDestroyOthersFF(player, block); release = true; } } else if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.forcefield")) { plugin.getCommunicationManager().notifyBypassDestroyFF(player, block); release = true; } else { plugin.getCommunicationManager().warnDestroyFF(player, block); } if (plugin.getForceFieldManager().hasSubFields(field)) { ChatBlock.send(player, "cannotRemoveWithSubplots"); } if (release) { plugin.getForceFieldManager().releaseNoDrop(field); if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.purchase")) { if (!plugin.getSettingsManager().isNoRefunds()) { int refund = fs.getRefund(); if (refund > -1) { plugin.getForceFieldManager().refund(player, refund); } } } } } // if block is an unbreakable remove it if (plugin.getUnbreakableManager().isUnbreakable(block)) { if (plugin.getUnbreakableManager().isOwner(block, player.getName())) { plugin.getCommunicationManager().notifyDestroyU(player, block); plugin.getUnbreakableManager().release(block); } else if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.unbreakable")) { plugin.getCommunicationManager().notifyBypassDestroyU(player, block); plugin.getUnbreakableManager().release(block); } } // do the final destruction Helper.dropBlock(block); block.setTypeIdAndData(0, (byte) 0, false); } } } } } } // -------------------------------------------------------------------------------- snitch record right click actions if (block != null) { if (event.getAction().equals(Action.PHYSICAL)) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (block.getType().equals(Material.WALL_SIGN)) { plugin.getSnitchManager().recordSnitchShop(player, block); } if (block.getType().equals(Material.WORKBENCH) || block.getType().equals(Material.BED) || block.getType().equals(Material.WOODEN_DOOR) || block.getType().equals(Material.LEVER) || block.getType().equals(Material.MINECART) || block.getType().equals(Material.NOTE_BLOCK) || block.getType().equals(Material.JUKEBOX) || block.getType().equals(Material.STONE_BUTTON)) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (block.getState() instanceof InventoryHolder) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (is != null) { if (plugin.getSettingsManager().isToolItemType(is.getTypeId())) { if (plugin.getSettingsManager().isBypassBlock(block)) { return; } // -------------------------------------------------------------------------------- right clicking on fields try { // makes sure water/see-through fields can be right clicked TargetBlock aiming = new TargetBlock(player, 1000, 0.2, new int[]{0}); Block targetBlock = aiming.getTargetBlock(); if (targetBlock != null && plugin.getForceFieldManager().isField(targetBlock)) { block = targetBlock; } } catch (Exception ex) { } if (plugin.getForceFieldManager().isField(block)) { Field field = plugin.getForceFieldManager().getField(block); if (field.isChild()) { field = field.getParent(); } // only those with permission can use fields if (!field.getSettings().getRequiredPermissionUse().isEmpty()) { if (!plugin.getPermissionsManager().has(player, field.getSettings().getRequiredPermissionUse())) { return; } } // -------------------------------------------------------------------------------- handle changing owners if (field.getNewOwner() != null) { if (field.getNewOwner().equalsIgnoreCase(player.getName())) { PreciousStones plugin = PreciousStones.getInstance(); PreciousStones.getInstance().getStorageManager().changeTranslocationOwner(field, field.getNewOwner()); String oldOwnerName = field.getOwner(); field.changeOwner(); plugin.getStorageManager().offerPlayer(field.getOwner()); - plugin.getStorageManager().offerPlayer(field.getNewOwner()); + plugin.getStorageManager().offerPlayer(oldOwnerName); PreciousStones.getInstance().getStorageManager().offerField(field); ChatBlock.send(player, "takenFieldOwnership", oldOwnerName); Player oldOwner = Bukkit.getServer().getPlayerExact(oldOwnerName); if (oldOwner != null) { ChatBlock.send(oldOwner, "tookOwnership", player.getName()); } return; } else { ChatBlock.send(player, "cannotTakeOwnership", field.getNewOwner()); } } // -------------------------------------------------------------------------------- visualize/enable on sneaking right click if (player.isSneaking()) { if (FieldFlag.VISUALIZE_ON_SRC.applies(field, player)) { if (plugin.getCuboidManager().hasOpenCuboid(player)) { ChatBlock.send(player, "visualizationNotWhileCuboid"); } else { if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize")) { ChatBlock.send(player, "visualizing"); plugin.getVisualizationManager().visualizeSingleField(player, field); } } } if (!field.hasFlag(FieldFlag.TRANSLOCATION)) { if (FieldFlag.ENABLE_ON_SRC.applies(field, player)) { if (field.isDisabled()) { ChatBlock.send(player, "fieldTypeEnabled", field.getSettings().getTitle()); boolean disabled = field.setDisabled(false, player); if (!disabled) { ChatBlock.send(player, "cannotEnable"); return; } field.dirtyFlags(); } else { ChatBlock.send(player, "fieldTypeDisabled", field.getSettings().getTitle()); field.setDisabled(true, player); field.dirtyFlags(); } } } } else { // -------------------------------------------------------------------------------- snitch block right click action if (plugin.getSettingsManager().isSnitchType(block)) { if (plugin.getForceFieldManager().isAllowed(field, player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.admin.details")) { if (!plugin.getCommunicationManager().showSnitchList(player, plugin.getForceFieldManager().getField(block))) { showInfo(field, player); ChatBlock.send(player, "noIntruders"); ChatBlock.sendBlank(player); } return; } } // -------------------------------------------------------------------------------- grief revert right click action if ((field.hasFlag(FieldFlag.GRIEF_REVERT)) && (plugin.getForceFieldManager().isAllowed(block, player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.admin.undo"))) { int size = plugin.getGriefUndoManager().undoGrief(field); if (size == 0) { showInfo(field, player); ChatBlock.send(player, "noGriefRecorded"); ChatBlock.sendBlank(player); } return; } // -------------------------------------------------------------------------------- right click translocation boolean showTranslocations = false; if (plugin.getPermissionsManager().has(player, "preciousstones.translocation.use")) { if (field.hasFlag(FieldFlag.TRANSLOCATION) && plugin.getForceFieldManager().isAllowed(block, player.getName())) { if (!field.isTranslocating()) { if (field.isNamed()) { if (!field.isDisabled()) { if (plugin.getStorageManager().appliedTranslocationCount(field) > 0) { PreciousStones.debug("clearing"); int size = plugin.getTranslocationManager().clearTranslocation(field); plugin.getCommunicationManager().notifyClearTranslocation(field, player, size); return; } else { PreciousStones.debug("disabled"); field.setDisabled(true, player); field.dirtyFlags(); return; } } else { if (plugin.getStorageManager().unappliedTranslocationCount(field) > 0) { PreciousStones.debug("applying"); int size = plugin.getTranslocationManager().applyTranslocation(field); plugin.getCommunicationManager().notifyApplyTranslocation(field, player, size); return; } else { PreciousStones.debug("recording"); boolean disabled = field.setDisabled(false, player); if (!disabled) { ChatBlock.send(player, "cannotEnable"); return; } field.dirtyFlags(); return; } } } else { showTranslocations = true; } } } } // -------------------------------------------------------------------------------- show info right click action if (showInfo(field, player)) { if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle")) { if (showTranslocations) { plugin.getCommunicationManager().notifyStoredTranslocations(player); } else if (!field.isDisabled() && !field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED)) { ChatBlock.send(player, "usageToggle"); } ChatBlock.sendBlank(player); } } } } else if (plugin.getUnbreakableManager().isUnbreakable(block)) { // -------------------------------------------------------------------------------- unbreakable info right click if (plugin.getUnbreakableManager().isOwner(block, player.getName()) || plugin.getSettingsManager().isPublicBlockDetails() || plugin.getPermissionsManager().has(player, "preciousstones.admin.details")) { plugin.getCommunicationManager().showUnbreakableDetails(plugin.getUnbreakableManager().getUnbreakable(block), player); } else { plugin.getCommunicationManager().showUnbreakableDetails(player, block); } } else { // -------------------------------------------------------------------------------- protected surface right click action Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.ALL); if (field != null) { if (plugin.getForceFieldManager().isAllowed(field, player.getName()) || plugin.getSettingsManager().isPublicBlockDetails()) { if (!plugin.getSettingsManager().isDisableGroundInfo()) { plugin.getCommunicationManager().showProtectedLocation(player, block); } } } } } } } } } private boolean showInfo(Field field, Player player) { Block block = field.getBlock(); if (plugin.getForceFieldManager().isAllowed(block, player.getName()) || plugin.getSettingsManager().isPublicBlockDetails() || plugin.getPermissionsManager().has(player, "preciousstones.admin.details")) { if (plugin.getCommunicationManager().showFieldDetails(player, field)) { return true; } else { return false; } } else { plugin.getCommunicationManager().showFieldOwner(player, block); return false; } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerBucketFill(final PlayerBucketFillEvent event) { if (event.isCancelled()) { return; } final Player player = event.getPlayer(); final Block block = event.getBlockClicked(); final Block liquid = block.getRelative(event.getBlockFace()); if (block == null) { return; } if (plugin.getSettingsManager().isBlacklistedWorld(player.getLocation().getWorld())) { return; } // snitch plugin.getSnitchManager().recordSnitchBucketFill(player, block); // -------------------------------------------------------------------------------------- prevent pickup up fields if (plugin.getForceFieldManager().isField(block)) { event.setCancelled(true); return; } // -------------------------------------------------------------------------------------- breaking in a prevent-destroy area Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_DESTROY); if (field != null) { if (!field.getSettings().inDestroyBlacklist(block)) { if (FieldFlag.PREVENT_DESTROY.applies(field, player)) { if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { plugin.getCommunicationManager().notifyBypassDestroy(player, block, field); } else { event.setCancelled(true); plugin.getCommunicationManager().warnDestroyArea(player, block, field); } } } } // -------------------------------------------------------------------------------------- breaking in a grief revert area field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.GRIEF_REVERT); if (field != null) { if (FieldFlag.GRIEF_REVERT.applies(field, player)) { if (field.getSettings().canGrief(block.getTypeId())) { return; } if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { plugin.getCommunicationManager().notifyBypassPlace(player, block, field); } else { event.setCancelled(true); plugin.getCommunicationManager().warnDestroyArea(player, block, field); return; } } } // -------------------------------------------------------------------------------------- breaking in a translocation area if (liquid.isLiquid()) { field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.TRANSLOCATION); if (field != null) { if (field.isNamed()) { plugin.getTranslocationManager().removeBlock(field, block); plugin.getTranslocationManager().flashFieldBlock(field, player); } } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) { if (event.isCancelled()) { return; } final Player player = event.getPlayer(); final Block block = event.getBlockClicked(); final Block liquid = block.getRelative(event.getBlockFace()); Material mat = event.getBucket(); if (plugin.getSettingsManager().isBlacklistedWorld(player.getLocation().getWorld())) { return; } // snitch if (mat.equals(Material.LAVA_BUCKET)) { plugin.getSnitchManager().recordSnitchBucketEmpty(player, block, "LAVA"); } if (mat.equals(Material.WATER_BUCKET)) { plugin.getSnitchManager().recordSnitchBucketEmpty(player, block, "WATER"); } if (mat.equals(Material.MILK_BUCKET)) { plugin.getSnitchManager().recordSnitchBucketEmpty(player, block, "MILK"); } // -------------------------------------------------------------------------------------- placing in a prevent-place area Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_PLACE); if (field != null) { if (!field.getSettings().inPlaceBlacklist(block)) { if (FieldFlag.PREVENT_PLACE.applies(field, player)) { if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.place")) { plugin.getCommunicationManager().notifyBypassPlace(player, block, field); } else { event.setCancelled(true); plugin.getCommunicationManager().warnEmpty(player, block, field); } } } } // -------------------------------------------------------------------------------------- placing in a grief revert area field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.GRIEF_REVERT); if (field != null) { if (FieldFlag.GRIEF_REVERT.applies(field, player)) { if (field.hasFlag(FieldFlag.PLACE_GRIEF)) { if (!plugin.getSettingsManager().isGriefUndoBlackListType(block.getTypeId())) { plugin.getGriefUndoManager().addBlock(field, block, true); plugin.getStorageManager().offerGrief(field); } } else { if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.place")) { plugin.getCommunicationManager().notifyBypassPlace(player, block, field); } else { event.setCancelled(true); plugin.getCommunicationManager().warnPlace(player, block, field); return; } } } } // -------------------------------------------------------------------------------------- placing in a translocation area if (!liquid.isLiquid()) { return; } field = plugin.getForceFieldManager().getEnabledSourceField(liquid.getLocation(), FieldFlag.TRANSLOCATION); if (field != null) { if (FieldFlag.TRANSLOCATION.applies(field, player)) { if (field.getSettings().canTranslocate(new BlockTypeEntry(liquid))) { if (field.getName().length() == 0) { ChatBlock.send(player, "translocatorNameToBegin"); event.setCancelled(true); } if (field.isOverTranslocationMax(1)) { ChatBlock.send(player, "translocationReachedSize"); event.setCancelled(true); return; } final Field finalField = field; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { plugin.getTranslocationManager().addBlock(finalField, liquid); plugin.getTranslocationManager().flashFieldBlock(finalField, player); } }, 5); } } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerGameModeChangeEvent(PlayerGameModeChangeEvent event) { Player player = event.getPlayer(); GameMode gameMode = event.getNewGameMode(); Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.ALL); if (field != null) { if (field.getSettings().getForceEntryGameMode() != null) { if (FieldFlag.ENTRY_GAME_MODE.applies(field, player)) { if (!gameMode.equals(field.getSettings().getForceEntryGameMode())) { ChatBlock.send(player, "cannotChangeGameMode"); event.setCancelled(true); } } } } } /** * @param event */ @EventHandler(priority = EventPriority.LOWEST) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { if (event.isCancelled()) { return; } String[] split = event.getMessage().substring(1).split(" "); if (split.length == 0) { return; } Player player = event.getPlayer(); String command = split[0]; if (command.equals("//")) { if (plugin.getPermissionsManager().has(player, "preciousstones.admin.superduperpickaxe")) { PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (data.isSuperduperpickaxe()) { data.setSuperduperpickaxe(false); ChatBlock.send(player, "pickaxeDisabled"); } else { data.setSuperduperpickaxe(true); ChatBlock.send(player, "pickaxeEnabled"); } plugin.getStorageManager().offerPlayer(player.getName()); event.setCancelled(true); } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPotionSplash(PotionSplashEvent event) { boolean hasHarm = false; ThrownPotion potion = event.getPotion(); Collection<PotionEffect> effects = potion.getEffects(); for (PotionEffect effect : effects) { if (effect.getType().equals(PotionEffectType.BLINDNESS) || effect.getType().equals(PotionEffectType.CONFUSION) || effect.getType().equals(PotionEffectType.HARM) || effect.getType().equals(PotionEffectType.POISON) || effect.getType().equals(PotionEffectType.WEAKNESS) || effect.getType().equals(PotionEffectType.SLOW) || effect.getType().equals(PotionEffectType.SLOW_DIGGING)) { hasHarm = true; } } if (hasHarm) { Collection<LivingEntity> entities = event.getAffectedEntities(); for (LivingEntity entity : entities) { if (entity instanceof Player) { Player player = (Player) entity; Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.PREVENT_PVP); if (field != null) { event.setCancelled(true); } } } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPortalEnter(PlayerPortalEvent event) { Field field = plugin.getForceFieldManager().getEnabledSourceField(event.getPlayer().getLocation(), FieldFlag.PREVENT_PORTAL_ENTER); if (field != null) { if (FieldFlag.PREVENT_PORTAL_ENTER.applies(field, event.getPlayer())) { event.setCancelled(true); } } } /** * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerSprint(PlayerToggleSprintEvent event) { if (event.isSprinting()) { return; } Field field = plugin.getForceFieldManager().getEnabledSourceField(event.getPlayer().getLocation(), FieldFlag.NO_PLAYER_SPRINT); if (field != null) { if (FieldFlag.NO_PLAYER_SPRINT.applies(field, event.getPlayer())) { event.setCancelled(true); } } } }
true
true
public void onPlayerInteract(PlayerInteractEvent event) { if (plugin.getSettingsManager().isBlacklistedWorld(event.getPlayer().getLocation().getWorld())) { return; } final Player player = event.getPlayer(); Block block = event.getClickedBlock(); ItemStack is = player.getItemInHand(); if (player == null) { return; } // -------------------------------------------------------------------------------- interacting with use protected block if (block != null) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.use")) { Field useField = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_USE); if (useField != null) { if (FieldFlag.PREVENT_USE.applies(useField, player)) { if (!useField.getSettings().canUse(block.getTypeId())) { plugin.getCommunicationManager().warnUse(player, block, useField); event.setCancelled(true); return; } } } } } // -------------------------------------------------------------------------------- renting time if (block != null) { if (SignHelper.isSign(block)) { FieldSign s = new FieldSign(block); if (s.isValid()) { Field field = s.getField(); if (!field.isOwner(player.getName())) { if (field.isDisabled()) { ChatBlock.send(player, "fieldSignCannotRentDisabled"); event.setCancelled(true); return; } if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (s.isRentable() || s.isShareable()) { if (s.isRentable()) { if (field.isRented()) { if (!field.isRenter(player.getName())) { ChatBlock.send(player, "fieldSignAlreadyRented"); plugin.getCommunicationManager().showRenterInfo(player, field); event.setCancelled(true); return; } else { if (player.isSneaking()) { field.abandonRent(player); ChatBlock.send(player, "fieldSignRentAbandoned"); event.setCancelled(true); return; } } } } if (field.rent(player, s)) { if (s.isRentable()) { s.setRentedColor(); } else if (s.isShareable()) { s.setSharedColor(); } event.setCancelled(true); return; } return; } if (s.isBuyable()) { if (field.hasPendingPurchase()) { ChatBlock.send(player, "fieldSignAlreadyBought"); } else if (field.buy(player, s)) { s.setBoughtColor(player); PreciousStones.getInstance().getForceFieldManager().addAllowed(field, player.getName()); ChatBlock.send(player, "fieldSignBoughtAndAllowed"); } event.setCancelled(true); return; } } if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (s.isRentable()) { if (field.isRented() && !field.isRenter(player.getName())) { ChatBlock.send(player, "fieldSignAlreadyRented"); plugin.getCommunicationManager().showRenterInfo(player, field); event.setCancelled(true); return; } } plugin.getVisualizationManager().visualizeSingleOutline(player, field, true); plugin.getCommunicationManager().showFieldDetails(player, field); plugin.getCommunicationManager().showRenterInfo(player, field); } event.setCancelled(true); return; } else { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (field.hasPendingPurchase()) { field.retrievePurchase(player); s.eject(); event.setCancelled(true); return; } if (field.isRented()) { if (field.hasPendingPayments()) { field.retrievePayment(player); } else { plugin.getCommunicationManager().showRenterInfo(player, field); } } else { ChatBlock.send(player, "fieldSignNoTennant"); } event.setCancelled(true); return; } } } } } // -------------------------------------------------------------------------------- soil interaction if (block != null) { if (plugin.getSettingsManager().isCrop(block)) { Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.PROTECT_CROPS); if (field != null) { if (FieldFlag.PROTECT_CROPS.applies(field, player)) { event.setCancelled(true); } } } } // -------------------------------------------------------------------------------- actions during an open cuboid boolean hasCuboidHand = is == null || is.getTypeId() == 0 || plugin.getSettingsManager().isToolItemType(is.getTypeId()) || plugin.getSettingsManager().isFieldType(new BlockTypeEntry(is.getTypeId(), is.getData().getData())); if (hasCuboidHand) { if (plugin.getCuboidManager().hasOpenCuboid(player)) { if (player.isSneaking()) { // handle cuboid undo if (event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { plugin.getCuboidManager().revertLastSelection(player); return; } } // handle cuboid expand if (event.getAction().equals(Action.RIGHT_CLICK_AIR)) { plugin.getCuboidManager().expandDirection(player); return; } // handle open cuboid commands if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block target = aiming.getTargetBlock(); if (target == null) { return; } // close the cuboid if the player shift clicks any block if (player.isSneaking()) { plugin.getCuboidManager().closeCuboid(player); return; } // close the cuboid when clicking back to the origin block if (plugin.getCuboidManager().isOpenCuboid(player, target)) { plugin.getCuboidManager().closeCuboid(player); return; } // do not select field blocks if (plugin.getForceFieldManager().getField(target) != null) { return; } // or add to the cuboid selection Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.PREVENT_DESTROY); if (field == null) { field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.GRIEF_REVERT); } if (field != null) { boolean applies = FieldFlag.PROTECT_CROPS.applies(field, player); boolean applies2 = FieldFlag.GRIEF_REVERT.applies(field, player); if (applies || applies2) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { return; } } } // add to the cuboid if (plugin.getCuboidManager().processSelectedBlock(player, target)) { event.setCancelled(true); } return; } } else { // -------------------------------------------------------------------------------- creating a cuboid if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { try { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block target = aiming.getTargetBlock(); if (target == null) { return; } if (player.isSneaking()) { Field field = plugin.getForceFieldManager().getField(target); if (field != null) { if (field.getBlock().getType().equals(Material.AIR)) { return; } if (field.hasFlag(FieldFlag.CUBOID)) { if (field.getParent() != null) { field = field.getParent(); } if (field.isOwner(player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.bypass.cuboid")) { if (field.hasFlag(FieldFlag.TRANSLOCATION)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.cuboid")) { if (field.isNamed()) { if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner())) { ChatBlock.send(player, "cannotReshapeWhileCuboid"); return; } } } } if (plugin.getForceFieldManager().hasSubFields(field)) { ChatBlock.send(player, "cannotRedefineWhileCuboid"); return; } if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled")) { if (field.hasFlag(FieldFlag.REDEFINE_ON_DISABLED)) { if (!field.isDisabled()) { ChatBlock.send(player, "redefineWhileDisabled"); return; } } } if (field.isRented()) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { ChatBlock.send(player, "fieldSignCannotChange"); return; } } plugin.getCuboidManager().openCuboid(player, field); } return; } } } } catch (Exception ex) { } } } } // -------------------------------------------------------------------------------- super pickaxes if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (is != null) { if (is.getTypeId() == 270 || is.getTypeId() == 274 || is.getTypeId() == 278 || is.getTypeId() == 285) { PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (data.isSuperduperpickaxe()) { boolean canDestroy = true; // if superduper then get target block if (data.isSuperduperpickaxe()) { if (event.getAction().equals(Action.LEFT_CLICK_AIR)) { try { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block targetBlock = aiming.getTargetBlock(); if (targetBlock != null) { block = targetBlock; } } catch (Exception ex) { } } } if (block != null) { // check for protections Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_DESTROY); if (field != null) { if (!field.getSettings().inDestroyBlacklist(block)) { if (FieldFlag.PREVENT_DESTROY.applies(field, player)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { canDestroy = false; } } } } field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.GRIEF_REVERT); if (field != null && !field.getSettings().canGrief(block.getTypeId())) { if (FieldFlag.GRIEF_REVERT.applies(field, player)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { canDestroy = false; } } else { plugin.getStorageManager().deleteBlockGrief(block); } } if (!plugin.getWorldGuardManager().canBuild(player, block.getLocation())) { canDestroy = false; } if (plugin.getPermissionsManager().lwcProtected(player, block)) { canDestroy = false; } if (plugin.getPermissionsManager().locketteProtected(player, block)) { canDestroy = false; } // go ahead and do the block destruction if (canDestroy) { // if block is a field then remove it if (plugin.getForceFieldManager().isField(block)) { field = plugin.getForceFieldManager().getField(block); FieldSettings fs = field.getSettings(); if (field == null) { return; } boolean release = false; if (field.isOwner(player.getName())) { plugin.getCommunicationManager().notifyDestroyFF(player, block); release = true; } else if (field.hasFlag(FieldFlag.BREAKABLE)) { plugin.getCommunicationManager().notifyDestroyBreakableFF(player, block); release = true; } else if (field.hasFlag(FieldFlag.ALLOWED_CAN_BREAK)) { if (plugin.getForceFieldManager().isAllowed(block, player.getName())) { plugin.getCommunicationManager().notifyDestroyOthersFF(player, block); release = true; } } else if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.forcefield")) { plugin.getCommunicationManager().notifyBypassDestroyFF(player, block); release = true; } else { plugin.getCommunicationManager().warnDestroyFF(player, block); } if (plugin.getForceFieldManager().hasSubFields(field)) { ChatBlock.send(player, "cannotRemoveWithSubplots"); } if (release) { plugin.getForceFieldManager().releaseNoDrop(field); if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.purchase")) { if (!plugin.getSettingsManager().isNoRefunds()) { int refund = fs.getRefund(); if (refund > -1) { plugin.getForceFieldManager().refund(player, refund); } } } } } // if block is an unbreakable remove it if (plugin.getUnbreakableManager().isUnbreakable(block)) { if (plugin.getUnbreakableManager().isOwner(block, player.getName())) { plugin.getCommunicationManager().notifyDestroyU(player, block); plugin.getUnbreakableManager().release(block); } else if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.unbreakable")) { plugin.getCommunicationManager().notifyBypassDestroyU(player, block); plugin.getUnbreakableManager().release(block); } } // do the final destruction Helper.dropBlock(block); block.setTypeIdAndData(0, (byte) 0, false); } } } } } } // -------------------------------------------------------------------------------- snitch record right click actions if (block != null) { if (event.getAction().equals(Action.PHYSICAL)) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (block.getType().equals(Material.WALL_SIGN)) { plugin.getSnitchManager().recordSnitchShop(player, block); } if (block.getType().equals(Material.WORKBENCH) || block.getType().equals(Material.BED) || block.getType().equals(Material.WOODEN_DOOR) || block.getType().equals(Material.LEVER) || block.getType().equals(Material.MINECART) || block.getType().equals(Material.NOTE_BLOCK) || block.getType().equals(Material.JUKEBOX) || block.getType().equals(Material.STONE_BUTTON)) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (block.getState() instanceof InventoryHolder) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (is != null) { if (plugin.getSettingsManager().isToolItemType(is.getTypeId())) { if (plugin.getSettingsManager().isBypassBlock(block)) { return; } // -------------------------------------------------------------------------------- right clicking on fields try { // makes sure water/see-through fields can be right clicked TargetBlock aiming = new TargetBlock(player, 1000, 0.2, new int[]{0}); Block targetBlock = aiming.getTargetBlock(); if (targetBlock != null && plugin.getForceFieldManager().isField(targetBlock)) { block = targetBlock; } } catch (Exception ex) { } if (plugin.getForceFieldManager().isField(block)) { Field field = plugin.getForceFieldManager().getField(block); if (field.isChild()) { field = field.getParent(); } // only those with permission can use fields if (!field.getSettings().getRequiredPermissionUse().isEmpty()) { if (!plugin.getPermissionsManager().has(player, field.getSettings().getRequiredPermissionUse())) { return; } } // -------------------------------------------------------------------------------- handle changing owners if (field.getNewOwner() != null) { if (field.getNewOwner().equalsIgnoreCase(player.getName())) { PreciousStones plugin = PreciousStones.getInstance(); PreciousStones.getInstance().getStorageManager().changeTranslocationOwner(field, field.getNewOwner()); String oldOwnerName = field.getOwner(); field.changeOwner(); plugin.getStorageManager().offerPlayer(field.getOwner()); plugin.getStorageManager().offerPlayer(field.getNewOwner()); PreciousStones.getInstance().getStorageManager().offerField(field); ChatBlock.send(player, "takenFieldOwnership", oldOwnerName); Player oldOwner = Bukkit.getServer().getPlayerExact(oldOwnerName); if (oldOwner != null) { ChatBlock.send(oldOwner, "tookOwnership", player.getName()); } return; } else { ChatBlock.send(player, "cannotTakeOwnership", field.getNewOwner()); } } // -------------------------------------------------------------------------------- visualize/enable on sneaking right click if (player.isSneaking()) { if (FieldFlag.VISUALIZE_ON_SRC.applies(field, player)) { if (plugin.getCuboidManager().hasOpenCuboid(player)) { ChatBlock.send(player, "visualizationNotWhileCuboid"); } else { if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize")) { ChatBlock.send(player, "visualizing"); plugin.getVisualizationManager().visualizeSingleField(player, field); } } } if (!field.hasFlag(FieldFlag.TRANSLOCATION)) { if (FieldFlag.ENABLE_ON_SRC.applies(field, player)) { if (field.isDisabled()) { ChatBlock.send(player, "fieldTypeEnabled", field.getSettings().getTitle()); boolean disabled = field.setDisabled(false, player); if (!disabled) { ChatBlock.send(player, "cannotEnable"); return; } field.dirtyFlags(); } else { ChatBlock.send(player, "fieldTypeDisabled", field.getSettings().getTitle()); field.setDisabled(true, player); field.dirtyFlags(); } } } } else { // -------------------------------------------------------------------------------- snitch block right click action if (plugin.getSettingsManager().isSnitchType(block)) { if (plugin.getForceFieldManager().isAllowed(field, player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.admin.details")) { if (!plugin.getCommunicationManager().showSnitchList(player, plugin.getForceFieldManager().getField(block))) { showInfo(field, player); ChatBlock.send(player, "noIntruders"); ChatBlock.sendBlank(player); } return; } } // -------------------------------------------------------------------------------- grief revert right click action if ((field.hasFlag(FieldFlag.GRIEF_REVERT)) && (plugin.getForceFieldManager().isAllowed(block, player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.admin.undo"))) { int size = plugin.getGriefUndoManager().undoGrief(field); if (size == 0) { showInfo(field, player); ChatBlock.send(player, "noGriefRecorded"); ChatBlock.sendBlank(player); } return; } // -------------------------------------------------------------------------------- right click translocation boolean showTranslocations = false; if (plugin.getPermissionsManager().has(player, "preciousstones.translocation.use")) { if (field.hasFlag(FieldFlag.TRANSLOCATION) && plugin.getForceFieldManager().isAllowed(block, player.getName())) { if (!field.isTranslocating()) { if (field.isNamed()) { if (!field.isDisabled()) { if (plugin.getStorageManager().appliedTranslocationCount(field) > 0) { PreciousStones.debug("clearing"); int size = plugin.getTranslocationManager().clearTranslocation(field); plugin.getCommunicationManager().notifyClearTranslocation(field, player, size); return; } else { PreciousStones.debug("disabled"); field.setDisabled(true, player); field.dirtyFlags(); return; } } else { if (plugin.getStorageManager().unappliedTranslocationCount(field) > 0) { PreciousStones.debug("applying"); int size = plugin.getTranslocationManager().applyTranslocation(field); plugin.getCommunicationManager().notifyApplyTranslocation(field, player, size); return; } else { PreciousStones.debug("recording"); boolean disabled = field.setDisabled(false, player); if (!disabled) { ChatBlock.send(player, "cannotEnable"); return; } field.dirtyFlags(); return; } } } else { showTranslocations = true; } } } } // -------------------------------------------------------------------------------- show info right click action if (showInfo(field, player)) { if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle")) { if (showTranslocations) { plugin.getCommunicationManager().notifyStoredTranslocations(player); } else if (!field.isDisabled() && !field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED)) { ChatBlock.send(player, "usageToggle"); } ChatBlock.sendBlank(player); } } } } else if (plugin.getUnbreakableManager().isUnbreakable(block)) { // -------------------------------------------------------------------------------- unbreakable info right click if (plugin.getUnbreakableManager().isOwner(block, player.getName()) || plugin.getSettingsManager().isPublicBlockDetails() || plugin.getPermissionsManager().has(player, "preciousstones.admin.details")) { plugin.getCommunicationManager().showUnbreakableDetails(plugin.getUnbreakableManager().getUnbreakable(block), player); } else { plugin.getCommunicationManager().showUnbreakableDetails(player, block); } } else { // -------------------------------------------------------------------------------- protected surface right click action Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.ALL); if (field != null) { if (plugin.getForceFieldManager().isAllowed(field, player.getName()) || plugin.getSettingsManager().isPublicBlockDetails()) { if (!plugin.getSettingsManager().isDisableGroundInfo()) { plugin.getCommunicationManager().showProtectedLocation(player, block); } } } } } } } } }
public void onPlayerInteract(PlayerInteractEvent event) { if (plugin.getSettingsManager().isBlacklistedWorld(event.getPlayer().getLocation().getWorld())) { return; } final Player player = event.getPlayer(); Block block = event.getClickedBlock(); ItemStack is = player.getItemInHand(); if (player == null) { return; } // -------------------------------------------------------------------------------- interacting with use protected block if (block != null) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.use")) { Field useField = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_USE); if (useField != null) { if (FieldFlag.PREVENT_USE.applies(useField, player)) { if (!useField.getSettings().canUse(block.getTypeId())) { plugin.getCommunicationManager().warnUse(player, block, useField); event.setCancelled(true); return; } } } } } // -------------------------------------------------------------------------------- renting time if (block != null) { if (SignHelper.isSign(block)) { FieldSign s = new FieldSign(block); if (s.isValid()) { Field field = s.getField(); if (!field.isOwner(player.getName())) { if (field.isDisabled()) { ChatBlock.send(player, "fieldSignCannotRentDisabled"); event.setCancelled(true); return; } if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (s.isRentable() || s.isShareable()) { if (s.isRentable()) { if (field.isRented()) { if (!field.isRenter(player.getName())) { ChatBlock.send(player, "fieldSignAlreadyRented"); plugin.getCommunicationManager().showRenterInfo(player, field); event.setCancelled(true); return; } else { if (player.isSneaking()) { field.abandonRent(player); ChatBlock.send(player, "fieldSignRentAbandoned"); event.setCancelled(true); return; } } } } if (field.rent(player, s)) { if (s.isRentable()) { s.setRentedColor(); } else if (s.isShareable()) { s.setSharedColor(); } event.setCancelled(true); return; } return; } if (s.isBuyable()) { if (field.hasPendingPurchase()) { ChatBlock.send(player, "fieldSignAlreadyBought"); } else if (field.buy(player, s)) { s.setBoughtColor(player); PreciousStones.getInstance().getForceFieldManager().addAllowed(field, player.getName()); ChatBlock.send(player, "fieldSignBoughtAndAllowed"); } event.setCancelled(true); return; } } if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (s.isRentable()) { if (field.isRented() && !field.isRenter(player.getName())) { ChatBlock.send(player, "fieldSignAlreadyRented"); plugin.getCommunicationManager().showRenterInfo(player, field); event.setCancelled(true); return; } } plugin.getVisualizationManager().visualizeSingleOutline(player, field, true); plugin.getCommunicationManager().showFieldDetails(player, field); plugin.getCommunicationManager().showRenterInfo(player, field); } event.setCancelled(true); return; } else { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (field.hasPendingPurchase()) { field.retrievePurchase(player); s.eject(); event.setCancelled(true); return; } if (field.isRented()) { if (field.hasPendingPayments()) { field.retrievePayment(player); } else { plugin.getCommunicationManager().showRenterInfo(player, field); } } else { ChatBlock.send(player, "fieldSignNoTennant"); } event.setCancelled(true); return; } } } } } // -------------------------------------------------------------------------------- soil interaction if (block != null) { if (plugin.getSettingsManager().isCrop(block)) { Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.PROTECT_CROPS); if (field != null) { if (FieldFlag.PROTECT_CROPS.applies(field, player)) { event.setCancelled(true); } } } } // -------------------------------------------------------------------------------- actions during an open cuboid boolean hasCuboidHand = is == null || is.getTypeId() == 0 || plugin.getSettingsManager().isToolItemType(is.getTypeId()) || plugin.getSettingsManager().isFieldType(new BlockTypeEntry(is.getTypeId(), is.getData().getData())); if (hasCuboidHand) { if (plugin.getCuboidManager().hasOpenCuboid(player)) { if (player.isSneaking()) { // handle cuboid undo if (event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { plugin.getCuboidManager().revertLastSelection(player); return; } } // handle cuboid expand if (event.getAction().equals(Action.RIGHT_CLICK_AIR)) { plugin.getCuboidManager().expandDirection(player); return; } // handle open cuboid commands if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block target = aiming.getTargetBlock(); if (target == null) { return; } // close the cuboid if the player shift clicks any block if (player.isSneaking()) { plugin.getCuboidManager().closeCuboid(player); return; } // close the cuboid when clicking back to the origin block if (plugin.getCuboidManager().isOpenCuboid(player, target)) { plugin.getCuboidManager().closeCuboid(player); return; } // do not select field blocks if (plugin.getForceFieldManager().getField(target) != null) { return; } // or add to the cuboid selection Field field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.PREVENT_DESTROY); if (field == null) { field = plugin.getForceFieldManager().getEnabledSourceField(player.getLocation(), FieldFlag.GRIEF_REVERT); } if (field != null) { boolean applies = FieldFlag.PROTECT_CROPS.applies(field, player); boolean applies2 = FieldFlag.GRIEF_REVERT.applies(field, player); if (applies || applies2) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { return; } } } // add to the cuboid if (plugin.getCuboidManager().processSelectedBlock(player, target)) { event.setCancelled(true); } return; } } else { // -------------------------------------------------------------------------------- creating a cuboid if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { try { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block target = aiming.getTargetBlock(); if (target == null) { return; } if (player.isSneaking()) { Field field = plugin.getForceFieldManager().getField(target); if (field != null) { if (field.getBlock().getType().equals(Material.AIR)) { return; } if (field.hasFlag(FieldFlag.CUBOID)) { if (field.getParent() != null) { field = field.getParent(); } if (field.isOwner(player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.bypass.cuboid")) { if (field.hasFlag(FieldFlag.TRANSLOCATION)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.cuboid")) { if (field.isNamed()) { if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner())) { ChatBlock.send(player, "cannotReshapeWhileCuboid"); return; } } } } if (plugin.getForceFieldManager().hasSubFields(field)) { ChatBlock.send(player, "cannotRedefineWhileCuboid"); return; } if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled")) { if (field.hasFlag(FieldFlag.REDEFINE_ON_DISABLED)) { if (!field.isDisabled()) { ChatBlock.send(player, "redefineWhileDisabled"); return; } } } if (field.isRented()) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { ChatBlock.send(player, "fieldSignCannotChange"); return; } } plugin.getCuboidManager().openCuboid(player, field); } return; } } } } catch (Exception ex) { } } } } // -------------------------------------------------------------------------------- super pickaxes if (event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (is != null) { if (is.getTypeId() == 270 || is.getTypeId() == 274 || is.getTypeId() == 278 || is.getTypeId() == 285) { PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName()); if (data.isSuperduperpickaxe()) { boolean canDestroy = true; // if superduper then get target block if (data.isSuperduperpickaxe()) { if (event.getAction().equals(Action.LEFT_CLICK_AIR)) { try { TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet()); Block targetBlock = aiming.getTargetBlock(); if (targetBlock != null) { block = targetBlock; } } catch (Exception ex) { } } } if (block != null) { // check for protections Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.PREVENT_DESTROY); if (field != null) { if (!field.getSettings().inDestroyBlacklist(block)) { if (FieldFlag.PREVENT_DESTROY.applies(field, player)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { canDestroy = false; } } } } field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.GRIEF_REVERT); if (field != null && !field.getSettings().canGrief(block.getTypeId())) { if (FieldFlag.GRIEF_REVERT.applies(field, player)) { if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.destroy")) { canDestroy = false; } } else { plugin.getStorageManager().deleteBlockGrief(block); } } if (!plugin.getWorldGuardManager().canBuild(player, block.getLocation())) { canDestroy = false; } if (plugin.getPermissionsManager().lwcProtected(player, block)) { canDestroy = false; } if (plugin.getPermissionsManager().locketteProtected(player, block)) { canDestroy = false; } // go ahead and do the block destruction if (canDestroy) { // if block is a field then remove it if (plugin.getForceFieldManager().isField(block)) { field = plugin.getForceFieldManager().getField(block); FieldSettings fs = field.getSettings(); if (field == null) { return; } boolean release = false; if (field.isOwner(player.getName())) { plugin.getCommunicationManager().notifyDestroyFF(player, block); release = true; } else if (field.hasFlag(FieldFlag.BREAKABLE)) { plugin.getCommunicationManager().notifyDestroyBreakableFF(player, block); release = true; } else if (field.hasFlag(FieldFlag.ALLOWED_CAN_BREAK)) { if (plugin.getForceFieldManager().isAllowed(block, player.getName())) { plugin.getCommunicationManager().notifyDestroyOthersFF(player, block); release = true; } } else if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.forcefield")) { plugin.getCommunicationManager().notifyBypassDestroyFF(player, block); release = true; } else { plugin.getCommunicationManager().warnDestroyFF(player, block); } if (plugin.getForceFieldManager().hasSubFields(field)) { ChatBlock.send(player, "cannotRemoveWithSubplots"); } if (release) { plugin.getForceFieldManager().releaseNoDrop(field); if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.purchase")) { if (!plugin.getSettingsManager().isNoRefunds()) { int refund = fs.getRefund(); if (refund > -1) { plugin.getForceFieldManager().refund(player, refund); } } } } } // if block is an unbreakable remove it if (plugin.getUnbreakableManager().isUnbreakable(block)) { if (plugin.getUnbreakableManager().isOwner(block, player.getName())) { plugin.getCommunicationManager().notifyDestroyU(player, block); plugin.getUnbreakableManager().release(block); } else if (plugin.getPermissionsManager().has(player, "preciousstones.bypass.unbreakable")) { plugin.getCommunicationManager().notifyBypassDestroyU(player, block); plugin.getUnbreakableManager().release(block); } } // do the final destruction Helper.dropBlock(block); block.setTypeIdAndData(0, (byte) 0, false); } } } } } } // -------------------------------------------------------------------------------- snitch record right click actions if (block != null) { if (event.getAction().equals(Action.PHYSICAL)) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (block.getType().equals(Material.WALL_SIGN)) { plugin.getSnitchManager().recordSnitchShop(player, block); } if (block.getType().equals(Material.WORKBENCH) || block.getType().equals(Material.BED) || block.getType().equals(Material.WOODEN_DOOR) || block.getType().equals(Material.LEVER) || block.getType().equals(Material.MINECART) || block.getType().equals(Material.NOTE_BLOCK) || block.getType().equals(Material.JUKEBOX) || block.getType().equals(Material.STONE_BUTTON)) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (block.getState() instanceof InventoryHolder) { plugin.getSnitchManager().recordSnitchUsed(player, block); } if (is != null) { if (plugin.getSettingsManager().isToolItemType(is.getTypeId())) { if (plugin.getSettingsManager().isBypassBlock(block)) { return; } // -------------------------------------------------------------------------------- right clicking on fields try { // makes sure water/see-through fields can be right clicked TargetBlock aiming = new TargetBlock(player, 1000, 0.2, new int[]{0}); Block targetBlock = aiming.getTargetBlock(); if (targetBlock != null && plugin.getForceFieldManager().isField(targetBlock)) { block = targetBlock; } } catch (Exception ex) { } if (plugin.getForceFieldManager().isField(block)) { Field field = plugin.getForceFieldManager().getField(block); if (field.isChild()) { field = field.getParent(); } // only those with permission can use fields if (!field.getSettings().getRequiredPermissionUse().isEmpty()) { if (!plugin.getPermissionsManager().has(player, field.getSettings().getRequiredPermissionUse())) { return; } } // -------------------------------------------------------------------------------- handle changing owners if (field.getNewOwner() != null) { if (field.getNewOwner().equalsIgnoreCase(player.getName())) { PreciousStones plugin = PreciousStones.getInstance(); PreciousStones.getInstance().getStorageManager().changeTranslocationOwner(field, field.getNewOwner()); String oldOwnerName = field.getOwner(); field.changeOwner(); plugin.getStorageManager().offerPlayer(field.getOwner()); plugin.getStorageManager().offerPlayer(oldOwnerName); PreciousStones.getInstance().getStorageManager().offerField(field); ChatBlock.send(player, "takenFieldOwnership", oldOwnerName); Player oldOwner = Bukkit.getServer().getPlayerExact(oldOwnerName); if (oldOwner != null) { ChatBlock.send(oldOwner, "tookOwnership", player.getName()); } return; } else { ChatBlock.send(player, "cannotTakeOwnership", field.getNewOwner()); } } // -------------------------------------------------------------------------------- visualize/enable on sneaking right click if (player.isSneaking()) { if (FieldFlag.VISUALIZE_ON_SRC.applies(field, player)) { if (plugin.getCuboidManager().hasOpenCuboid(player)) { ChatBlock.send(player, "visualizationNotWhileCuboid"); } else { if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize")) { ChatBlock.send(player, "visualizing"); plugin.getVisualizationManager().visualizeSingleField(player, field); } } } if (!field.hasFlag(FieldFlag.TRANSLOCATION)) { if (FieldFlag.ENABLE_ON_SRC.applies(field, player)) { if (field.isDisabled()) { ChatBlock.send(player, "fieldTypeEnabled", field.getSettings().getTitle()); boolean disabled = field.setDisabled(false, player); if (!disabled) { ChatBlock.send(player, "cannotEnable"); return; } field.dirtyFlags(); } else { ChatBlock.send(player, "fieldTypeDisabled", field.getSettings().getTitle()); field.setDisabled(true, player); field.dirtyFlags(); } } } } else { // -------------------------------------------------------------------------------- snitch block right click action if (plugin.getSettingsManager().isSnitchType(block)) { if (plugin.getForceFieldManager().isAllowed(field, player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.admin.details")) { if (!plugin.getCommunicationManager().showSnitchList(player, plugin.getForceFieldManager().getField(block))) { showInfo(field, player); ChatBlock.send(player, "noIntruders"); ChatBlock.sendBlank(player); } return; } } // -------------------------------------------------------------------------------- grief revert right click action if ((field.hasFlag(FieldFlag.GRIEF_REVERT)) && (plugin.getForceFieldManager().isAllowed(block, player.getName()) || plugin.getPermissionsManager().has(player, "preciousstones.admin.undo"))) { int size = plugin.getGriefUndoManager().undoGrief(field); if (size == 0) { showInfo(field, player); ChatBlock.send(player, "noGriefRecorded"); ChatBlock.sendBlank(player); } return; } // -------------------------------------------------------------------------------- right click translocation boolean showTranslocations = false; if (plugin.getPermissionsManager().has(player, "preciousstones.translocation.use")) { if (field.hasFlag(FieldFlag.TRANSLOCATION) && plugin.getForceFieldManager().isAllowed(block, player.getName())) { if (!field.isTranslocating()) { if (field.isNamed()) { if (!field.isDisabled()) { if (plugin.getStorageManager().appliedTranslocationCount(field) > 0) { PreciousStones.debug("clearing"); int size = plugin.getTranslocationManager().clearTranslocation(field); plugin.getCommunicationManager().notifyClearTranslocation(field, player, size); return; } else { PreciousStones.debug("disabled"); field.setDisabled(true, player); field.dirtyFlags(); return; } } else { if (plugin.getStorageManager().unappliedTranslocationCount(field) > 0) { PreciousStones.debug("applying"); int size = plugin.getTranslocationManager().applyTranslocation(field); plugin.getCommunicationManager().notifyApplyTranslocation(field, player, size); return; } else { PreciousStones.debug("recording"); boolean disabled = field.setDisabled(false, player); if (!disabled) { ChatBlock.send(player, "cannotEnable"); return; } field.dirtyFlags(); return; } } } else { showTranslocations = true; } } } } // -------------------------------------------------------------------------------- show info right click action if (showInfo(field, player)) { if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle")) { if (showTranslocations) { plugin.getCommunicationManager().notifyStoredTranslocations(player); } else if (!field.isDisabled() && !field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED)) { ChatBlock.send(player, "usageToggle"); } ChatBlock.sendBlank(player); } } } } else if (plugin.getUnbreakableManager().isUnbreakable(block)) { // -------------------------------------------------------------------------------- unbreakable info right click if (plugin.getUnbreakableManager().isOwner(block, player.getName()) || plugin.getSettingsManager().isPublicBlockDetails() || plugin.getPermissionsManager().has(player, "preciousstones.admin.details")) { plugin.getCommunicationManager().showUnbreakableDetails(plugin.getUnbreakableManager().getUnbreakable(block), player); } else { plugin.getCommunicationManager().showUnbreakableDetails(player, block); } } else { // -------------------------------------------------------------------------------- protected surface right click action Field field = plugin.getForceFieldManager().getEnabledSourceField(block.getLocation(), FieldFlag.ALL); if (field != null) { if (plugin.getForceFieldManager().isAllowed(field, player.getName()) || plugin.getSettingsManager().isPublicBlockDetails()) { if (!plugin.getSettingsManager().isDisableGroundInfo()) { plugin.getCommunicationManager().showProtectedLocation(player, block); } } } } } } } } }
diff --git a/core/src/com/shafiq/myfeedle/core/OAuthLogin.java b/core/src/com/shafiq/myfeedle/core/OAuthLogin.java index a110d58..2ced0ff 100644 --- a/core/src/com/shafiq/myfeedle/core/OAuthLogin.java +++ b/core/src/com/shafiq/myfeedle/core/OAuthLogin.java @@ -1,1027 +1,1027 @@ /* * Myfeedle - Android Social Networking Widget * Copyright (C) 2013 Mohd Shafiq Mat Daud * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Mohd Shafiq Mat Daud [email protected] */ package com.shafiq.myfeedle.core; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.appwidget.AppWidgetManager; import android.content.ContentValues; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.Toast; import com.shafiq.myfeedle.core.Myfeedle.Accounts; import com.shafiq.myfeedle.core.Myfeedle.Widget_accounts; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import static com.shafiq.myfeedle.core.Myfeedle.CHATTER; import static com.shafiq.myfeedle.core.Myfeedle.CHATTER_URL_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.CHATTER_URL_ME; import static com.shafiq.myfeedle.core.Myfeedle.FACEBOOK; import static com.shafiq.myfeedle.core.Myfeedle.FACEBOOK_BASE_URL; import static com.shafiq.myfeedle.core.Myfeedle.FACEBOOK_URL_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.FACEBOOK_URL_ME; import static com.shafiq.myfeedle.core.Myfeedle.FOURSQUARE; import static com.shafiq.myfeedle.core.Myfeedle.FOURSQUARE_BASE_URL; import static com.shafiq.myfeedle.core.Myfeedle.FOURSQUARE_URL_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.FOURSQUARE_URL_ME; import static com.shafiq.myfeedle.core.Myfeedle.GOOGLEPLUS; import static com.shafiq.myfeedle.core.Myfeedle.GOOGLEPLUS_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.GOOGLEPLUS_BASE_URL; import static com.shafiq.myfeedle.core.Myfeedle.GOOGLEPLUS_URL_ME; import static com.shafiq.myfeedle.core.Myfeedle.GOOGLE_ACCESS; import static com.shafiq.myfeedle.core.Myfeedle.IDENTICA; import static com.shafiq.myfeedle.core.Myfeedle.IDENTICA_BASE_URL; import static com.shafiq.myfeedle.core.Myfeedle.IDENTICA_URL_ACCESS; import static com.shafiq.myfeedle.core.Myfeedle.IDENTICA_URL_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.IDENTICA_URL_REQUEST; import static com.shafiq.myfeedle.core.Myfeedle.LINKEDIN; import static com.shafiq.myfeedle.core.Myfeedle.LINKEDIN_BASE_URL; import static com.shafiq.myfeedle.core.Myfeedle.LINKEDIN_HEADERS; import static com.shafiq.myfeedle.core.Myfeedle.LINKEDIN_URL_ACCESS; import static com.shafiq.myfeedle.core.Myfeedle.LINKEDIN_URL_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.LINKEDIN_URL_ME; import static com.shafiq.myfeedle.core.Myfeedle.LINKEDIN_URL_REQUEST; import static com.shafiq.myfeedle.core.Myfeedle.MYSPACE; import static com.shafiq.myfeedle.core.Myfeedle.MYSPACE_BASE_URL; import static com.shafiq.myfeedle.core.Myfeedle.MYSPACE_URL_ACCESS; import static com.shafiq.myfeedle.core.Myfeedle.MYSPACE_URL_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.MYSPACE_URL_ME; import static com.shafiq.myfeedle.core.Myfeedle.MYSPACE_URL_REQUEST; import static com.shafiq.myfeedle.core.Myfeedle.PINTEREST; import static com.shafiq.myfeedle.core.Myfeedle.RSS; import static com.shafiq.myfeedle.core.Myfeedle.SMS; import static com.shafiq.myfeedle.core.Myfeedle.Saccess_token; import static com.shafiq.myfeedle.core.Myfeedle.Sdescription; import static com.shafiq.myfeedle.core.Myfeedle.SdisplayName; import static com.shafiq.myfeedle.core.Myfeedle.Sexpires_in; import static com.shafiq.myfeedle.core.Myfeedle.Sid; import static com.shafiq.myfeedle.core.Myfeedle.Simage; import static com.shafiq.myfeedle.core.Myfeedle.Sitem; import static com.shafiq.myfeedle.core.Myfeedle.Slink; import static com.shafiq.myfeedle.core.Myfeedle.Sname; import static com.shafiq.myfeedle.core.Myfeedle.Spubdate; import static com.shafiq.myfeedle.core.Myfeedle.Sscreen_name; import static com.shafiq.myfeedle.core.Myfeedle.Stitle; import static com.shafiq.myfeedle.core.Myfeedle.Surl; import static com.shafiq.myfeedle.core.Myfeedle.TWITTER; import static com.shafiq.myfeedle.core.Myfeedle.TWITTER_BASE_URL; import static com.shafiq.myfeedle.core.Myfeedle.TWITTER_URL_ACCESS; import static com.shafiq.myfeedle.core.Myfeedle.TWITTER_URL_AUTHORIZE; import static com.shafiq.myfeedle.core.Myfeedle.TWITTER_URL_REQUEST; import static com.shafiq.myfeedle.core.MyfeedleTokens.CHATTER_KEY; import static com.shafiq.myfeedle.core.MyfeedleTokens.FACEBOOK_ID; import static com.shafiq.myfeedle.core.MyfeedleTokens.FOURSQUARE_KEY; import static com.shafiq.myfeedle.core.MyfeedleTokens.GOOGLE_CLIENTID; import static com.shafiq.myfeedle.core.MyfeedleTokens.GOOGLE_CLIENTSECRET; import static com.shafiq.myfeedle.core.MyfeedleTokens.IDENTICA_KEY; import static com.shafiq.myfeedle.core.MyfeedleTokens.IDENTICA_SECRET; import static com.shafiq.myfeedle.core.MyfeedleTokens.LINKEDIN_KEY; import static com.shafiq.myfeedle.core.MyfeedleTokens.LINKEDIN_SECRET; import static com.shafiq.myfeedle.core.MyfeedleTokens.MYSPACE_KEY; import static com.shafiq.myfeedle.core.MyfeedleTokens.MYSPACE_SECRET; import static com.shafiq.myfeedle.core.MyfeedleTokens.TWITTER_KEY; import static com.shafiq.myfeedle.core.MyfeedleTokens.TWITTER_SECRET; import static oauth.signpost.OAuth.OAUTH_VERIFIER; //import android.view.View; public class OAuthLogin extends Activity implements OnCancelListener, OnClickListener { private static final String TAG = "OAuthLogin"; private static Uri TWITTER_CALLBACK = Uri.parse("myfeedle://twitter"); private static Uri MYSPACE_CALLBACK = Uri.parse("myfeedle://myspace"); private static Uri CHATTER_CALLBACK = Uri.parse("myfeedle://chatter"); private static Uri FACEBOOK_CALLBACK = Uri.parse("fbconnect://success"); private static Uri FOURSQUARE_CALLBACK = Uri.parse("myfeedle://foursquare"); private static Uri LINKEDIN_CALLBACK = Uri.parse("myfeedle://linkedin"); private static Uri IDENTICA_CALLBACK = Uri.parse("myfeedle://identi.ca"); // private static Uri GOOGLEPLUS_CALLBACK = Uri.parse("http://localhost"); private MyfeedleOAuth mMyfeedleOAuth; private ProgressDialog mLoadingDialog; private int mWidgetId; private long mAccountId; private String mServiceName = "unknown"; private MyfeedleWebView mMyfeedleWebView; private HttpClient mHttpClient; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED); mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()); mLoadingDialog = new ProgressDialog(this); mLoadingDialog.setMessage(getString(R.string.loading)); mLoadingDialog.setCancelable(true); mLoadingDialog.setOnCancelListener(this); mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE); mServiceName = Myfeedle.getServiceName(getResources(), service); mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID); mMyfeedleWebView = new MyfeedleWebView(); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { try { return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3], Boolean.parseBoolean(args[4]), mHttpClient); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthNotAuthorizedException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String url) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); // load the webview if (url != null) { mMyfeedleWebView.open(url); } else { (Toast.makeText(OAuthLogin.this, String.format(getString(R.string.oauth_error), mServiceName), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); switch (service) { case TWITTER: mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET); asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL), String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL), String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case FACEBOOK: mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID, FACEBOOK_CALLBACK.toString())); break; case MYSPACE: mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET); asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case FOURSQUARE: mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY, FOURSQUARE_CALLBACK.toString())); break; case LINKEDIN: mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET); asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE, LINKEDIN_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case SMS: Cursor c = getContentResolver().query(Accounts.getContentUri(this), new String[]{Accounts._ID}, Accounts.SERVICE + "=?", new String[]{Integer.toString(SMS)}, null); if (c.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show(); } else { addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS, null); } c.close(); finish(); break; case RSS: // prompt for RSS url final EditText rss_url = new EditText(this); rss_url.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this) .setTitle(R.string.rss_url) .setView(rss_url) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { // test the url and add if valid, else Toast error mLoadingDialog.show(); (new AsyncTask<String, Void, String>() { String url; @Override protected String doInBackground(String... params) { url = rss_url.getText().toString(); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url)); } @Override protected void onPostExecute(String response) { mLoadingDialog.dismiss(); if (response != null) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document doc = db.parse(is); // test parsing... NodeList nodes = doc.getElementsByTagName(Sitem); if (nodes.getLength() > 0) { // check for an image NodeList images = doc.getElementsByTagName(Simage); if (images.getLength() > 0) { NodeList imageChildren = images.item(0).getChildNodes(); Node n = imageChildren.item(0); if (n.getNodeName().toLowerCase().equals(Surl)) { if (n.hasChildNodes()) { n.getChildNodes().item(0).getNodeValue(); } } } NodeList children = nodes.item(0).getChildNodes(); String date = null; String title = null; String description = null; String link = null; int values_count = 0; for (int child = 0, c2 = children.getLength(); (child < c2) && (values_count < 4); child++) { Node n = children.item(child); if (n.getNodeName().toLowerCase().equals(Spubdate)) { values_count++; if (n.hasChildNodes()) { date = n.getChildNodes().item(0).getNodeValue(); } } else if (n.getNodeName().toLowerCase().equals(Stitle)) { values_count++; if (n.hasChildNodes()) { title = n.getChildNodes().item(0).getNodeValue(); } } else if (n.getNodeName().toLowerCase().equals(Sdescription)) { values_count++; if (n.hasChildNodes()) { StringBuilder sb = new StringBuilder(); NodeList descNodes = n.getChildNodes(); for (int dn = 0, dn2 = descNodes.getLength(); dn < dn2; dn++) { Node descNode = descNodes.item(dn); if (descNode.getNodeType() == Node.TEXT_NODE) { sb.append(descNode.getNodeValue()); } } // strip out the html tags description = sb.toString().replaceAll("\\<(.|\n)*?>", ""); } } else if (n.getNodeName().toLowerCase().equals(Slink)) { values_count++; if (n.hasChildNodes()) { link = n.getChildNodes().item(0).getNodeValue(); } } } if (Myfeedle.HasValues(new String[]{title, description, link, date})) { final EditText url_name = new EditText(OAuthLogin.this); url_name.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this) .setTitle(R.string.rss_channel) .setView(url_name) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog1, int which) { addAccount(url_name.getText().toString(), null, null, 0, RSS, url); dialog1.dismiss(); dialog.dismiss(); finish(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog1, int which) { dialog1.dismiss(); dialog.dismiss(); finish(); } }) .show(); } else { (Toast.makeText(OAuthLogin.this, "Feed is missing standard fields", Toast.LENGTH_LONG)).show(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } catch (ParserConfigurationException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (SAXException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (IOException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } }).execute(rss_url.getText().toString()); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }) .show(); break; case IDENTICA: mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET); asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case GOOGLEPLUS: mMyfeedleWebView.open(String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob")); break; case CHATTER: mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString())); break; case PINTEREST: Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this), new String[]{Accounts._ID}, Accounts.SERVICE + "=?", new String[]{Integer.toString(PINTEREST)}, null); if (pinterestAccount.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG)).show(); } else { (Toast.makeText(OAuthLogin.this, "Pinterest currently allows only public, non-authenticated viewing.", Toast.LENGTH_LONG)).show(); String[] values = getResources().getStringArray(R.array.service_values); String[] entries = getResources().getStringArray(R.array.service_entries); for (int i = 0, l = values.length; i < l; i++) { if (Integer.toString(PINTEREST).equals(values[i])) { addAccount(entries[i], null, null, 0, PINTEREST, null); break; } } } pinterestAccount.close(); finish(); break; default: this.finish(); } } } } private String addAccount(String username, String token, String secret, int expiry, int service, String sid) { String accountId; ContentValues values = new ContentValues(); values.put(Accounts.USERNAME, username); values.put(Accounts.TOKEN, token); values.put(Accounts.SECRET, secret); values.put(Accounts.EXPIRY, expiry); values.put(Accounts.SERVICE, service); values.put(Accounts.SID, sid); if (mAccountId != Myfeedle.INVALID_ACCOUNT_ID) { // re-authenticating accountId = Long.toString(mAccountId); getContentResolver().update(Accounts.getContentUri(this), values, Accounts._ID + "=?", new String[]{Long.toString(mAccountId)}); } else { // new account accountId = getContentResolver().insert(Accounts.getContentUri(this), values).getLastPathSegment(); values.clear(); values.put(Widget_accounts.ACCOUNT, accountId); values.put(Widget_accounts.WIDGET, mWidgetId); getContentResolver().insert(Widget_accounts.getContentUri(this), values); } setResult(RESULT_OK); return accountId; } private class MyfeedleWebView { private WebView mWebView; public MyfeedleWebView() { mWebView = new WebView(OAuthLogin.this); OAuthLogin.this.setContentView(mWebView); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { mLoadingDialog.dismiss(); if (url != null) { Uri uri = Uri.parse(url); UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); matcher.addURI("accounts.google.com", "o/oauth2/approval", 1); if (matcher.match(uri) == 1) { // get the access_token String code = view.getTitle().split("=")[1]; String[] title = view.getTitle().split("="); if (title.length > 0) { code = title[1]; } if (code != null) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String refresh_token = null; @Override protected String doInBackground(String... args) { HttpPost httpPost = new HttpPost(GOOGLE_ACCESS); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("code", args[0])); params.add(new BasicNameValuePair("client_id", GOOGLE_CLIENTID)); params.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENTSECRET)); - params.add(new BasicNameValuePair("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")); + params.add(new BasicNameValuePair("redirect_uri", "http://localhost/oauth2callback")); params.add(new BasicNameValuePair("grant_type", "authorization_code")); String response = null; try { httpPost.setEntity(new UrlEncodedFormEntity(params)); if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost)) != null) { JSONObject j = new JSONObject(response); if (j.has("access_token") && j.has("refresh_token")) { refresh_token = j.getString("refresh_token"); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(GOOGLEPLUS_URL_ME, GOOGLEPLUS_BASE_URL, j.getString("access_token")))); } } else { return null; } } catch (UnsupportedEncodingException e) { Log.e(TAG,e.toString()); } catch (JSONException e) { Log.e(TAG,e.toString()); } return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); boolean finish = true; if (response != null) { try { JSONObject j = new JSONObject(response); if (j.has(Sid) && j.has(SdisplayName)) { addAccount(j.getString(SdisplayName), refresh_token, "", 0, GOOGLEPLUS, j.getString(Sid)); // beta message to user finish = false; AlertDialog.Builder dialog = new AlertDialog.Builder(OAuthLogin.this); dialog.setTitle(Myfeedle.getServiceName(getResources(), GOOGLEPLUS)); dialog.setMessage(R.string.googleplusbeta); dialog.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.cancel(); OAuthLogin.this.finish(); } }); dialog.setCancelable(true); dialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } if (finish) { OAuthLogin.this.finish(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(code); loadingDialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } } } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null) { mLoadingDialog.show(); Uri uri = Uri.parse(url); String host = uri.getHost(); Log.d(TAG, "shouldOverrideUrlLoading, host: " + host); if (TWITTER_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet("http://api.twitter.com/1/account/verify_credentials.json"))); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); addAccount(jobj.getString(Sscreen_name), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, TWITTER, jobj.getString(Sid)); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (FOURSQUARE_CALLBACK.getHost().equals(host)) { // get the access_token String token = ""; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) { token = param[1]; break; } } final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String token; @Override protected String doInBackground(String... args) { token = args[0]; return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(args[1])); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { JSONObject jobj; try { jobj = (new JSONObject(response)).getJSONObject("response").getJSONObject("user"); if (jobj.has("firstName") && jobj.has(Sid)) { addAccount(jobj.getString("firstName") + " " + jobj.getString("lastName"), token, "", 0, FOURSQUARE, jobj.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, String.format(FOURSQUARE_URL_ME, FOURSQUARE_BASE_URL, token)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (FACEBOOK_CALLBACK.getHost().equals(host)) { String token = ""; int expiry = 0; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) { token = param[1]; } else if (Sexpires_in.equals(param[0])) { expiry = param[1] == "0" ? 0 : (int) System.currentTimeMillis() + Integer.parseInt(param[1]) * 1000; } } final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String token; int expiry; @Override protected String doInBackground(String... args) { token = args[0]; expiry = Integer.parseInt(args[1]); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(args[2])); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has(Sname) && jobj.has(Sid)) { addAccount(jobj.getString(Sname), token, "", expiry, FACEBOOK, jobj.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, Integer.toString(expiry), String.format(FACEBOOK_URL_ME, FACEBOOK_BASE_URL, Saccess_token, token)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (MYSPACE_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet(String.format(MYSPACE_URL_ME, MYSPACE_BASE_URL)))); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); JSONObject person = jobj.getJSONObject("person"); if (person.has(SdisplayName) && person.has(Sid)) { addAccount(person.getString(SdisplayName), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, MYSPACE, person.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (LINKEDIN_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_ME, LINKEDIN_BASE_URL)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(httpGet)); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has("firstName") && jobj.has(Sid)) addAccount(jobj.getString("firstName") + " " + jobj.getString("lastName"), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, LINKEDIN, jobj.getString(Sid)); else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (IDENTICA_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet("https://identi.ca/api/account/verify_credentials.json"))); else return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); addAccount(jobj.getString(Sscreen_name), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, IDENTICA, jobj.getString(Sid)); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (CHATTER_CALLBACK.getHost().equals(host)) { // get the access_token String token = null, refresh_token = null, instance_url = null; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) token = Uri.decode(param[1]); else if ("refresh_token".equals(param[0])) refresh_token = Uri.decode(param[1]); else if ("instance_url".equals(param[0])) instance_url = Uri.decode(param[1]); } if ((token != null) && (refresh_token != null) && (instance_url != null)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String refresh_token; @Override protected String doInBackground(String... args) { refresh_token = args[2]; HttpGet httpGet = new HttpGet(String.format(CHATTER_URL_ME, args[1])); httpGet.setHeader("Authorization", "OAuth " + args[0]); return MyfeedleHttpClient.httpResponse(mHttpClient, httpGet); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has(Sname) && jobj.has(Sid)) // save the refresh_token to retrieve updated access_token addAccount(jobj.getString(Sname), refresh_token, "", 0, CHATTER, jobj.getString(Sid)); else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { // check for REST_API enabled (Toast.makeText(OAuthLogin.this, "Salesforce does not allow REST API access for Professional and Group Editions. Please ask them to make it available.", Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, instance_url, refresh_token); mLoadingDialog.dismiss(); loadingDialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); mLoadingDialog.dismiss(); OAuthLogin.this.finish(); } } else return false;// allow google to redirect } return true; } }); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDefaultTextEncodingName("UTF-8"); } public void open(String url) { if (url != null) mWebView.loadUrl(url); else OAuthLogin.this.finish(); } } private String[] getParams(String url) { if (url.contains("?")) return url.substring(url.indexOf("?") + 1).replace("#", "&").split("&"); else if (url.contains("#")) return url.substring(url.indexOf("#") + 1).split("&"); else return new String[0]; } @Override public void onClick(DialogInterface arg0, int arg1) { finish(); } @Override public void onCancel(DialogInterface dialog) { finish(); } }
true
true
public MyfeedleWebView() { mWebView = new WebView(OAuthLogin.this); OAuthLogin.this.setContentView(mWebView); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { mLoadingDialog.dismiss(); if (url != null) { Uri uri = Uri.parse(url); UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); matcher.addURI("accounts.google.com", "o/oauth2/approval", 1); if (matcher.match(uri) == 1) { // get the access_token String code = view.getTitle().split("=")[1]; String[] title = view.getTitle().split("="); if (title.length > 0) { code = title[1]; } if (code != null) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String refresh_token = null; @Override protected String doInBackground(String... args) { HttpPost httpPost = new HttpPost(GOOGLE_ACCESS); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("code", args[0])); params.add(new BasicNameValuePair("client_id", GOOGLE_CLIENTID)); params.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENTSECRET)); params.add(new BasicNameValuePair("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")); params.add(new BasicNameValuePair("grant_type", "authorization_code")); String response = null; try { httpPost.setEntity(new UrlEncodedFormEntity(params)); if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost)) != null) { JSONObject j = new JSONObject(response); if (j.has("access_token") && j.has("refresh_token")) { refresh_token = j.getString("refresh_token"); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(GOOGLEPLUS_URL_ME, GOOGLEPLUS_BASE_URL, j.getString("access_token")))); } } else { return null; } } catch (UnsupportedEncodingException e) { Log.e(TAG,e.toString()); } catch (JSONException e) { Log.e(TAG,e.toString()); } return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); boolean finish = true; if (response != null) { try { JSONObject j = new JSONObject(response); if (j.has(Sid) && j.has(SdisplayName)) { addAccount(j.getString(SdisplayName), refresh_token, "", 0, GOOGLEPLUS, j.getString(Sid)); // beta message to user finish = false; AlertDialog.Builder dialog = new AlertDialog.Builder(OAuthLogin.this); dialog.setTitle(Myfeedle.getServiceName(getResources(), GOOGLEPLUS)); dialog.setMessage(R.string.googleplusbeta); dialog.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.cancel(); OAuthLogin.this.finish(); } }); dialog.setCancelable(true); dialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } if (finish) { OAuthLogin.this.finish(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(code); loadingDialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } } } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null) { mLoadingDialog.show(); Uri uri = Uri.parse(url); String host = uri.getHost(); Log.d(TAG, "shouldOverrideUrlLoading, host: " + host); if (TWITTER_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet("http://api.twitter.com/1/account/verify_credentials.json"))); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); addAccount(jobj.getString(Sscreen_name), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, TWITTER, jobj.getString(Sid)); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (FOURSQUARE_CALLBACK.getHost().equals(host)) { // get the access_token String token = ""; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) { token = param[1]; break; } } final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String token; @Override protected String doInBackground(String... args) { token = args[0]; return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(args[1])); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { JSONObject jobj; try { jobj = (new JSONObject(response)).getJSONObject("response").getJSONObject("user"); if (jobj.has("firstName") && jobj.has(Sid)) { addAccount(jobj.getString("firstName") + " " + jobj.getString("lastName"), token, "", 0, FOURSQUARE, jobj.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, String.format(FOURSQUARE_URL_ME, FOURSQUARE_BASE_URL, token)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (FACEBOOK_CALLBACK.getHost().equals(host)) { String token = ""; int expiry = 0; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) { token = param[1]; } else if (Sexpires_in.equals(param[0])) { expiry = param[1] == "0" ? 0 : (int) System.currentTimeMillis() + Integer.parseInt(param[1]) * 1000; } } final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String token; int expiry; @Override protected String doInBackground(String... args) { token = args[0]; expiry = Integer.parseInt(args[1]); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(args[2])); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has(Sname) && jobj.has(Sid)) { addAccount(jobj.getString(Sname), token, "", expiry, FACEBOOK, jobj.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, Integer.toString(expiry), String.format(FACEBOOK_URL_ME, FACEBOOK_BASE_URL, Saccess_token, token)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (MYSPACE_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet(String.format(MYSPACE_URL_ME, MYSPACE_BASE_URL)))); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); JSONObject person = jobj.getJSONObject("person"); if (person.has(SdisplayName) && person.has(Sid)) { addAccount(person.getString(SdisplayName), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, MYSPACE, person.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (LINKEDIN_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_ME, LINKEDIN_BASE_URL)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(httpGet)); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has("firstName") && jobj.has(Sid)) addAccount(jobj.getString("firstName") + " " + jobj.getString("lastName"), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, LINKEDIN, jobj.getString(Sid)); else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (IDENTICA_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet("https://identi.ca/api/account/verify_credentials.json"))); else return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); addAccount(jobj.getString(Sscreen_name), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, IDENTICA, jobj.getString(Sid)); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (CHATTER_CALLBACK.getHost().equals(host)) { // get the access_token String token = null, refresh_token = null, instance_url = null; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) token = Uri.decode(param[1]); else if ("refresh_token".equals(param[0])) refresh_token = Uri.decode(param[1]); else if ("instance_url".equals(param[0])) instance_url = Uri.decode(param[1]); } if ((token != null) && (refresh_token != null) && (instance_url != null)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String refresh_token; @Override protected String doInBackground(String... args) { refresh_token = args[2]; HttpGet httpGet = new HttpGet(String.format(CHATTER_URL_ME, args[1])); httpGet.setHeader("Authorization", "OAuth " + args[0]); return MyfeedleHttpClient.httpResponse(mHttpClient, httpGet); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has(Sname) && jobj.has(Sid)) // save the refresh_token to retrieve updated access_token addAccount(jobj.getString(Sname), refresh_token, "", 0, CHATTER, jobj.getString(Sid)); else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { // check for REST_API enabled (Toast.makeText(OAuthLogin.this, "Salesforce does not allow REST API access for Professional and Group Editions. Please ask them to make it available.", Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, instance_url, refresh_token); mLoadingDialog.dismiss(); loadingDialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); mLoadingDialog.dismiss(); OAuthLogin.this.finish(); } } else return false;// allow google to redirect } return true; } }); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDefaultTextEncodingName("UTF-8"); }
public MyfeedleWebView() { mWebView = new WebView(OAuthLogin.this); OAuthLogin.this.setContentView(mWebView); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { mLoadingDialog.dismiss(); if (url != null) { Uri uri = Uri.parse(url); UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); matcher.addURI("accounts.google.com", "o/oauth2/approval", 1); if (matcher.match(uri) == 1) { // get the access_token String code = view.getTitle().split("=")[1]; String[] title = view.getTitle().split("="); if (title.length > 0) { code = title[1]; } if (code != null) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String refresh_token = null; @Override protected String doInBackground(String... args) { HttpPost httpPost = new HttpPost(GOOGLE_ACCESS); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("code", args[0])); params.add(new BasicNameValuePair("client_id", GOOGLE_CLIENTID)); params.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENTSECRET)); params.add(new BasicNameValuePair("redirect_uri", "http://localhost/oauth2callback")); params.add(new BasicNameValuePair("grant_type", "authorization_code")); String response = null; try { httpPost.setEntity(new UrlEncodedFormEntity(params)); if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost)) != null) { JSONObject j = new JSONObject(response); if (j.has("access_token") && j.has("refresh_token")) { refresh_token = j.getString("refresh_token"); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(GOOGLEPLUS_URL_ME, GOOGLEPLUS_BASE_URL, j.getString("access_token")))); } } else { return null; } } catch (UnsupportedEncodingException e) { Log.e(TAG,e.toString()); } catch (JSONException e) { Log.e(TAG,e.toString()); } return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); boolean finish = true; if (response != null) { try { JSONObject j = new JSONObject(response); if (j.has(Sid) && j.has(SdisplayName)) { addAccount(j.getString(SdisplayName), refresh_token, "", 0, GOOGLEPLUS, j.getString(Sid)); // beta message to user finish = false; AlertDialog.Builder dialog = new AlertDialog.Builder(OAuthLogin.this); dialog.setTitle(Myfeedle.getServiceName(getResources(), GOOGLEPLUS)); dialog.setMessage(R.string.googleplusbeta); dialog.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.cancel(); OAuthLogin.this.finish(); } }); dialog.setCancelable(true); dialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } if (finish) { OAuthLogin.this.finish(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(code); loadingDialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } } } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null) { mLoadingDialog.show(); Uri uri = Uri.parse(url); String host = uri.getHost(); Log.d(TAG, "shouldOverrideUrlLoading, host: " + host); if (TWITTER_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet("http://api.twitter.com/1/account/verify_credentials.json"))); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); addAccount(jobj.getString(Sscreen_name), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, TWITTER, jobj.getString(Sid)); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (FOURSQUARE_CALLBACK.getHost().equals(host)) { // get the access_token String token = ""; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) { token = param[1]; break; } } final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String token; @Override protected String doInBackground(String... args) { token = args[0]; return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(args[1])); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { JSONObject jobj; try { jobj = (new JSONObject(response)).getJSONObject("response").getJSONObject("user"); if (jobj.has("firstName") && jobj.has(Sid)) { addAccount(jobj.getString("firstName") + " " + jobj.getString("lastName"), token, "", 0, FOURSQUARE, jobj.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, String.format(FOURSQUARE_URL_ME, FOURSQUARE_BASE_URL, token)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (FACEBOOK_CALLBACK.getHost().equals(host)) { String token = ""; int expiry = 0; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) { token = param[1]; } else if (Sexpires_in.equals(param[0])) { expiry = param[1] == "0" ? 0 : (int) System.currentTimeMillis() + Integer.parseInt(param[1]) * 1000; } } final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String token; int expiry; @Override protected String doInBackground(String... args) { token = args[0]; expiry = Integer.parseInt(args[1]); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(args[2])); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has(Sname) && jobj.has(Sid)) { addAccount(jobj.getString(Sname), token, "", expiry, FACEBOOK, jobj.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, Integer.toString(expiry), String.format(FACEBOOK_URL_ME, FACEBOOK_BASE_URL, Saccess_token, token)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (MYSPACE_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet(String.format(MYSPACE_URL_ME, MYSPACE_BASE_URL)))); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); JSONObject person = jobj.getJSONObject("person"); if (person.has(SdisplayName) && person.has(Sid)) { addAccount(person.getString(SdisplayName), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, MYSPACE, person.getString(Sid)); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (LINKEDIN_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) { HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_ME, LINKEDIN_BASE_URL)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(httpGet)); } else { return null; } } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has("firstName") && jobj.has(Sid)) addAccount(jobj.getString("firstName") + " " + jobj.getString("lastName"), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, LINKEDIN, jobj.getString(Sid)); else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (IDENTICA_CALLBACK.getHost().equals(host)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { if (mMyfeedleOAuth.retrieveAccessToken(args[0])) return MyfeedleHttpClient.httpResponse(mHttpClient, mMyfeedleOAuth.getSignedRequest(new HttpGet("https://identi.ca/api/account/verify_credentials.json"))); else return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); addAccount(jobj.getString(Sscreen_name), mMyfeedleOAuth.getToken(), mMyfeedleOAuth.getTokenSecret(), 0, IDENTICA, jobj.getString(Sid)); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(uri.getQueryParameter(OAUTH_VERIFIER)); mLoadingDialog.dismiss(); loadingDialog.show(); } else if (CHATTER_CALLBACK.getHost().equals(host)) { // get the access_token String token = null, refresh_token = null, instance_url = null; String[] parameters = getParams(url); for (String parameter : parameters) { String[] param = parameter.split("="); if (Saccess_token.equals(param[0])) token = Uri.decode(param[1]); else if ("refresh_token".equals(param[0])) refresh_token = Uri.decode(param[1]); else if ("instance_url".equals(param[0])) instance_url = Uri.decode(param[1]); } if ((token != null) && (refresh_token != null) && (instance_url != null)) { final ProgressDialog loadingDialog = new ProgressDialog(OAuthLogin.this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { String refresh_token; @Override protected String doInBackground(String... args) { refresh_token = args[2]; HttpGet httpGet = new HttpGet(String.format(CHATTER_URL_ME, args[1])); httpGet.setHeader("Authorization", "OAuth " + args[0]); return MyfeedleHttpClient.httpResponse(mHttpClient, httpGet); } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has(Sname) && jobj.has(Sid)) // save the refresh_token to retrieve updated access_token addAccount(jobj.getString(Sname), refresh_token, "", 0, CHATTER, jobj.getString(Sid)); else (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } else { // check for REST_API enabled (Toast.makeText(OAuthLogin.this, "Salesforce does not allow REST API access for Professional and Group Editions. Please ask them to make it available.", Toast.LENGTH_LONG)).show(); } OAuthLogin.this.finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); asyncTask.execute(token, instance_url, refresh_token); mLoadingDialog.dismiss(); loadingDialog.show(); } else { (Toast.makeText(OAuthLogin.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); mLoadingDialog.dismiss(); OAuthLogin.this.finish(); } } else return false;// allow google to redirect } return true; } }); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDefaultTextEncodingName("UTF-8"); }
diff --git a/acceptance-webapp/src/main/java/org/exoplatform/acceptance/frontend/security/CrowdAuthenticationProviderMock.java b/acceptance-webapp/src/main/java/org/exoplatform/acceptance/frontend/security/CrowdAuthenticationProviderMock.java index 7c77126..213262a 100644 --- a/acceptance-webapp/src/main/java/org/exoplatform/acceptance/frontend/security/CrowdAuthenticationProviderMock.java +++ b/acceptance-webapp/src/main/java/org/exoplatform/acceptance/frontend/security/CrowdAuthenticationProviderMock.java @@ -1,91 +1,91 @@ /* * Copyright (C) 2011-2013 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.acceptance.frontend.security; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * A basic implementation of {@link AuthenticationProvider} which is using our {@link CrowdAuthenticationProviderMock} to manage users. */ public class CrowdAuthenticationProviderMock implements AuthenticationProvider { private final CrowdUserDetailsServiceMock crowdUserDetailsServiceMock; public CrowdAuthenticationProviderMock(CrowdUserDetailsServiceMock userDetailsService) { this.crowdUserDetailsServiceMock = userDetailsService; } /** * Performs authentication with the same contract as {@link * org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}. * * @param authentication the authentication request object. * @return a fully authenticated object including credentials. May return <code>null</code> if the * <code>AuthenticationProvider</code> is unable to support authentication of the passed * <code>Authentication</code> object. In such a case, the next <code>AuthenticationProvider</code> that * supports the presented <code>Authentication</code> class will be tried. * @throws AuthenticationException if authentication fails. */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); try { UserDetails user = crowdUserDetailsServiceMock.loadUserByUsername(name); if (user.getPassword().equals(password)) { return new UsernamePasswordAuthenticationToken( user.getUsername(), user.getPassword(), user.getAuthorities()); } else { throw new BadCredentialsException("Invalid username or password"); } } catch (UsernameNotFoundException unnfe) { - throw new BadCredentialsException("Invalid username or password",unnfe); + throw new BadCredentialsException("Invalid username or password", unnfe); } } /** * Returns <code>true</code> if this <Code>AuthenticationProvider</code> supports the indicated * <Code>Authentication</code> object. * <p> * Returning <code>true</code> does not guarantee an <code>AuthenticationProvider</code> will be able to * authenticate the presented instance of the <code>Authentication</code> class. It simply indicates it can support * closer evaluation of it. An <code>AuthenticationProvider</code> can still return <code>null</code> from the * {@link #authenticate(Authentication)} method to indicate another <code>AuthenticationProvider</code> should be * tried. * </p> * <p>Selection of an <code>AuthenticationProvider</code> capable of performing authentication is * conducted at runtime the <code>ProviderManager</code>.</p> * * @param authentication * @return <code>true</code> if the implementation can more closely evaluate the <code>Authentication</code> class * presented */ @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } }
true
true
public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); try { UserDetails user = crowdUserDetailsServiceMock.loadUserByUsername(name); if (user.getPassword().equals(password)) { return new UsernamePasswordAuthenticationToken( user.getUsername(), user.getPassword(), user.getAuthorities()); } else { throw new BadCredentialsException("Invalid username or password"); } } catch (UsernameNotFoundException unnfe) { throw new BadCredentialsException("Invalid username or password",unnfe); } }
public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); try { UserDetails user = crowdUserDetailsServiceMock.loadUserByUsername(name); if (user.getPassword().equals(password)) { return new UsernamePasswordAuthenticationToken( user.getUsername(), user.getPassword(), user.getAuthorities()); } else { throw new BadCredentialsException("Invalid username or password"); } } catch (UsernameNotFoundException unnfe) { throw new BadCredentialsException("Invalid username or password", unnfe); } }
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java index d9eb6e626..1d5244dd6 100644 --- a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java +++ b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java @@ -1,727 +1,731 @@ package org.eclipse.birt.report.engine.emitter.excel; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.IExcelRenderOption; import org.eclipse.birt.report.engine.api.IHTMLActionHandler; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.RenderOption; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.engine.content.IAutoTextContent; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IContainerContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IDataContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.content.IHyperlinkAction; import org.eclipse.birt.report.engine.content.IImageContent; import org.eclipse.birt.report.engine.content.ILabelContent; import org.eclipse.birt.report.engine.content.IListBandContent; import org.eclipse.birt.report.engine.content.IListContent; import org.eclipse.birt.report.engine.content.IPageContent; import org.eclipse.birt.report.engine.content.IReportContent; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.content.ITextContent; import org.eclipse.birt.report.engine.css.engine.value.DataFormatValue; import org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter; import org.eclipse.birt.report.engine.emitter.EmitterUtil; import org.eclipse.birt.report.engine.emitter.IEmitterServices; import org.eclipse.birt.report.engine.emitter.excel.layout.ColumnsInfo; import org.eclipse.birt.report.engine.emitter.excel.layout.ContainerSizeInfo; import org.eclipse.birt.report.engine.emitter.excel.layout.ExcelContext; import org.eclipse.birt.report.engine.emitter.excel.layout.ExcelLayoutEngine; import org.eclipse.birt.report.engine.emitter.excel.layout.LayoutUtil; import org.eclipse.birt.report.engine.emitter.excel.layout.PageDef; import org.eclipse.birt.report.engine.ir.DataItemDesign; import org.eclipse.birt.report.engine.ir.DimensionType; import org.eclipse.birt.report.engine.ir.MapDesign; import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign; import org.eclipse.birt.report.engine.layout.pdf.util.HTML2Content; import org.eclipse.birt.report.engine.presentation.ContentEmitterVisitor; import com.ibm.icu.util.TimeZone; import com.ibm.icu.util.ULocale; public class ExcelEmitter extends ContentEmitterAdapter { protected static Logger logger = Logger.getLogger( ExcelEmitter.class .getName( ) ); protected IEmitterServices service = null; protected OutputStream out = null; protected ExcelLayoutEngine engine; ContentEmitterVisitor contentVisitor = new ContentEmitterVisitor( this ); protected IExcelWriter writer; public ExcelContext context = new ExcelContext( ); private String orientation = null; protected String pageHeader; protected String pageFooter; private boolean outputInMasterPage = false; protected boolean isRTLSheet = false; private int sheetIndex = 1; public String getOutputFormat( ) { return "xls"; } public void initialize( IEmitterServices service ) throws EngineException { this.service = service; if ( service != null ) { this.out = EmitterUtil.getOuputStream( service, "report." + getOutputFormat( ) ); } context.setTempFileDir( service.getReportEngine( ).getConfig( ) .getTempDir( ) ); IReportContext reportContext = service.getReportContext( ); if ( reportContext != null ) { Locale locale = reportContext.getLocale( ); if ( locale != null ) { context.setLocale( ULocale.forLocale( locale ) ); } else context.setLocale( ULocale.getDefault( ) ); } } public void start( IReportContent report ) { setupRenderOptions( ); // We can the page size from the design, maybe there is a better way // to get the page definition. String reportOrientation = report.getDesign( ).getReportDesign( ) .getBidiOrientation( ); if ( "rtl".equalsIgnoreCase( reportOrientation ) ) isRTLSheet = true; IStyle style = report.getRoot( ).getComputedStyle( ); SimpleMasterPageDesign master = (SimpleMasterPageDesign) report .getDesign( ).getPageSetup( ).getMasterPage( 0 ); engine = createLayoutEngine( context, this ); engine.initalize( new PageDef( master, style ) ); createWriter( ); } protected ExcelLayoutEngine createLayoutEngine( ExcelContext context, ExcelEmitter emitter ) { return new ExcelLayoutEngine( context, emitter ); } private void setupRenderOptions() { IRenderOption renderOptions = service.getRenderOption( ); Object textWrapping = renderOptions.getOption(IExcelRenderOption.WRAPPING_TEXT); if(textWrapping!=null && textWrapping instanceof Boolean) { context.setWrappingText((Boolean)textWrapping); } else { context.setWrappingText( ( Boolean )true); } Object officeVersion = renderOptions.getOption(IExcelRenderOption.OFFICE_VERSION); if(officeVersion!=null && officeVersion instanceof String) { if(officeVersion.equals( "office2007" )) { context.setOfficeVersion("office2007" ); } } else { context.setOfficeVersion( "office2003" ); } } public void startPage( IPageContent page ) throws BirtException { if ( orientation == null ) { orientation = capitalize( page.getOrientation( ) ); } if(needOutputInMasterPage(page.getPageHeader( ))&& needOutputInMasterPage(page.getPageFooter( ))) { outputInMasterPage = true; pageHeader = formatHeaderFooter( page.getPageHeader( ),true ); pageFooter = formatHeaderFooter( page.getPageFooter( ),false ); } if ( !outputInMasterPage && page.getPageHeader( ) != null ) { contentVisitor.visitChildren( page.getPageHeader( ), null ); } engine.setPageStyle( page.getComputedStyle( ) ); } public void endPage( IPageContent page ) throws BirtException { if(!outputInMasterPage && page.getPageFooter( ) != null) { contentVisitor.visitChildren( page.getPageFooter( ), null ); } } public void startTable( ITableContent table ) { ContainerSizeInfo sizeInfo = engine.getCurrentContainer( ).getSizeInfo( ); int width = sizeInfo.getWidth( ); ColumnsInfo info = LayoutUtil.createTable( table, width ); if( info == null ) { return; } String caption = table.getCaption( ); if(caption != null) { engine.addCaption( caption ); } engine.addTable( table, info, sizeInfo ); } public void startRow( IRowContent row ) { engine.addRow( row.getComputedStyle( ) ); } public void endRow( IRowContent row ) { DimensionType height = row.getHeight( ); double rowHeight = height != null ? ExcelUtil.covertDimensionType( height, 0 ) : 0; engine.endRow( rowHeight ); } public void startCell( ICellContent cell ) { IStyle style = cell.getComputedStyle( ); engine.addCell( cell, cell.getColumn( ), cell.getColSpan( ), cell .getRowSpan( ), style ); } public void endCell( ICellContent cell ) { engine.endCell( ); } public void endTable( ITableContent table ) { engine.endTable(); } public void startList( IListContent list ) { ContainerSizeInfo size = engine.getCurrentContainer( ).getSizeInfo( ); ColumnsInfo table = LayoutUtil.createTable( list, size.getWidth( ) ); engine.addTable( list, table, size ); if(list.getChildren( ) == null) { HyperlinkDef link = parseHyperLink(list); BookmarkDef bookmark = getBookmark( list ); engine.addData( ExcelLayoutEngine.EMPTY, list.getComputedStyle( ), link, bookmark ); } } public void startListBand( IListBandContent listBand ) { engine.addCell( 0, 1, 0, listBand.getComputedStyle( ) ); } public void endListBand( IListBandContent listBand ) { engine.endContainer( ); } public void endList( IListContent list ) { engine.endTable( ); } public void startForeign( IForeignContent foreign ) throws BirtException { if ( IForeignContent.HTML_TYPE.equalsIgnoreCase( foreign.getRawType( ) ) ) { HTML2Content.html2Content( foreign ); HyperlinkDef link = parseHyperLink(foreign); engine.addContainer( foreign.getComputedStyle( ), link ); contentVisitor.visitChildren( foreign, null ); engine.endContainer( ); } } public void startText( ITextContent text ) { HyperlinkDef url = parseHyperLink( text ); BookmarkDef bookmark = getBookmark( text ); engine.addData( text.getText( ), text.getComputedStyle( ), url, bookmark ); } public void startData( IDataContent data ) { addDataContent( data ); } protected Data addDataContent( IDataContent data ) { HyperlinkDef url = parseHyperLink( data ); BookmarkDef bookmark = getBookmark( data ); Data excelData = null; Object generateBy = data.getGenerateBy( ); IStyle style = data.getComputedStyle( ); DataFormatValue dataformat = style.getDataFormat( ); - DataItemDesign design = (DataItemDesign) generateBy; - MapDesign map = design.getMap( ); + MapDesign map = null; + if(generateBy instanceof DataItemDesign ) + { + DataItemDesign design = (DataItemDesign) generateBy; + map = design.getMap( ); + } if ( map != null && map.getRuleCount( ) > 0 && data.getLabelText( ) != null ) { excelData = engine.addData( data.getLabelText( ).trim( ), style, url, bookmark ); } else { String locale = null; int type = ExcelUtil.getType( data.getValue( ) ); if ( type == SheetData.STRING ) { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addData( data.getText( ), style, url, bookmark, locale ); } else if ( type == Data.NUMBER ) { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addData( data.getValue( ), style, url, bookmark, locale ); } else { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addDateTime( data, style, url, bookmark, locale ); } } return excelData; } public void startImage( IImageContent image ) { IStyle style = image.getComputedStyle( ); HyperlinkDef url = parseHyperLink( image ); BookmarkDef bookmark = getBookmark( image ); engine.addImageData( image, style, url, bookmark ); } public void startLabel( ILabelContent label ) { Object design = label.getGenerateBy( ); IContent container = label; while ( design == null ) { container = (IContent) container.getParent( ); design = ( (IContent) container ).getGenerateBy( ); } HyperlinkDef url = parseHyperLink( label ); BookmarkDef bookmark = getBookmark( label ); // If the text is BR and it generated by foreign, // ignore it if ( !( "\n".equalsIgnoreCase( label.getText( ) ) && container instanceof IForeignContent ) ) { engine.addData( label.getText( ), label.getComputedStyle( ), url, bookmark ); } } public void startAutoText( IAutoTextContent autoText ) { HyperlinkDef link = parseHyperLink( autoText ); BookmarkDef bookmark = getBookmark( autoText ); engine.addData( autoText.getText( ) , autoText.getComputedStyle( ), link, bookmark ); } public void outputSheet( ) { engine.cacheBookmarks( sheetIndex ); engine.complete( ); try { outputCacheData( ); } catch ( IOException e ) { logger.log( Level.SEVERE, e.getLocalizedMessage( ), e ); } sheetIndex++; } public void end( IReportContent report ) { // Make sure the engine already calculates all data in cache. engine.cacheBookmarks( sheetIndex ); engine.complete( ); try { writer.start( report, engine.getStyleMap( ), engine .getAllBookmarks( ) ); outputCacheData( ); writer.end( ); } catch ( IOException e ) { logger.log( Level.SEVERE, e.getLocalizedMessage( ), e ); } } protected void createWriter( ) { writer = new ExcelWriter( out, context, isRTLSheet ); } /** * @throws IOException * */ public void outputCacheData( ) throws IOException { writer.startSheet( engine.getCoordinates( ), pageHeader, pageFooter ); Iterator<RowData> it = engine.getIterator( ); while ( it.hasNext( ) ) { outputRowData( it.next( ) ); } writer.endSheet( orientation ); } protected void outputRowData( RowData rowData ) throws IOException { writer.startRow( rowData.getHeight( ) ); SheetData[] data = rowData.getRowdata( ); for ( int i = 0; i < data.length; i++ ) { writer.outputData( data[i] ); } writer.endRow( ); } public HyperlinkDef parseHyperLink( IContent content ) { HyperlinkDef hyperlink = null; IHyperlinkAction linkAction = content.getHyperlinkAction( ); if ( linkAction != null ) { String tooltip = linkAction.getTooltip( ); String bookmark = linkAction.getBookmark( ); IReportRunnable reportRunnable = service.getReportRunnable( ); IReportContext reportContext = service.getReportContext( ); IHTMLActionHandler actionHandler = (IHTMLActionHandler) service .getOption( RenderOption.ACTION_HANDLER ); switch ( linkAction.getType( ) ) { case IHyperlinkAction.ACTION_BOOKMARK : hyperlink = new HyperlinkDef( bookmark, IHyperlinkAction.ACTION_BOOKMARK, tooltip ); break; case IHyperlinkAction.ACTION_HYPERLINK : String url = EmitterUtil.getHyperlinkUrl( linkAction, reportRunnable, actionHandler, reportContext ); hyperlink = new HyperlinkDef( url, IHyperlinkAction.ACTION_HYPERLINK, tooltip ); break; case IHyperlinkAction.ACTION_DRILLTHROUGH : url = EmitterUtil.getHyperlinkUrl( linkAction, reportRunnable, actionHandler, reportContext ); hyperlink = new HyperlinkDef( url, IHyperlinkAction.ACTION_DRILLTHROUGH, tooltip ); break; } } return hyperlink; } protected BookmarkDef getBookmark( IContent content ) { String bookmarkName = content.getBookmark( ); if (bookmarkName == null) return null; BookmarkDef bookmark=new BookmarkDef(content.getBookmark( )); if ( !ExcelUtil.isValidBookmarkName( bookmarkName ) ) { bookmark.setGeneratedName( engine .getGenerateBookmark( bookmarkName ) ); } // !( content.getBookmark( ).startsWith( "__TOC" ) ) ) // bookmark starting with "__TOC" is not OK? return bookmark; } public String capitalize( String orientation ) { if ( orientation.equalsIgnoreCase( "landscape" ) ) { return "Landscape"; } if(orientation.equalsIgnoreCase( "portrait" )) { return "Portrait"; } return null; } public String formatHeaderFooter( IContent headerFooter, boolean isHeader ) { StringBuffer headfoot = new StringBuffer( ); if ( headerFooter != null ) { Collection list = headerFooter.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { Object child = iter.next( ); if ( child instanceof ITableContent ) { headfoot.append( getTableValue( (ITableContent) child ) ); } else processText( headfoot, child ); } return headfoot.toString( ); } return null; } private void processText( StringBuffer buffer, Object child ) { if ( child instanceof IAutoTextContent ) { buffer.append( getAutoText( (IAutoTextContent) child ) ); } else if ( child instanceof ITextContent ) { buffer.append( ( (ITextContent) child ).getText( ) ); } else if ( child instanceof IForeignContent ) { buffer.append( ( (IForeignContent) child ).getRawValue( ) ); } } public boolean needOutputInMasterPage( IContent headerFooter ) { if ( headerFooter != null ) { Collection list = headerFooter.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { Object child = iter.next( ); if ( child instanceof ITableContent ) { int columncount = ( (ITableContent) child ) .getColumnCount( ); int rowcount = ( (ITableContent) child ).getChildren( ) .size( ); if ( columncount > 3 || rowcount > 1 ) { logger .log( Level.WARNING, "Excel page header or footer only accept a table no more than 1 row and 3 columns." ); return false; } if ( isEmbededTable( (ITableContent) child ) ) { logger .log( Level.WARNING, "Excel page header and footer don't support embeded grid." ); return false; } } if ( isHtmlText( child ) ) { logger .log( Level.WARNING, "Excel page header and footer don't support html text." ); return false; } } } return true; } private boolean isHtmlText( Object child ) { return child instanceof IForeignContent && IForeignContent.HTML_TYPE .equalsIgnoreCase( ( (IForeignContent) child ) .getRawType( ) ); } public String getTableValue( ITableContent table ) { StringBuffer tableValue = new StringBuffer( ); Collection list = table.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { Object child = iter.next( ); tableValue.append( getRowValue( (IRowContent) child ) ); } return tableValue.toString( ); } public String getRowValue( IRowContent row ) { StringBuffer rowValue = new StringBuffer( ); Collection list = row.getChildren( ); Iterator iter = list.iterator( ); int cellCount = list.size( ); int currentCellCount = 0; while ( iter.hasNext( ) ) { currentCellCount++; Object child = iter.next( ); switch ( currentCellCount ) { case 1 : rowValue.append( "&L" ); break; case 2 : rowValue.append( "&C" ); break; case 3 : rowValue.append( "&R" ); break; default : break; } rowValue.append( getCellValue( (ICellContent) child ) ); } return rowValue.toString( ); } public String getCellValue( ICellContent cell ) { StringBuffer cellValue = new StringBuffer( ); Collection list = cell.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { processText( cellValue, iter.next( ) ); } return cellValue.toString( ); } private String getAutoText( IAutoTextContent autoText ) { String result = null; int type = autoText.getType( ); if ( type == IAutoTextContent.PAGE_NUMBER ) { result = "&P"; } else if ( type == IAutoTextContent.TOTAL_PAGE ) { result = "&N"; } return result; } private boolean isEmbededTable(ITableContent table) { boolean isEmbeded = false; Collection list = table.getChildren( ); Iterator iterRow = list.iterator( ); while ( iterRow.hasNext( ) ) { Object child = iterRow.next( ); Collection listCell = ( (IRowContent) child ).getChildren( ); Iterator iterCell = listCell.iterator( ); while ( iterCell.hasNext( ) ) { Object cellChild = iterCell.next( ); Collection listCellChild = ( (ICellContent) cellChild ) .getChildren( ); Iterator iterCellChild = listCellChild.iterator( ); while ( iterCellChild.hasNext( ) ) { Object cellchild = iterCellChild.next( ); if ( cellchild instanceof ITableContent ) { isEmbeded = true; } } } } return isEmbeded; } public TimeZone getTimeZone() { if ( service != null ) { IReportContext reportContext = service.getReportContext( ); if ( reportContext != null ) { return reportContext.getTimeZone( ); } } return TimeZone.getDefault( ); } public void endContainer( IContainerContent container ) { engine.removeContainerStyle( ); } public void startContainer( IContainerContent container ) { engine.addContainerStyle( container.getComputedStyle( ) ); } }
true
true
protected Data addDataContent( IDataContent data ) { HyperlinkDef url = parseHyperLink( data ); BookmarkDef bookmark = getBookmark( data ); Data excelData = null; Object generateBy = data.getGenerateBy( ); IStyle style = data.getComputedStyle( ); DataFormatValue dataformat = style.getDataFormat( ); DataItemDesign design = (DataItemDesign) generateBy; MapDesign map = design.getMap( ); if ( map != null && map.getRuleCount( ) > 0 && data.getLabelText( ) != null ) { excelData = engine.addData( data.getLabelText( ).trim( ), style, url, bookmark ); } else { String locale = null; int type = ExcelUtil.getType( data.getValue( ) ); if ( type == SheetData.STRING ) { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addData( data.getText( ), style, url, bookmark, locale ); } else if ( type == Data.NUMBER ) { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addData( data.getValue( ), style, url, bookmark, locale ); } else { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addDateTime( data, style, url, bookmark, locale ); } } return excelData; }
protected Data addDataContent( IDataContent data ) { HyperlinkDef url = parseHyperLink( data ); BookmarkDef bookmark = getBookmark( data ); Data excelData = null; Object generateBy = data.getGenerateBy( ); IStyle style = data.getComputedStyle( ); DataFormatValue dataformat = style.getDataFormat( ); MapDesign map = null; if(generateBy instanceof DataItemDesign ) { DataItemDesign design = (DataItemDesign) generateBy; map = design.getMap( ); } if ( map != null && map.getRuleCount( ) > 0 && data.getLabelText( ) != null ) { excelData = engine.addData( data.getLabelText( ).trim( ), style, url, bookmark ); } else { String locale = null; int type = ExcelUtil.getType( data.getValue( ) ); if ( type == SheetData.STRING ) { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addData( data.getText( ), style, url, bookmark, locale ); } else if ( type == Data.NUMBER ) { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addData( data.getValue( ), style, url, bookmark, locale ); } else { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addDateTime( data, style, url, bookmark, locale ); } } return excelData; }
diff --git a/loci/MultiLUT.java b/loci/MultiLUT.java index c69893e..21b3b34 100644 --- a/loci/MultiLUT.java +++ b/loci/MultiLUT.java @@ -1,479 +1,479 @@ // // MultiLUT.java // package loci; import visad.*; import visad.data.*; import visad.util.*; import visad.bom.*; import visad.java3d.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.IOException; import java.rmi.RemoteException; /** An application for weighted spectral mapping. */ public class MultiLUT extends Object implements ActionListener { private static final int NFILES = 17; private TextType text = null; private RealType element = null, line = null, value = null; private TupleType textTuple = null; private float[][] dataValues = null; private float[][] values = null; private float[][] wedgeSamples = null; private FlatField data = null; private FieldImpl textField = null; private FlatField wedge = null; private DataReferenceImpl[] valueRefs = null; private DataReferenceImpl[] hueRefs = null; private int npixels = 0; private JLabel minmax = null; private DisplayImplJ3D display1 = null; private ScalarMap vmap = null; private ScalarMap hmap = null; private ScalarMap huexmap = null; private DataReferenceImpl lineRef = null; /** * Run with 'java -mx256m MultiLUT' * in directory with SPB1.PIC, SPB2.PIC, ..., SPB17.PIC. */ public static void main(String[] args) throws IOException, VisADException { MultiLUT ml = new MultiLUT(); ml.go(args); } public void go(String[] args) throws IOException, VisADException { String dir = ""; String slash = System.getProperty("file.separator"); if (args.length > 0) { dir = args[0]; if (!dir.endsWith(slash)) dir = dir + slash; } RealTupleType domain = null; Unit unit = null; String name = null; Set set = null; RealType[] valueTypes = new RealType[NFILES]; values = new float[NFILES][]; DefaultFamily loader = new DefaultFamily("loader"); for (int i=0; i<NFILES; i++) { Tuple tuple = (Tuple) loader.open(dir + "SPB" + (i+1) + ".PIC"); FieldImpl field = (FieldImpl) tuple.getComponent(0); FlatField ff = (FlatField) field.getSample(0); set = ff.getDomainSet(); /* System.out.println("set = " + set); set = Linear2DSet: Length = 393216 Dimension 1: Length = 768 Range = 0.0 to 767.0 Dimension 2: Length = 512 Range = 0.0 to 511.0 */ if (i == 0) { FunctionType func = (FunctionType) ff.getType(); domain = func.getDomain(); element = (RealType) domain.getComponent(0); line = (RealType) domain.getComponent(1); value = (RealType) func.getRange(); unit = value.getDefaultUnit(); name = value.getName(); } valueTypes[i] = RealType.getRealType(name + (i+1), unit); float[][] temps = ff.getFloats(false); values[i] = temps[0]; // System.out.println("data " + i + " type: " + valueTypes[i]); } npixels = values[0].length; RealTupleType range = new RealTupleType(valueTypes); FunctionType bigFunc = new FunctionType(domain, range); final FlatField bigData = new FlatField(bigFunc, set); bigData.setSamples(values, false); // RealType value = RealType.getRealType("value"); RealType hue = RealType.getRealType("hue"); RealType bigHue = RealType.getRealType("HUE"); RealTupleType newRange = new RealTupleType(value, hue); FunctionType newFunc = new FunctionType(domain, newRange); data = new FlatField(newFunc, set); dataValues = new float[2][npixels]; DataReferenceImpl ref1 = new DataReferenceImpl("ref1"); ref1.setData(data); text = TextType.getTextType("text"); RealType[] time = {RealType.Time}; RealTupleType timeType = new RealTupleType(time); MathType[] mtypes = {element, line, text}; textTuple = new TupleType(mtypes); FunctionType textFunction = new FunctionType(RealType.Time, textTuple); Set timeSet = new Linear1DSet(timeType, 0.0, 1.0, 2); textField = new FieldImpl(textFunction, timeSet); DataReferenceImpl textRef = new DataReferenceImpl("textRef"); textRef.setData(textField); Linear2DSet wedgeSet = new Linear2DSet(domain, 0.0, 767.0, 768, 550.0, 570.0, 21); wedge = new FlatField(newFunc, wedgeSet); wedgeSamples = new float[2][768 * 21]; DataReferenceImpl wedgeRef = new DataReferenceImpl("wedgeRef"); wedgeRef.setData(wedge); final DataReferenceImpl xref = new DataReferenceImpl("xref"); // System.out.println("data type: " + newFunc); display1 = new DisplayImplJ3D("display1", new TwoDDisplayRendererJ3D()); ScalarMap xmap = new ScalarMap(element, Display.XAxis); display1.addMap(xmap); huexmap = new ScalarMap(bigHue, Display.XAxis); display1.addMap(huexmap); ScalarMap ymap = new ScalarMap(line, Display.YAxis); display1.addMap(ymap); ymap.setRange(0.0, 511.0); vmap = new ScalarMap(value, Display.Value); display1.addMap(vmap); hmap = new ScalarMap(hue, Display.Hue); display1.addMap(hmap); ScalarMap textmap = new ScalarMap(text, Display.Text); display1.addMap(textmap); display1.addMap(new ConstantMap(1.0, Display.Saturation)); Control ctrl = textmap.getControl(); if (ctrl != null && ctrl instanceof TextControl) { TextControl textControl = (TextControl) ctrl; textControl.setSize(1.0); textControl.setJustification(TextControl.Justification.CENTER); textControl.setAutoSize(true); } // display1.getGraphicsModeControl().setScaleEnable(true); display1.addReference(ref1); DefaultRendererJ3D renderer = new DefaultRendererJ3D(); display1.addReferences(renderer, xref); renderer.suppressExceptions(true); DefaultRendererJ3D textRenderer = new DefaultRendererJ3D(); display1.addReferences(textRenderer, textRef); textRenderer.suppressExceptions(true); DefaultRendererJ3D wedgeRenderer = new DefaultRendererJ3D(); display1.addReferences(wedgeRenderer, wedgeRef); wedgeRenderer.suppressExceptions(true); lineRef = new DataReferenceImpl("line"); Gridded2DSet dummySet = new Gridded2DSet(domain, null, 1); lineRef.setData(dummySet); display1.addReferences( new RubberBandLineRendererJ3D(element, line), lineRef); final RealType channel = RealType.getRealType("channel"); final RealType point = RealType.getRealType("point"); RealType intensity = RealType.getRealType("intensity"); final FunctionType spectrumType = new FunctionType(channel, intensity); final FunctionType spectraType = new FunctionType(point, spectrumType); final FunctionType lineType = new FunctionType(point, intensity); final FunctionType linesType = new FunctionType(channel, lineType); final DataReferenceImpl ref2 = new DataReferenceImpl("ref2"); DisplayImplJ3D display2 = new DisplayImplJ3D("display2"); ScalarMap xmap2 = new ScalarMap(channel, Display.XAxis); display2.addMap(xmap2); ScalarMap ymap2 = new ScalarMap(intensity, Display.YAxis); display2.addMap(ymap2); ScalarMap zmap2 = new ScalarMap(point, Display.ZAxis); display2.addMap(zmap2); display2.getGraphicsModeControl().setScaleEnable(true); DefaultRendererJ3D renderer2 = new DefaultRendererJ3D(); display2.addReferences(renderer2, ref2); renderer2.suppressExceptions(true); final RealTupleType fdomain = domain; CellImpl cell = new CellImpl() { public void doAction() throws VisADException, RemoteException { Set cellSet = (Set) lineRef.getData(); if (cellSet == null) return; float[][] samples = cellSet.getSamples(); if (samples == null) return; // System.out.println("box (" + samples[0][0] + ", " + samples[1][0] + // ") to (" + samples[0][1] + ", " + samples[1][1] + ")"); float x1 = samples[0][0]; float y1 = samples[1][0]; float x2 = samples[0][1]; float y2 = samples[1][1]; double dist = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); int nsamp = (int) (dist + 1.0); if (nsamp < 2) nsamp = 2; float[][] ss = new float[2][nsamp]; for (int i=0; i<nsamp; i++) { float a = ((float) i) / (nsamp - 1.0f); ss[0][i] = x1 + a * (x2 - x1); ss[1][i] = y1 + a * (y2 - y1); } Gridded2DSet lineSet = new Gridded2DSet(fdomain, ss, nsamp); xref.setData(lineSet); FlatField lineField = (FlatField) // bigData.resample(line, Data.WEIGHTED_AVERAGE, Data.NO_ERRORS); - bigData.resample(line, Data.NEAREST_NEIGHBOR, Data.NO_ERRORS); + bigData.resample(lineSet, Data.NEAREST_NEIGHBOR, Data.NO_ERRORS); float[][] lineSamples = lineField.getFloats(false); // [NFILES][nsamp] Linear1DSet pointSet = new Linear1DSet(point, 0.0, 1.0, nsamp); Integer1DSet channelSet = new Integer1DSet(channel, NFILES); FieldImpl spectra = new FieldImpl(spectraType, pointSet); for (int i=0; i<nsamp; i++) { FlatField spectrum = new FlatField(spectrumType, channelSet); float[][] temp = new float[1][NFILES]; for (int j=0; j<NFILES; j++) { temp[0][j] = lineSamples[j][i]; } spectrum.setSamples(temp, false); spectra.setSample(i, spectrum); } FieldImpl lines = new FieldImpl(linesType, channelSet); for (int j=0; j<NFILES; j++) { FlatField linex = new FlatField(lineType, pointSet); float[][] temp = new float[1][nsamp]; for (int i=0; i<nsamp; i++) { temp[0][i] = lineSamples[j][i]; } linex.setSamples(temp, false); lines.setSample(j, linex); } ref2.setData(new Tuple(new Data[] {spectra, lines})); } }; cell.addReference(lineRef); VisADSlider[] valueSliders = new VisADSlider[NFILES]; VisADSlider[] hueSliders = new VisADSlider[NFILES]; valueRefs = new DataReferenceImpl[NFILES]; hueRefs = new DataReferenceImpl[NFILES]; JFrame frame = new JFrame("VisAD MultiLUT"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // create JPanel in frame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setAlignmentY(JPanel.TOP_ALIGNMENT); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); frame.setContentPane(panel); JPanel left = new JPanel(); left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS)); left.setAlignmentY(JPanel.TOP_ALIGNMENT); left.setAlignmentX(JPanel.LEFT_ALIGNMENT); JPanel center = new JPanel(); center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS)); center.setAlignmentY(JPanel.TOP_ALIGNMENT); center.setAlignmentX(JPanel.LEFT_ALIGNMENT); JPanel right = new JPanel(); right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS)); right.setAlignmentY(JPanel.TOP_ALIGNMENT); right.setAlignmentX(JPanel.LEFT_ALIGNMENT); panel.add(left); panel.add(center); panel.add(right); Dimension d = new Dimension(300, 1000); left.setMaximumSize(d); center.setMaximumSize(d); for (int i=0; i<NFILES; i++) { valueRefs[i] = new DataReferenceImpl("value" + i); valueRefs[i].setData(new Real(1.0)); valueSliders[i] = new VisADSlider("value" + i, -100, 100, 100, 0.01, valueRefs[i], RealType.Generic); left.add(valueSliders[i]); hueRefs[i] = new DataReferenceImpl("hue" + i); hueRefs[i].setData(new Real(1.0)); hueSliders[i] = new VisADSlider("hue" + i, -100, 100, 100, 0.01, hueRefs[i], RealType.Generic); center.add(hueSliders[i]); } // slider button for setting all value sliders to 0 JButton valueClear = new JButton("Zero values"); valueClear.addActionListener(this); valueClear.setActionCommand("valueClear"); left.add(Box.createVerticalStrut(10)); left.add(valueClear); // slider button for setting all value sliders to 1 JButton valueSet = new JButton("One values"); valueSet.addActionListener(this); valueSet.setActionCommand("valueSet"); left.add(valueSet); // slider button for setting all hue sliders to 0 JButton hueClear = new JButton("Zero hues"); hueClear.addActionListener(this); hueClear.setActionCommand("hueClear"); center.add(Box.createVerticalStrut(10)); center.add(hueClear); // slider button for setting all hue sliders to 1 JButton hueSet = new JButton("One hues"); hueSet.addActionListener(this); hueSet.setActionCommand("hueSet"); center.add(hueSet); // slider button for setting all hue sliders to 0 right.add(display1.getComponent()); right.add(display2.getComponent()); // vmin and vmax labels minmax = new JLabel(" "); left.add(Box.createVerticalStrut(30)); left.add(minmax); // "GO" button for applying computation in sliders JButton compute = new JButton("Compute"); compute.addActionListener(this); compute.setActionCommand("compute"); left.add(Box.createVerticalStrut(10)); left.add(compute); int width = 1200; int height = 1000; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(screenSize.width/2 - width/2, screenSize.height/2 - height/2); frame.setSize(width, height); frame.setVisible(true); doit(); } /** Handles button press events. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("compute")) doit(); else if (cmd.equals("valueClear")) { try { for (int i=0; i<NFILES; i++) { valueRefs[i].setData(new Real(0.0)); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (cmd.equals("valueSet")) { try { for (int i=0; i<NFILES; i++) { valueRefs[i].setData(new Real(1.0)); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (cmd.equals("hueClear")) { try { for (int i=0; i<NFILES; i++) { hueRefs[i].setData(new Real(0.0)); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else if (cmd.equals("hueSet")) { try { for (int i=0; i<NFILES; i++) { hueRefs[i].setData(new Real(1.0)); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } } public void doit() { try { float[] valueWeights = new float[NFILES]; float[] hueWeights = new float[NFILES]; for (int i=0; i<NFILES; i++) { Real r = (Real) valueRefs[i].getData(); valueWeights[i] = (float) r.getValue(); r = (Real) hueRefs[i].getData(); hueWeights[i] = (float) r.getValue(); } float vmin = Float.MAX_VALUE; float vmax = Float.MIN_VALUE; float hmin = Float.MAX_VALUE; float hmax = Float.MIN_VALUE; for (int j=0; j<npixels; j++) { float v = 0, h = 0; for (int i=0; i<NFILES; i++) { v += valueWeights[i] * values[i][j]; h += hueWeights[i] * values[i][j]; } dataValues[0][j] = v; dataValues[1][j] = h; if (v < vmin) vmin = v; if (v > vmax) vmax = v; if (h < hmin) hmin = h; if (h > hmax) hmax = h; } for (int i=0; i<768; i++) { float hue = hmin + (((float) i) / 767.0f) * (hmax - hmin); for (int k=i; k<768*21; k+=768) { wedgeSamples[0][k] = vmax; wedgeSamples[1][k] = hue; } } minmax.setText("vmin = " + vmin + "; vmax = " + vmax); double x1 = 0.0, x2 = 767.0, y = 525.0; textField.setSample(0, new Tuple(textTuple, new Scalar[] { new Real(element, x1), new Real(line, y), new Text(text, "" + hmin) })); textField.setSample(1, new Tuple(textTuple, new Scalar[] { new Real(element, x2), new Real(line, y), new Text(text, "" + hmax) })); display1.disableAction(); vmap.setRange(vmin, vmax); hmap.setRange(hmin, hmax); huexmap.setRange(hmin, hmax); data.setSamples(dataValues, false); wedge.setSamples(wedgeSamples, false); display1.enableAction(); } catch (VisADException ex) { ex.printStackTrace(); } catch (RemoteException ex) { ex.printStackTrace(); } } }
true
true
public void go(String[] args) throws IOException, VisADException { String dir = ""; String slash = System.getProperty("file.separator"); if (args.length > 0) { dir = args[0]; if (!dir.endsWith(slash)) dir = dir + slash; } RealTupleType domain = null; Unit unit = null; String name = null; Set set = null; RealType[] valueTypes = new RealType[NFILES]; values = new float[NFILES][]; DefaultFamily loader = new DefaultFamily("loader"); for (int i=0; i<NFILES; i++) { Tuple tuple = (Tuple) loader.open(dir + "SPB" + (i+1) + ".PIC"); FieldImpl field = (FieldImpl) tuple.getComponent(0); FlatField ff = (FlatField) field.getSample(0); set = ff.getDomainSet(); /* System.out.println("set = " + set); set = Linear2DSet: Length = 393216 Dimension 1: Length = 768 Range = 0.0 to 767.0 Dimension 2: Length = 512 Range = 0.0 to 511.0 */ if (i == 0) { FunctionType func = (FunctionType) ff.getType(); domain = func.getDomain(); element = (RealType) domain.getComponent(0); line = (RealType) domain.getComponent(1); value = (RealType) func.getRange(); unit = value.getDefaultUnit(); name = value.getName(); } valueTypes[i] = RealType.getRealType(name + (i+1), unit); float[][] temps = ff.getFloats(false); values[i] = temps[0]; // System.out.println("data " + i + " type: " + valueTypes[i]); } npixels = values[0].length; RealTupleType range = new RealTupleType(valueTypes); FunctionType bigFunc = new FunctionType(domain, range); final FlatField bigData = new FlatField(bigFunc, set); bigData.setSamples(values, false); // RealType value = RealType.getRealType("value"); RealType hue = RealType.getRealType("hue"); RealType bigHue = RealType.getRealType("HUE"); RealTupleType newRange = new RealTupleType(value, hue); FunctionType newFunc = new FunctionType(domain, newRange); data = new FlatField(newFunc, set); dataValues = new float[2][npixels]; DataReferenceImpl ref1 = new DataReferenceImpl("ref1"); ref1.setData(data); text = TextType.getTextType("text"); RealType[] time = {RealType.Time}; RealTupleType timeType = new RealTupleType(time); MathType[] mtypes = {element, line, text}; textTuple = new TupleType(mtypes); FunctionType textFunction = new FunctionType(RealType.Time, textTuple); Set timeSet = new Linear1DSet(timeType, 0.0, 1.0, 2); textField = new FieldImpl(textFunction, timeSet); DataReferenceImpl textRef = new DataReferenceImpl("textRef"); textRef.setData(textField); Linear2DSet wedgeSet = new Linear2DSet(domain, 0.0, 767.0, 768, 550.0, 570.0, 21); wedge = new FlatField(newFunc, wedgeSet); wedgeSamples = new float[2][768 * 21]; DataReferenceImpl wedgeRef = new DataReferenceImpl("wedgeRef"); wedgeRef.setData(wedge); final DataReferenceImpl xref = new DataReferenceImpl("xref"); // System.out.println("data type: " + newFunc); display1 = new DisplayImplJ3D("display1", new TwoDDisplayRendererJ3D()); ScalarMap xmap = new ScalarMap(element, Display.XAxis); display1.addMap(xmap); huexmap = new ScalarMap(bigHue, Display.XAxis); display1.addMap(huexmap); ScalarMap ymap = new ScalarMap(line, Display.YAxis); display1.addMap(ymap); ymap.setRange(0.0, 511.0); vmap = new ScalarMap(value, Display.Value); display1.addMap(vmap); hmap = new ScalarMap(hue, Display.Hue); display1.addMap(hmap); ScalarMap textmap = new ScalarMap(text, Display.Text); display1.addMap(textmap); display1.addMap(new ConstantMap(1.0, Display.Saturation)); Control ctrl = textmap.getControl(); if (ctrl != null && ctrl instanceof TextControl) { TextControl textControl = (TextControl) ctrl; textControl.setSize(1.0); textControl.setJustification(TextControl.Justification.CENTER); textControl.setAutoSize(true); } // display1.getGraphicsModeControl().setScaleEnable(true); display1.addReference(ref1); DefaultRendererJ3D renderer = new DefaultRendererJ3D(); display1.addReferences(renderer, xref); renderer.suppressExceptions(true); DefaultRendererJ3D textRenderer = new DefaultRendererJ3D(); display1.addReferences(textRenderer, textRef); textRenderer.suppressExceptions(true); DefaultRendererJ3D wedgeRenderer = new DefaultRendererJ3D(); display1.addReferences(wedgeRenderer, wedgeRef); wedgeRenderer.suppressExceptions(true); lineRef = new DataReferenceImpl("line"); Gridded2DSet dummySet = new Gridded2DSet(domain, null, 1); lineRef.setData(dummySet); display1.addReferences( new RubberBandLineRendererJ3D(element, line), lineRef); final RealType channel = RealType.getRealType("channel"); final RealType point = RealType.getRealType("point"); RealType intensity = RealType.getRealType("intensity"); final FunctionType spectrumType = new FunctionType(channel, intensity); final FunctionType spectraType = new FunctionType(point, spectrumType); final FunctionType lineType = new FunctionType(point, intensity); final FunctionType linesType = new FunctionType(channel, lineType); final DataReferenceImpl ref2 = new DataReferenceImpl("ref2"); DisplayImplJ3D display2 = new DisplayImplJ3D("display2"); ScalarMap xmap2 = new ScalarMap(channel, Display.XAxis); display2.addMap(xmap2); ScalarMap ymap2 = new ScalarMap(intensity, Display.YAxis); display2.addMap(ymap2); ScalarMap zmap2 = new ScalarMap(point, Display.ZAxis); display2.addMap(zmap2); display2.getGraphicsModeControl().setScaleEnable(true); DefaultRendererJ3D renderer2 = new DefaultRendererJ3D(); display2.addReferences(renderer2, ref2); renderer2.suppressExceptions(true); final RealTupleType fdomain = domain; CellImpl cell = new CellImpl() { public void doAction() throws VisADException, RemoteException { Set cellSet = (Set) lineRef.getData(); if (cellSet == null) return; float[][] samples = cellSet.getSamples(); if (samples == null) return; // System.out.println("box (" + samples[0][0] + ", " + samples[1][0] + // ") to (" + samples[0][1] + ", " + samples[1][1] + ")"); float x1 = samples[0][0]; float y1 = samples[1][0]; float x2 = samples[0][1]; float y2 = samples[1][1]; double dist = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); int nsamp = (int) (dist + 1.0); if (nsamp < 2) nsamp = 2; float[][] ss = new float[2][nsamp]; for (int i=0; i<nsamp; i++) { float a = ((float) i) / (nsamp - 1.0f); ss[0][i] = x1 + a * (x2 - x1); ss[1][i] = y1 + a * (y2 - y1); } Gridded2DSet lineSet = new Gridded2DSet(fdomain, ss, nsamp); xref.setData(lineSet); FlatField lineField = (FlatField) // bigData.resample(line, Data.WEIGHTED_AVERAGE, Data.NO_ERRORS); bigData.resample(line, Data.NEAREST_NEIGHBOR, Data.NO_ERRORS); float[][] lineSamples = lineField.getFloats(false); // [NFILES][nsamp] Linear1DSet pointSet = new Linear1DSet(point, 0.0, 1.0, nsamp); Integer1DSet channelSet = new Integer1DSet(channel, NFILES); FieldImpl spectra = new FieldImpl(spectraType, pointSet); for (int i=0; i<nsamp; i++) { FlatField spectrum = new FlatField(spectrumType, channelSet); float[][] temp = new float[1][NFILES]; for (int j=0; j<NFILES; j++) { temp[0][j] = lineSamples[j][i]; } spectrum.setSamples(temp, false); spectra.setSample(i, spectrum); } FieldImpl lines = new FieldImpl(linesType, channelSet); for (int j=0; j<NFILES; j++) { FlatField linex = new FlatField(lineType, pointSet); float[][] temp = new float[1][nsamp]; for (int i=0; i<nsamp; i++) { temp[0][i] = lineSamples[j][i]; } linex.setSamples(temp, false); lines.setSample(j, linex); } ref2.setData(new Tuple(new Data[] {spectra, lines})); } }; cell.addReference(lineRef); VisADSlider[] valueSliders = new VisADSlider[NFILES]; VisADSlider[] hueSliders = new VisADSlider[NFILES]; valueRefs = new DataReferenceImpl[NFILES]; hueRefs = new DataReferenceImpl[NFILES]; JFrame frame = new JFrame("VisAD MultiLUT"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // create JPanel in frame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setAlignmentY(JPanel.TOP_ALIGNMENT); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); frame.setContentPane(panel); JPanel left = new JPanel(); left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS)); left.setAlignmentY(JPanel.TOP_ALIGNMENT); left.setAlignmentX(JPanel.LEFT_ALIGNMENT); JPanel center = new JPanel(); center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS)); center.setAlignmentY(JPanel.TOP_ALIGNMENT); center.setAlignmentX(JPanel.LEFT_ALIGNMENT); JPanel right = new JPanel(); right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS)); right.setAlignmentY(JPanel.TOP_ALIGNMENT); right.setAlignmentX(JPanel.LEFT_ALIGNMENT); panel.add(left); panel.add(center); panel.add(right); Dimension d = new Dimension(300, 1000); left.setMaximumSize(d); center.setMaximumSize(d); for (int i=0; i<NFILES; i++) { valueRefs[i] = new DataReferenceImpl("value" + i); valueRefs[i].setData(new Real(1.0)); valueSliders[i] = new VisADSlider("value" + i, -100, 100, 100, 0.01, valueRefs[i], RealType.Generic); left.add(valueSliders[i]); hueRefs[i] = new DataReferenceImpl("hue" + i); hueRefs[i].setData(new Real(1.0)); hueSliders[i] = new VisADSlider("hue" + i, -100, 100, 100, 0.01, hueRefs[i], RealType.Generic); center.add(hueSliders[i]); } // slider button for setting all value sliders to 0 JButton valueClear = new JButton("Zero values"); valueClear.addActionListener(this); valueClear.setActionCommand("valueClear"); left.add(Box.createVerticalStrut(10)); left.add(valueClear); // slider button for setting all value sliders to 1 JButton valueSet = new JButton("One values"); valueSet.addActionListener(this); valueSet.setActionCommand("valueSet"); left.add(valueSet); // slider button for setting all hue sliders to 0 JButton hueClear = new JButton("Zero hues"); hueClear.addActionListener(this); hueClear.setActionCommand("hueClear"); center.add(Box.createVerticalStrut(10)); center.add(hueClear); // slider button for setting all hue sliders to 1 JButton hueSet = new JButton("One hues"); hueSet.addActionListener(this); hueSet.setActionCommand("hueSet"); center.add(hueSet); // slider button for setting all hue sliders to 0 right.add(display1.getComponent()); right.add(display2.getComponent()); // vmin and vmax labels minmax = new JLabel(" "); left.add(Box.createVerticalStrut(30)); left.add(minmax); // "GO" button for applying computation in sliders JButton compute = new JButton("Compute"); compute.addActionListener(this); compute.setActionCommand("compute"); left.add(Box.createVerticalStrut(10)); left.add(compute); int width = 1200; int height = 1000; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(screenSize.width/2 - width/2, screenSize.height/2 - height/2); frame.setSize(width, height); frame.setVisible(true); doit(); }
public void go(String[] args) throws IOException, VisADException { String dir = ""; String slash = System.getProperty("file.separator"); if (args.length > 0) { dir = args[0]; if (!dir.endsWith(slash)) dir = dir + slash; } RealTupleType domain = null; Unit unit = null; String name = null; Set set = null; RealType[] valueTypes = new RealType[NFILES]; values = new float[NFILES][]; DefaultFamily loader = new DefaultFamily("loader"); for (int i=0; i<NFILES; i++) { Tuple tuple = (Tuple) loader.open(dir + "SPB" + (i+1) + ".PIC"); FieldImpl field = (FieldImpl) tuple.getComponent(0); FlatField ff = (FlatField) field.getSample(0); set = ff.getDomainSet(); /* System.out.println("set = " + set); set = Linear2DSet: Length = 393216 Dimension 1: Length = 768 Range = 0.0 to 767.0 Dimension 2: Length = 512 Range = 0.0 to 511.0 */ if (i == 0) { FunctionType func = (FunctionType) ff.getType(); domain = func.getDomain(); element = (RealType) domain.getComponent(0); line = (RealType) domain.getComponent(1); value = (RealType) func.getRange(); unit = value.getDefaultUnit(); name = value.getName(); } valueTypes[i] = RealType.getRealType(name + (i+1), unit); float[][] temps = ff.getFloats(false); values[i] = temps[0]; // System.out.println("data " + i + " type: " + valueTypes[i]); } npixels = values[0].length; RealTupleType range = new RealTupleType(valueTypes); FunctionType bigFunc = new FunctionType(domain, range); final FlatField bigData = new FlatField(bigFunc, set); bigData.setSamples(values, false); // RealType value = RealType.getRealType("value"); RealType hue = RealType.getRealType("hue"); RealType bigHue = RealType.getRealType("HUE"); RealTupleType newRange = new RealTupleType(value, hue); FunctionType newFunc = new FunctionType(domain, newRange); data = new FlatField(newFunc, set); dataValues = new float[2][npixels]; DataReferenceImpl ref1 = new DataReferenceImpl("ref1"); ref1.setData(data); text = TextType.getTextType("text"); RealType[] time = {RealType.Time}; RealTupleType timeType = new RealTupleType(time); MathType[] mtypes = {element, line, text}; textTuple = new TupleType(mtypes); FunctionType textFunction = new FunctionType(RealType.Time, textTuple); Set timeSet = new Linear1DSet(timeType, 0.0, 1.0, 2); textField = new FieldImpl(textFunction, timeSet); DataReferenceImpl textRef = new DataReferenceImpl("textRef"); textRef.setData(textField); Linear2DSet wedgeSet = new Linear2DSet(domain, 0.0, 767.0, 768, 550.0, 570.0, 21); wedge = new FlatField(newFunc, wedgeSet); wedgeSamples = new float[2][768 * 21]; DataReferenceImpl wedgeRef = new DataReferenceImpl("wedgeRef"); wedgeRef.setData(wedge); final DataReferenceImpl xref = new DataReferenceImpl("xref"); // System.out.println("data type: " + newFunc); display1 = new DisplayImplJ3D("display1", new TwoDDisplayRendererJ3D()); ScalarMap xmap = new ScalarMap(element, Display.XAxis); display1.addMap(xmap); huexmap = new ScalarMap(bigHue, Display.XAxis); display1.addMap(huexmap); ScalarMap ymap = new ScalarMap(line, Display.YAxis); display1.addMap(ymap); ymap.setRange(0.0, 511.0); vmap = new ScalarMap(value, Display.Value); display1.addMap(vmap); hmap = new ScalarMap(hue, Display.Hue); display1.addMap(hmap); ScalarMap textmap = new ScalarMap(text, Display.Text); display1.addMap(textmap); display1.addMap(new ConstantMap(1.0, Display.Saturation)); Control ctrl = textmap.getControl(); if (ctrl != null && ctrl instanceof TextControl) { TextControl textControl = (TextControl) ctrl; textControl.setSize(1.0); textControl.setJustification(TextControl.Justification.CENTER); textControl.setAutoSize(true); } // display1.getGraphicsModeControl().setScaleEnable(true); display1.addReference(ref1); DefaultRendererJ3D renderer = new DefaultRendererJ3D(); display1.addReferences(renderer, xref); renderer.suppressExceptions(true); DefaultRendererJ3D textRenderer = new DefaultRendererJ3D(); display1.addReferences(textRenderer, textRef); textRenderer.suppressExceptions(true); DefaultRendererJ3D wedgeRenderer = new DefaultRendererJ3D(); display1.addReferences(wedgeRenderer, wedgeRef); wedgeRenderer.suppressExceptions(true); lineRef = new DataReferenceImpl("line"); Gridded2DSet dummySet = new Gridded2DSet(domain, null, 1); lineRef.setData(dummySet); display1.addReferences( new RubberBandLineRendererJ3D(element, line), lineRef); final RealType channel = RealType.getRealType("channel"); final RealType point = RealType.getRealType("point"); RealType intensity = RealType.getRealType("intensity"); final FunctionType spectrumType = new FunctionType(channel, intensity); final FunctionType spectraType = new FunctionType(point, spectrumType); final FunctionType lineType = new FunctionType(point, intensity); final FunctionType linesType = new FunctionType(channel, lineType); final DataReferenceImpl ref2 = new DataReferenceImpl("ref2"); DisplayImplJ3D display2 = new DisplayImplJ3D("display2"); ScalarMap xmap2 = new ScalarMap(channel, Display.XAxis); display2.addMap(xmap2); ScalarMap ymap2 = new ScalarMap(intensity, Display.YAxis); display2.addMap(ymap2); ScalarMap zmap2 = new ScalarMap(point, Display.ZAxis); display2.addMap(zmap2); display2.getGraphicsModeControl().setScaleEnable(true); DefaultRendererJ3D renderer2 = new DefaultRendererJ3D(); display2.addReferences(renderer2, ref2); renderer2.suppressExceptions(true); final RealTupleType fdomain = domain; CellImpl cell = new CellImpl() { public void doAction() throws VisADException, RemoteException { Set cellSet = (Set) lineRef.getData(); if (cellSet == null) return; float[][] samples = cellSet.getSamples(); if (samples == null) return; // System.out.println("box (" + samples[0][0] + ", " + samples[1][0] + // ") to (" + samples[0][1] + ", " + samples[1][1] + ")"); float x1 = samples[0][0]; float y1 = samples[1][0]; float x2 = samples[0][1]; float y2 = samples[1][1]; double dist = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); int nsamp = (int) (dist + 1.0); if (nsamp < 2) nsamp = 2; float[][] ss = new float[2][nsamp]; for (int i=0; i<nsamp; i++) { float a = ((float) i) / (nsamp - 1.0f); ss[0][i] = x1 + a * (x2 - x1); ss[1][i] = y1 + a * (y2 - y1); } Gridded2DSet lineSet = new Gridded2DSet(fdomain, ss, nsamp); xref.setData(lineSet); FlatField lineField = (FlatField) // bigData.resample(line, Data.WEIGHTED_AVERAGE, Data.NO_ERRORS); bigData.resample(lineSet, Data.NEAREST_NEIGHBOR, Data.NO_ERRORS); float[][] lineSamples = lineField.getFloats(false); // [NFILES][nsamp] Linear1DSet pointSet = new Linear1DSet(point, 0.0, 1.0, nsamp); Integer1DSet channelSet = new Integer1DSet(channel, NFILES); FieldImpl spectra = new FieldImpl(spectraType, pointSet); for (int i=0; i<nsamp; i++) { FlatField spectrum = new FlatField(spectrumType, channelSet); float[][] temp = new float[1][NFILES]; for (int j=0; j<NFILES; j++) { temp[0][j] = lineSamples[j][i]; } spectrum.setSamples(temp, false); spectra.setSample(i, spectrum); } FieldImpl lines = new FieldImpl(linesType, channelSet); for (int j=0; j<NFILES; j++) { FlatField linex = new FlatField(lineType, pointSet); float[][] temp = new float[1][nsamp]; for (int i=0; i<nsamp; i++) { temp[0][i] = lineSamples[j][i]; } linex.setSamples(temp, false); lines.setSample(j, linex); } ref2.setData(new Tuple(new Data[] {spectra, lines})); } }; cell.addReference(lineRef); VisADSlider[] valueSliders = new VisADSlider[NFILES]; VisADSlider[] hueSliders = new VisADSlider[NFILES]; valueRefs = new DataReferenceImpl[NFILES]; hueRefs = new DataReferenceImpl[NFILES]; JFrame frame = new JFrame("VisAD MultiLUT"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // create JPanel in frame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setAlignmentY(JPanel.TOP_ALIGNMENT); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); frame.setContentPane(panel); JPanel left = new JPanel(); left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS)); left.setAlignmentY(JPanel.TOP_ALIGNMENT); left.setAlignmentX(JPanel.LEFT_ALIGNMENT); JPanel center = new JPanel(); center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS)); center.setAlignmentY(JPanel.TOP_ALIGNMENT); center.setAlignmentX(JPanel.LEFT_ALIGNMENT); JPanel right = new JPanel(); right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS)); right.setAlignmentY(JPanel.TOP_ALIGNMENT); right.setAlignmentX(JPanel.LEFT_ALIGNMENT); panel.add(left); panel.add(center); panel.add(right); Dimension d = new Dimension(300, 1000); left.setMaximumSize(d); center.setMaximumSize(d); for (int i=0; i<NFILES; i++) { valueRefs[i] = new DataReferenceImpl("value" + i); valueRefs[i].setData(new Real(1.0)); valueSliders[i] = new VisADSlider("value" + i, -100, 100, 100, 0.01, valueRefs[i], RealType.Generic); left.add(valueSliders[i]); hueRefs[i] = new DataReferenceImpl("hue" + i); hueRefs[i].setData(new Real(1.0)); hueSliders[i] = new VisADSlider("hue" + i, -100, 100, 100, 0.01, hueRefs[i], RealType.Generic); center.add(hueSliders[i]); } // slider button for setting all value sliders to 0 JButton valueClear = new JButton("Zero values"); valueClear.addActionListener(this); valueClear.setActionCommand("valueClear"); left.add(Box.createVerticalStrut(10)); left.add(valueClear); // slider button for setting all value sliders to 1 JButton valueSet = new JButton("One values"); valueSet.addActionListener(this); valueSet.setActionCommand("valueSet"); left.add(valueSet); // slider button for setting all hue sliders to 0 JButton hueClear = new JButton("Zero hues"); hueClear.addActionListener(this); hueClear.setActionCommand("hueClear"); center.add(Box.createVerticalStrut(10)); center.add(hueClear); // slider button for setting all hue sliders to 1 JButton hueSet = new JButton("One hues"); hueSet.addActionListener(this); hueSet.setActionCommand("hueSet"); center.add(hueSet); // slider button for setting all hue sliders to 0 right.add(display1.getComponent()); right.add(display2.getComponent()); // vmin and vmax labels minmax = new JLabel(" "); left.add(Box.createVerticalStrut(30)); left.add(minmax); // "GO" button for applying computation in sliders JButton compute = new JButton("Compute"); compute.addActionListener(this); compute.setActionCommand("compute"); left.add(Box.createVerticalStrut(10)); left.add(compute); int width = 1200; int height = 1000; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(screenSize.width/2 - width/2, screenSize.height/2 - height/2); frame.setSize(width, height); frame.setVisible(true); doit(); }
diff --git a/src/main/java/org/mctourney/AutoReferee/AutoReferee.java b/src/main/java/org/mctourney/AutoReferee/AutoReferee.java index 9eba6f4..e729655 100644 --- a/src/main/java/org/mctourney/AutoReferee/AutoReferee.java +++ b/src/main/java/org/mctourney/AutoReferee/AutoReferee.java @@ -1,1037 +1,1037 @@ package org.mctourney.AutoReferee; import java.io.File; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.text.StrMatcher; import org.apache.commons.lang.text.StrTokenizer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.conversations.BooleanPrompt; import org.bukkit.conversations.Conversation; import org.bukkit.conversations.ConversationContext; import org.bukkit.conversations.Prompt; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.messaging.Messenger; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.selections.CuboidSelection; import com.sk89q.worldedit.bukkit.selections.Selection; import org.mctourney.AutoReferee.AutoRefMatch.MatchStatus; import org.mctourney.AutoReferee.listeners.ObjectiveTracker; import org.mctourney.AutoReferee.listeners.PlayerVersusPlayerListener; import org.mctourney.AutoReferee.listeners.RefereeChannelListener; import org.mctourney.AutoReferee.listeners.TeamListener; import org.mctourney.AutoReferee.listeners.WorldListener; import org.mctourney.AutoReferee.listeners.ZoneListener; import org.mctourney.AutoReferee.util.BlockData; import org.mctourney.AutoReferee.util.BlockVector3; import org.mctourney.AutoReferee.util.CuboidRegion; import org.mctourney.AutoReferee.util.Vector3; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class AutoReferee extends JavaPlugin { // singleton instance private static AutoReferee instance = null; public static AutoReferee getInstance() { return instance; } // expected configuration version number private static final int PLUGIN_CFG_VERSION = 2; // plugin channel encoding public static final String PLUGIN_CHANNEL_ENC = "UTF-8"; // plugin channel prefix - identifies all channels as belonging to AutoReferee private static final String PLUGIN_CHANNEL_PREFIX = "autoref:"; // plugin channels (referee) public static final String REFEREE_PLUGIN_CHANNEL = PLUGIN_CHANNEL_PREFIX + "referee"; private RefereeChannelListener refChannelListener = null; // name of the stored map configuration file public static final String CFG_FILENAME = "autoreferee.yml"; // prefix for temporary worlds public static final String WORLD_PREFIX = "world-autoref-"; // messages public static final String NO_LOGIN_MESSAGE = "You are not scheduled for a match on this server."; public static final String COMPLETED_KICK_MESSAGE = "Thank you for playing!"; public static final String NO_WEBSTATS_MESSAGE = "An error has occured; no webstats will be generated."; // query server object public QueryServer qserv = null; private World lobby = null; public World getLobbyWorld() { return lobby; } public void setLobbyWorld(World w) { this.lobby = w; } // is this plugin in online mode? private boolean autoMode = true; public boolean isAutoMode() { return autoMode; } public boolean setAutoMode(boolean m) { return this.autoMode = m; } // get the match associated with the world private Map<UUID, AutoRefMatch> matches = Maps.newHashMap(); public AutoRefMatch getMatch(World w) { return w != null ? matches.get(w.getUID()) : null; } public Collection<AutoRefMatch> getMatches() { return matches.values(); } public void addMatch(AutoRefMatch match) { matches.put(match.getWorld().getUID(), match); } public void clearMatch(AutoRefMatch match) { matches.remove(match.getWorld().getUID()); } public AutoRefTeam getTeam(Player pl) { // go through all the matches for (AutoRefMatch match : matches.values()) { // if the player is on a team for this match... AutoRefTeam team = match.getPlayerTeam(pl); if (team != null) return team; } // this player is on no known teams return null; } public AutoRefTeam getExpectedTeam(Player pl) { AutoRefTeam actualTeam = getTeam(pl); if (actualTeam != null) return actualTeam; // go through all the matches for (AutoRefMatch match : matches.values()) { // if the player is expected for any of these teams for (AutoRefTeam team : match.getTeams()) if (team.getExpectedPlayers().contains(pl)) return team; } // this player is expected on no known teams return null; } private boolean checkPlugins(PluginManager pm) { boolean foundOtherPlugin = false; for ( Plugin p : pm.getPlugins() ) if (p != this) { if (!foundOtherPlugin) getLogger().severe("No other plugins may be loaded in online mode..."); getLogger().severe("Agressively disabling plugin: " + p.getName()); pm.disablePlugin(p); String pStatus = p.isEnabled() ? "NOT disabled" : "disabled"; getLogger().severe(p.getName() + " is " + pStatus + "."); foundOtherPlugin = true; } // return true if all other plugins are disabled for ( Plugin p : pm.getPlugins() ) if (p != this && p.isEnabled()) return false; return true; } public void onEnable() { // store the singleton instance instance = this; PluginManager pm = getServer().getPluginManager(); // events related to team management, chat, whitelists, respawn pm.registerEvents(new TeamListener(this), this); // events related to PvP, damage, death, mobs pm.registerEvents(new PlayerVersusPlayerListener(this), this); // events related to safe zones, creating zones, map conditions pm.registerEvents(new ZoneListener(this), this); // events related to worlds pm.registerEvents(new WorldListener(this), this); // events related to tracking objectives during a match pm.registerEvents(new ObjectiveTracker(this), this); // events related to referee channel pm.registerEvents(refChannelListener = new RefereeChannelListener(this), this); // global configuration object (can't be changed, so don't save onDisable) InputStream configInputStream = getResource("defaults/config.yml"); if (configInputStream != null) getConfig().setDefaults( YamlConfiguration.loadConfiguration(configInputStream)); getConfig().options().copyDefaults(true); saveConfig(); // ensure we are dealing with the right type of config file int configVersion = getConfig().getInt("config-version", -1); if (configVersion != PLUGIN_CFG_VERSION && configVersion != -1) getLogger().severe(String.format("!!! Incorrect config-version (expected %d, got %d)", PLUGIN_CFG_VERSION, configVersion)); // get server list, and attempt to determine whether we are in online mode String qurl = getConfig().getString("server-mode.query-server", null); setAutoMode(getServer().getOnlineMode() && qurl != null && this.getConfig().getBoolean("server-mode.online", true)); // setup a possible alternate map repository String mrepo = this.getConfig().getString("server-mode.map-repo", null); if (mrepo != null) AutoRefMatch.changeMapRepo(mrepo); // attempt to setup the plugin channels setupPluginChannels(); // wrap up, debug to follow this message getLogger().info(this.getName() + " loaded successfully" + (hasSportBukkitApi() ? " with SportBukkit API" : "") + "."); // save the "lobby" world as a sort of drop-zone for discharged players String lobbyname = getConfig().getString("lobby-world", null); World lobbyworld = lobbyname == null ? null : getServer().getWorld(lobbyname); setLobbyWorld(lobbyworld == null ? getServer().getWorlds().get(0) : lobbyworld); // connect to server, or let the server operator know to set up the match manually if (!makeServerConnection(qurl)) getLogger().info(this.getName() + " is running in OFFLINE mode. All setup must be done manually."); // update online mode to represent whether or not we have a connection if (isAutoMode()) setAutoMode(checkPlugins(pm)); // setup the map library folder AutoRefMap.getMapLibrary(); // process initial world(s), just in case for ( World w : getServer().getWorlds() ) AutoRefMatch.setupWorld(w, false); // update maps automatically if auto-update is enabled if (getConfig().getBoolean("auto-update", true)) AutoRefMap.getUpdates(Bukkit.getConsoleSender(), false); } public boolean makeServerConnection(String qurl) { // if we are not in online mode, stop right here if (!isAutoMode()) return false; // get default key and server key String defkey = getConfig().getDefaults().getString("server-mode.key"); String key = getConfig().getString("server-mode.key", null); // if there is no server key listed, or it is set to the default key if (key == null || key.equals(defkey)) { // reference the keyserver to remind operator to get a server key getLogger().severe("Please get a server key from " + getConfig().getString("server-mode.keyserver")); return setAutoMode(false); } // setup query server and return response from ACK qserv = new QueryServer(qurl, key); return setAutoMode(qserv.ack()); } public void onDisable() { getLogger().info(this.getName() + " disabled."); } private void setupPluginChannels() { Messenger m = getServer().getMessenger(); // setup referee plugin channels m.registerOutgoingPluginChannel(this, REFEREE_PLUGIN_CHANNEL); m.registerIncomingPluginChannel(this, REFEREE_PLUGIN_CHANNEL, refChannelListener); } public void playerDone(Player p) { // take them back to the lobby, one way or another if (p.getWorld() != getLobbyWorld()) { p.setGameMode(WorldListener.getDefaultGamemode(getLobbyWorld())); p.teleport(getLobbyWorld().getSpawnLocation()); } // if the server is in online mode, remove them as well if (isAutoMode()) p.kickPlayer(AutoReferee.COMPLETED_KICK_MESSAGE); } private WorldEditPlugin getWorldEdit() { Plugin plugin = getServer().getPluginManager().getPlugin("WorldEdit"); // WorldEdit may not be loaded if (plugin == null || !(plugin instanceof WorldEditPlugin)) return null; return (WorldEditPlugin) plugin; } public boolean playerWhitelisted(Player player) { if (player.hasPermission("autoreferee.admin")) return true; if (player.hasPermission("autoreferee.referee")) return true; return getExpectedTeam(player) != null; } private World consoleWorld = null; public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { World world = null; Player player = null; if (sender instanceof Player) { player = (Player) sender; world = player.getWorld(); } else world = consoleWorld; AutoRefMatch match = getMatch(world); // reparse the args properly using the string tokenizer from org.apache.commons args = new StrTokenizer(StringUtils.join(args, ' '), StrMatcher.splitMatcher(), StrMatcher.quoteMatcher()).setTrimmerMatcher(StrMatcher.trimMatcher()).getTokenArray(); if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.configure")) { // CMD: /autoref cfg ... if (args.length > 1 && "cfg".equalsIgnoreCase(args[0])) { // CMD: /autoref cfg save if (args.length >= 2 && "save".equalsIgnoreCase(args[1]) && match != null) { match.saveWorldConfiguration(); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " saved."); } // CMD: /autoref init if (args.length >= 2 && "init".equalsIgnoreCase(args[1])) { // if there is not yet a match object for this map if (match == null) { addMatch(match = new AutoRefMatch(world, false)); match.saveWorldConfiguration(); match.setCurrentState(MatchStatus.NONE); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " generated."); } else sender.sendMessage(this.getName() + " already initialized for " + match.worldConfig.getString("map.name", "this map") + "."); } // CMD: /autoref cfg reload if (args.length >= 2 && "reload".equalsIgnoreCase(args[1]) && match != null) { match.reload(); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " reload complete!"); } return true; } // CMD: /autoref archive [zip] if (args.length >= 1 && "archive".equalsIgnoreCase(args[0]) && match != null) try { // LAST MINUTE CLEANUP!!! match.clearEntities(); world.setTime(match.getStartTime()); // save the world and configuration first world.save(); match.saveWorldConfiguration(); File archiveFolder = null; if (args.length >= 2 && "zip".equalsIgnoreCase(args[1])) archiveFolder = match.distributeMap(); else archiveFolder = match.archiveMapData(); String resp = String.format("%s %s", match.getVersionString(), archiveFolder == null ? "failed to archive." : "archived!"); sender.sendMessage(ChatColor.GREEN + resp); getLogger().info(resp); return true; } catch (Exception e) { return false; } // CMD: /autoref debug [console] if (args.length >= 1 && "debug".equalsIgnoreCase(args[0]) && match != null) { if (match.isDebugMode()) { match.setDebug(null); return true; } boolean consoleDebug = args.length >= 2 && "console".equalsIgnoreCase(args[1]); match.setDebug(consoleDebug ? getServer().getConsoleSender() : sender); return true; } // CMD: /autoref tool <type> if (args.length >= 1 && "tool".equalsIgnoreCase(args[0])) { // get the tool for setting win condition if (args.length >= 2 && "wincond".equalsIgnoreCase(args[1])) { // get the tool used to set the win conditions int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.win-condition", null), Material.GOLD_SPADE); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given win condition tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on a block to set it as a win-condition."); return true; } // get the tool for setting starting mechanisms if (args.length >= 2 && "startmech".equalsIgnoreCase(args[1])) { // get the tool used to set the starting mechanisms int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.start-mechanism", null), Material.GOLD_AXE); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given start mechanism tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on a device to set it as a starting mechanism."); return true; } // get the tool for setting protected entities if (args.length >= 2 && "protect".equalsIgnoreCase(args[1])) { // get the tool used to set the starting mechanisms int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.protect-entities", null), Material.GOLD_SWORD); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given entity protection tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on an entity to protect it from butchering."); return true; } } // CMD: /autoref nocraft if (args.length >= 1 && "nocraft".equalsIgnoreCase(args[0]) && match != null) { ItemStack item = player.getItemInHand(); if (item != null) match.addIllegalCraft(BlockData.fromItemStack(item)); return true; } // CMD: /autoref setspawn <team> if (args.length >= 2 && "setspawn".equalsIgnoreCase(args[0]) && match != null && player != null) { AutoRefTeam team = match.teamNameLookup(args[1]); if (team == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + args[1] + - ChatColor.RESET + "is not a valid team."); + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else { team.setSpawnLocation(player.getLocation()); String coords = BlockVector3.fromLocation(player.getLocation()).toCoords(); sender.sendMessage(ChatColor.GRAY + "Spawn set to " + coords + " for " + team.getName()); } return true; } } if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.admin")) { // CMD: /autoref world <world> if (args.length == 2 && "world".equalsIgnoreCase(args[0])) { consoleWorld = getServer().getWorld(args[1]); if (consoleWorld != null) sender.sendMessage("Selected world " + consoleWorld.getName()); return consoleWorld != null; } // CMD: /autoref load <map> [<custom>] if (args.length >= 2 && "load".equalsIgnoreCase(args[0])) try { // get generate a map name from the args String mapName = args[1]; // may specify a custom world name as the 3rd argument String customName = args.length >= 3 ? args[2] : null; // get world setup for match sender.sendMessage(ChatColor.GREEN + "Please wait..."); AutoRefMap.loadMap(sender, mapName, customName); return true; } catch (Exception e) { e.printStackTrace(); return true; } // CMD: /autoref unload if (args.length == 1 && "unload".equalsIgnoreCase(args[0]) && match != null) { match.destroy(); return true; } // CMD: /autoref reload if (args.length == 1 && "reload".equalsIgnoreCase(args[0]) && match != null) try { AutoRefMap map = AutoRefMap.getMap(match.getMapName()); if (map == null || !map.isInstalled()) { sender.sendMessage(ChatColor.DARK_GRAY + "No archive of this map exists " + match.getMapName()); return true; } sender.sendMessage(ChatColor.DARK_GRAY + "Preparing a new copy of " + map.getVersionString()); AutoRefMatch newmatch = AutoRefMap.createMatch(map, null); for (Player p : match.getWorld().getPlayers()) p.teleport(newmatch.getWorldSpawn()); match.destroy(); return true; } catch (Exception e) { e.printStackTrace(); return true; } // CMD: /autoref maplist if (args.length == 1 && "maplist".equalsIgnoreCase(args[0])) { List<AutoRefMap> maps = Lists.newArrayList(AutoRefMap.getAvailableMaps()); Collections.sort(maps); sender.sendMessage(ChatColor.GOLD + String.format("Available Maps (%d):", maps.size())); for (AutoRefMap mapInfo : maps) { ChatColor color = mapInfo.isInstalled() ? ChatColor.WHITE : ChatColor.DARK_GRAY; sender.sendMessage("* " + color + mapInfo.getVersionString()); } return true; } // CMD: /autoref update [force] if (args.length >= 1 && "update".equalsIgnoreCase(args[0])) { boolean force = (args.length >= 2 && args[1].startsWith("f")); AutoRefMap.getUpdates(sender, force); return true; } // CMD: /autoref state [<new state>] if (args.length >= 1 && "state".equalsIgnoreCase(args[0]) && match != null && match.isDebugMode()) try { if (args.length >= 2) match.setCurrentState(MatchStatus.valueOf(args[1].toUpperCase())); getLogger().info("Match Status is now " + match.getCurrentState().name()); return true; } catch (Exception e) { return false; } // CMD: /autoref autoinvite <players...> if (args.length > 1 && "autoinvite".equalsIgnoreCase(args[0])) { for (int i = 1; i < args.length; ++i) { // first, remove this player from all expected player lists OfflinePlayer opl = getServer().getOfflinePlayer(args[i]); for (AutoRefMatch m : getMatches()) m.removeExpectedPlayer(opl); // add them to the expected players list match.addExpectedPlayer(opl); // if this player cannot be found, skip Player invited = getServer().getPlayer(args[i]); if (invited == null) continue; // if this player is already busy competing in a match, skip AutoRefMatch m = getMatch(invited.getWorld()); if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue; // otherwise, let's drag them in (no asking) match.acceptInvitation(invited); } return true; } // CMD: /autoref send <msg> [<recipient>] if (args.length >= 2 && "send".equalsIgnoreCase(args[0]) && match != null && match.isDebugMode()) { Set<Player> targets = match.getReferees(); if (args.length >= 3) targets = Sets.newHashSet(getServer().getPlayer(args[2])); for (Player ref : targets) if (ref != null) ref.sendPluginMessage(this, AutoReferee.REFEREE_PLUGIN_CHANNEL, args[1].getBytes()); return true; } } if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.referee")) { // CMD: /autoref teamname <currentname> <newname> if (args.length == 3 && "teamname".equalsIgnoreCase(args[0]) && match != null) { AutoRefTeam team = null; for (AutoRefTeam t : match.getTeams()) if (t.matches(args[1])) team = t; if (team == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[1] + - ChatColor.RESET + "is not a valid team."); + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else team.setName(args[2]); return true; } // CMD: /autoref hud ... if (args.length >= 1 && "hud".equalsIgnoreCase(args[0]) && match != null) { // CMD: /autoref hud swap if (args.length >= 2 && "swap".equalsIgnoreCase(args[1])) { match.messageReferee(player, "match", match.getWorld().getName(), "swap"); return true; } } // CMD: /autoref swapteams <team1> <team2> if (args.length == 3 && "swapteams".equalsIgnoreCase(args[0]) && match != null) { AutoRefTeam team1 = null, team2 = null; for (AutoRefTeam t : match.getTeams()) { if (t.matches(args[1])) team1 = t; if (t.matches(args[2])) team2 = t; } if (team1 == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[1] + - ChatColor.RESET + "is not a valid team."); + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else if (team2 == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[2] + - ChatColor.RESET + "is not a valid team."); + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else AutoRefTeam.switchTeams(team1, team2); return true; } // CMD: /autoref countdown if (args.length == 1 && "countdown".equalsIgnoreCase(args[0]) && match != null) { match.startCountdown(0, false); return true; } } if ("autoref".equalsIgnoreCase(cmd.getName())) { // CMD: /autoref invite <players...> if (args.length > 1 && "invite".equalsIgnoreCase(args[0]) && match != null && match.getCurrentState().isBeforeMatch()) { // who is doing the inviting String from = (sender instanceof Player) ? match.getPlayerName(player) : "This server"; for (int i = 1; i < args.length; ++i) { // if this player cannot be found, skip Player invited = getServer().getPlayer(args[i]); if (invited == null) continue; // if this player is already busy competing in a match, skip AutoRefMatch m = getMatch(invited.getWorld()); if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue; // otherwise, invite them if (invited.getWorld() != match.getWorld()) new Conversation(this, invited, new InvitationPrompt(match, from)).begin(); } return true; } // CMD: /autoref version if (args.length >= 1 && "version".equalsIgnoreCase(args[0])) { sender.sendMessage(ChatColor.DARK_GRAY + "This server is running " + ChatColor.BLUE + this.getDescription().getFullName()); return true; } } if ("zones".equalsIgnoreCase(cmd.getName()) && match != null) { Set<AutoRefTeam> lookupTeams = null; // if a team has been specified as an argument if (args.length > 1) { AutoRefTeam t = match.teamNameLookup(args[1]); if (t == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + args[1] + - ChatColor.RESET + "is not a valid team."); + ChatColor.RESET + " is not a valid team."); return true; } lookupTeams = Sets.newHashSet(); lookupTeams.add(t); } // otherwise, just print all the teams else lookupTeams = match.getTeams(); // sanity check... if (lookupTeams == null) return false; // for all the teams being looked up for (AutoRefTeam team : lookupTeams) { // print team-name header sender.sendMessage(team.getName() + "'s Regions:"); // print all the regions owned by this team if (team.getRegions().size() > 0) for (CuboidRegion reg : team.getRegions()) { Vector3 mn = reg.getMinimumPoint(), mx = reg.getMaximumPoint(); sender.sendMessage(" (" + mn.toCoords() + ") => (" + mx.toCoords() + ")"); } // if there are no regions, print None else sender.sendMessage(" <None>"); } return true; } if ("zone".equalsIgnoreCase(cmd.getName()) && match != null) { WorldEditPlugin worldEdit = getWorldEdit(); if (worldEdit == null) { // world edit not installed sender.sendMessage("This method requires WorldEdit installed and running."); return true; } if (args.length == 0) { // command is invalid. let the player know sender.sendMessage("Must specify a team as this zone's owner."); return true; } // START is a sentinel Team object representing the start region AutoRefTeam t, START = new AutoRefTeam(); String tname = args[0]; t = "start".equals(tname) ? START : match.teamNameLookup(tname); if (t == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + tname + - ChatColor.RESET + "is not a valid team."); + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); return true; } Selection sel = worldEdit.getSelection(player); if ((sel instanceof CuboidSelection)) { CuboidSelection csel = (CuboidSelection) sel; CuboidRegion reg = new CuboidRegion( new Vector3(csel.getNativeMinimumPoint()), new Vector3(csel.getNativeMaximumPoint()) ); // sentinel value represents the start region if (t == START) { // set the start region to the selection match.setStartRegion(reg); sender.sendMessage("Region now marked as " + "the start region!"); } else { AutoRefRegion areg = new AutoRefRegion(reg); if (args.length >= 2) for (String f : args[1].split(",")) areg.toggle(f); // add the region to the team, announce t.getRegions().add(areg); sender.sendMessage("Region now marked as " + t.getName() + "'s zone!"); } } return true; } if ("matchinfo".equalsIgnoreCase(cmd.getName())) { if (match != null) match.sendMatchInfo(player); else sender.sendMessage(ChatColor.GRAY + this.getName() + " is not running for this world!"); return true; } if ("jointeam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode()) { // get the target team AutoRefTeam team = args.length > 0 ? match.teamNameLookup(args[0]) : match.getArbitraryTeam(); if (team == null) { // team name is invalid. let the player know if (args.length > 0) { sender.sendMessage(ChatColor.DARK_GRAY + args[0] + - ChatColor.RESET + "is not a valid team."); + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } return true; } // if there are players specified on the command line, add them if (args.length >= 2 && player.hasPermission("autoreferee.referee")) for (int i = 1; i < args.length; ++i) { Player target = getServer().getPlayer(args[i]); if (target != null) match.joinTeam(target, team, true); } // otherwise, add yourself else match.joinTeam(player, team, player.hasPermission("autoreferee.referee")); return true; } if ("leaveteam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode()) { // if there are players specified on the command line, remove them if (args.length >= 1 && player.hasPermission("autoreferee.referee")) for (int i = 0; i < args.length; ++i) { Player target = getServer().getPlayer(args[i]); if (target != null) match.leaveTeam(target, true); } // otherwise, remove yourself else match.leaveTeam(player, player.hasPermission("autoreferee.referee")); return true; } if ("viewinventory".equalsIgnoreCase(cmd.getName()) && args.length == 1 && match != null && player != null) { if (!match.isReferee(player)) { sender.sendMessage("You do not have permission."); return true; } AutoRefPlayer target = match.getPlayer(getServer().getPlayer(args[0])); if (target != null) target.showInventory(player); return true; } if ("ready".equalsIgnoreCase(cmd.getName()) && match != null && match.getCurrentState().isBeforeMatch()) { boolean rstate = true; if (args.length > 0) { String rstr = args[0].toLowerCase(); rstate = !rstr.startsWith("f") && !rstr.startsWith("n"); } if (match.isReferee(player)) { // attempt to set the ready delay if one is specified if (args.length > 0) try { match.setReadyDelay(Integer.parseInt(args[0])); } catch (NumberFormatException e) { }; match.setRefereeReady(rstate); } else { AutoRefTeam team = match.getPlayerTeam(player); if (team != null) team.setReady(rstate); } match.checkTeamsStart(); return true; } return false; } public class InvitationPrompt extends BooleanPrompt { public InvitationPrompt(AutoRefMatch match, String from) { this.match = match; this.from = from; } private AutoRefMatch match; private String from; @Override public String getPromptText(ConversationContext context) { return String.format("%s is inviting you to a match on %s. Do you accept?", from, match.getMapName()); } @Override protected Prompt acceptValidatedInput(ConversationContext context, boolean response) { if (response && context.getForWhom() instanceof Player) match.acceptInvitation((Player) context.getForWhom()); return Prompt.END_OF_CONVERSATION; } } File getLogDirectory() { // create the log directory if it doesn't exist File logdir = new File(getDataFolder(), "logs"); if (!logdir.exists()) logdir.mkdir(); // return the reference to the log directory return logdir; } // ABANDON HOPE, ALL YE WHO ENTER HERE! public static long parseTimeString(String t) { // "Some people, when confronted with a problem, think 'I know, I'll use // regular expressions.' Now they have two problems." -- Jamie Zawinski Pattern pattern = Pattern.compile("(\\d{1,5})(:(\\d{2}))?((a|p)m?)?", Pattern.CASE_INSENSITIVE); Matcher match = pattern.matcher(t); // if the time matches something sensible if (match.matches()) try { // get the primary value (could be hour, could be entire time in ticks) long prim = Long.parseLong(match.group(1)); if (match.group(1).length() > 2 || prim > 24) return prim; // parse am/pm distinction (12am == midnight, 12pm == noon) if (match.group(5) != null) prim = ("p".equals(match.group(5)) ? 12 : 0) + (prim % 12L); // ticks are 1000/hour, group(3) is the minutes portion long ticks = prim * 1000L + (match.group(3) == null ? 0L : (Long.parseLong(match.group(3)) * 1000L / 60L)); // ticks (18000 == midnight, 6000 == noon) return (ticks + 18000L) % 24000L; } catch (NumberFormatException e) { }; // default time: 6am return 0L; } // ************************ CUSTOM API ************************ private static Method mAffectsSpawning = null; private static Method mCollidesWithEntities = null; static { try { mAffectsSpawning = HumanEntity.class.getDeclaredMethod("setAffectsSpawning", boolean.class); mCollidesWithEntities = Player.class.getDeclaredMethod("setCollidesWithEntities", boolean.class); } catch (Exception e) { } } public static boolean hasSportBukkitApi() { return mAffectsSpawning != null && mCollidesWithEntities != null; } public static void setAffectsSpawning(Player p, boolean yes) { if (mAffectsSpawning != null) try { mAffectsSpawning.invoke(p, yes); } catch (Exception e) { } } public static void setCollidesWithEntities(Player p, boolean yes) { if (mCollidesWithEntities != null) try { mCollidesWithEntities.invoke(p, yes); } catch (Exception e) { } } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { World world = null; Player player = null; if (sender instanceof Player) { player = (Player) sender; world = player.getWorld(); } else world = consoleWorld; AutoRefMatch match = getMatch(world); // reparse the args properly using the string tokenizer from org.apache.commons args = new StrTokenizer(StringUtils.join(args, ' '), StrMatcher.splitMatcher(), StrMatcher.quoteMatcher()).setTrimmerMatcher(StrMatcher.trimMatcher()).getTokenArray(); if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.configure")) { // CMD: /autoref cfg ... if (args.length > 1 && "cfg".equalsIgnoreCase(args[0])) { // CMD: /autoref cfg save if (args.length >= 2 && "save".equalsIgnoreCase(args[1]) && match != null) { match.saveWorldConfiguration(); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " saved."); } // CMD: /autoref init if (args.length >= 2 && "init".equalsIgnoreCase(args[1])) { // if there is not yet a match object for this map if (match == null) { addMatch(match = new AutoRefMatch(world, false)); match.saveWorldConfiguration(); match.setCurrentState(MatchStatus.NONE); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " generated."); } else sender.sendMessage(this.getName() + " already initialized for " + match.worldConfig.getString("map.name", "this map") + "."); } // CMD: /autoref cfg reload if (args.length >= 2 && "reload".equalsIgnoreCase(args[1]) && match != null) { match.reload(); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " reload complete!"); } return true; } // CMD: /autoref archive [zip] if (args.length >= 1 && "archive".equalsIgnoreCase(args[0]) && match != null) try { // LAST MINUTE CLEANUP!!! match.clearEntities(); world.setTime(match.getStartTime()); // save the world and configuration first world.save(); match.saveWorldConfiguration(); File archiveFolder = null; if (args.length >= 2 && "zip".equalsIgnoreCase(args[1])) archiveFolder = match.distributeMap(); else archiveFolder = match.archiveMapData(); String resp = String.format("%s %s", match.getVersionString(), archiveFolder == null ? "failed to archive." : "archived!"); sender.sendMessage(ChatColor.GREEN + resp); getLogger().info(resp); return true; } catch (Exception e) { return false; } // CMD: /autoref debug [console] if (args.length >= 1 && "debug".equalsIgnoreCase(args[0]) && match != null) { if (match.isDebugMode()) { match.setDebug(null); return true; } boolean consoleDebug = args.length >= 2 && "console".equalsIgnoreCase(args[1]); match.setDebug(consoleDebug ? getServer().getConsoleSender() : sender); return true; } // CMD: /autoref tool <type> if (args.length >= 1 && "tool".equalsIgnoreCase(args[0])) { // get the tool for setting win condition if (args.length >= 2 && "wincond".equalsIgnoreCase(args[1])) { // get the tool used to set the win conditions int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.win-condition", null), Material.GOLD_SPADE); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given win condition tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on a block to set it as a win-condition."); return true; } // get the tool for setting starting mechanisms if (args.length >= 2 && "startmech".equalsIgnoreCase(args[1])) { // get the tool used to set the starting mechanisms int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.start-mechanism", null), Material.GOLD_AXE); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given start mechanism tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on a device to set it as a starting mechanism."); return true; } // get the tool for setting protected entities if (args.length >= 2 && "protect".equalsIgnoreCase(args[1])) { // get the tool used to set the starting mechanisms int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.protect-entities", null), Material.GOLD_SWORD); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given entity protection tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on an entity to protect it from butchering."); return true; } } // CMD: /autoref nocraft if (args.length >= 1 && "nocraft".equalsIgnoreCase(args[0]) && match != null) { ItemStack item = player.getItemInHand(); if (item != null) match.addIllegalCraft(BlockData.fromItemStack(item)); return true; } // CMD: /autoref setspawn <team> if (args.length >= 2 && "setspawn".equalsIgnoreCase(args[0]) && match != null && player != null) { AutoRefTeam team = match.teamNameLookup(args[1]); if (team == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + "is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else { team.setSpawnLocation(player.getLocation()); String coords = BlockVector3.fromLocation(player.getLocation()).toCoords(); sender.sendMessage(ChatColor.GRAY + "Spawn set to " + coords + " for " + team.getName()); } return true; } } if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.admin")) { // CMD: /autoref world <world> if (args.length == 2 && "world".equalsIgnoreCase(args[0])) { consoleWorld = getServer().getWorld(args[1]); if (consoleWorld != null) sender.sendMessage("Selected world " + consoleWorld.getName()); return consoleWorld != null; } // CMD: /autoref load <map> [<custom>] if (args.length >= 2 && "load".equalsIgnoreCase(args[0])) try { // get generate a map name from the args String mapName = args[1]; // may specify a custom world name as the 3rd argument String customName = args.length >= 3 ? args[2] : null; // get world setup for match sender.sendMessage(ChatColor.GREEN + "Please wait..."); AutoRefMap.loadMap(sender, mapName, customName); return true; } catch (Exception e) { e.printStackTrace(); return true; } // CMD: /autoref unload if (args.length == 1 && "unload".equalsIgnoreCase(args[0]) && match != null) { match.destroy(); return true; } // CMD: /autoref reload if (args.length == 1 && "reload".equalsIgnoreCase(args[0]) && match != null) try { AutoRefMap map = AutoRefMap.getMap(match.getMapName()); if (map == null || !map.isInstalled()) { sender.sendMessage(ChatColor.DARK_GRAY + "No archive of this map exists " + match.getMapName()); return true; } sender.sendMessage(ChatColor.DARK_GRAY + "Preparing a new copy of " + map.getVersionString()); AutoRefMatch newmatch = AutoRefMap.createMatch(map, null); for (Player p : match.getWorld().getPlayers()) p.teleport(newmatch.getWorldSpawn()); match.destroy(); return true; } catch (Exception e) { e.printStackTrace(); return true; } // CMD: /autoref maplist if (args.length == 1 && "maplist".equalsIgnoreCase(args[0])) { List<AutoRefMap> maps = Lists.newArrayList(AutoRefMap.getAvailableMaps()); Collections.sort(maps); sender.sendMessage(ChatColor.GOLD + String.format("Available Maps (%d):", maps.size())); for (AutoRefMap mapInfo : maps) { ChatColor color = mapInfo.isInstalled() ? ChatColor.WHITE : ChatColor.DARK_GRAY; sender.sendMessage("* " + color + mapInfo.getVersionString()); } return true; } // CMD: /autoref update [force] if (args.length >= 1 && "update".equalsIgnoreCase(args[0])) { boolean force = (args.length >= 2 && args[1].startsWith("f")); AutoRefMap.getUpdates(sender, force); return true; } // CMD: /autoref state [<new state>] if (args.length >= 1 && "state".equalsIgnoreCase(args[0]) && match != null && match.isDebugMode()) try { if (args.length >= 2) match.setCurrentState(MatchStatus.valueOf(args[1].toUpperCase())); getLogger().info("Match Status is now " + match.getCurrentState().name()); return true; } catch (Exception e) { return false; } // CMD: /autoref autoinvite <players...> if (args.length > 1 && "autoinvite".equalsIgnoreCase(args[0])) { for (int i = 1; i < args.length; ++i) { // first, remove this player from all expected player lists OfflinePlayer opl = getServer().getOfflinePlayer(args[i]); for (AutoRefMatch m : getMatches()) m.removeExpectedPlayer(opl); // add them to the expected players list match.addExpectedPlayer(opl); // if this player cannot be found, skip Player invited = getServer().getPlayer(args[i]); if (invited == null) continue; // if this player is already busy competing in a match, skip AutoRefMatch m = getMatch(invited.getWorld()); if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue; // otherwise, let's drag them in (no asking) match.acceptInvitation(invited); } return true; } // CMD: /autoref send <msg> [<recipient>] if (args.length >= 2 && "send".equalsIgnoreCase(args[0]) && match != null && match.isDebugMode()) { Set<Player> targets = match.getReferees(); if (args.length >= 3) targets = Sets.newHashSet(getServer().getPlayer(args[2])); for (Player ref : targets) if (ref != null) ref.sendPluginMessage(this, AutoReferee.REFEREE_PLUGIN_CHANNEL, args[1].getBytes()); return true; } } if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.referee")) { // CMD: /autoref teamname <currentname> <newname> if (args.length == 3 && "teamname".equalsIgnoreCase(args[0]) && match != null) { AutoRefTeam team = null; for (AutoRefTeam t : match.getTeams()) if (t.matches(args[1])) team = t; if (team == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + "is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else team.setName(args[2]); return true; } // CMD: /autoref hud ... if (args.length >= 1 && "hud".equalsIgnoreCase(args[0]) && match != null) { // CMD: /autoref hud swap if (args.length >= 2 && "swap".equalsIgnoreCase(args[1])) { match.messageReferee(player, "match", match.getWorld().getName(), "swap"); return true; } } // CMD: /autoref swapteams <team1> <team2> if (args.length == 3 && "swapteams".equalsIgnoreCase(args[0]) && match != null) { AutoRefTeam team1 = null, team2 = null; for (AutoRefTeam t : match.getTeams()) { if (t.matches(args[1])) team1 = t; if (t.matches(args[2])) team2 = t; } if (team1 == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + "is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else if (team2 == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[2] + ChatColor.RESET + "is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else AutoRefTeam.switchTeams(team1, team2); return true; } // CMD: /autoref countdown if (args.length == 1 && "countdown".equalsIgnoreCase(args[0]) && match != null) { match.startCountdown(0, false); return true; } } if ("autoref".equalsIgnoreCase(cmd.getName())) { // CMD: /autoref invite <players...> if (args.length > 1 && "invite".equalsIgnoreCase(args[0]) && match != null && match.getCurrentState().isBeforeMatch()) { // who is doing the inviting String from = (sender instanceof Player) ? match.getPlayerName(player) : "This server"; for (int i = 1; i < args.length; ++i) { // if this player cannot be found, skip Player invited = getServer().getPlayer(args[i]); if (invited == null) continue; // if this player is already busy competing in a match, skip AutoRefMatch m = getMatch(invited.getWorld()); if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue; // otherwise, invite them if (invited.getWorld() != match.getWorld()) new Conversation(this, invited, new InvitationPrompt(match, from)).begin(); } return true; } // CMD: /autoref version if (args.length >= 1 && "version".equalsIgnoreCase(args[0])) { sender.sendMessage(ChatColor.DARK_GRAY + "This server is running " + ChatColor.BLUE + this.getDescription().getFullName()); return true; } } if ("zones".equalsIgnoreCase(cmd.getName()) && match != null) { Set<AutoRefTeam> lookupTeams = null; // if a team has been specified as an argument if (args.length > 1) { AutoRefTeam t = match.teamNameLookup(args[1]); if (t == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + "is not a valid team."); return true; } lookupTeams = Sets.newHashSet(); lookupTeams.add(t); } // otherwise, just print all the teams else lookupTeams = match.getTeams(); // sanity check... if (lookupTeams == null) return false; // for all the teams being looked up for (AutoRefTeam team : lookupTeams) { // print team-name header sender.sendMessage(team.getName() + "'s Regions:"); // print all the regions owned by this team if (team.getRegions().size() > 0) for (CuboidRegion reg : team.getRegions()) { Vector3 mn = reg.getMinimumPoint(), mx = reg.getMaximumPoint(); sender.sendMessage(" (" + mn.toCoords() + ") => (" + mx.toCoords() + ")"); } // if there are no regions, print None else sender.sendMessage(" <None>"); } return true; } if ("zone".equalsIgnoreCase(cmd.getName()) && match != null) { WorldEditPlugin worldEdit = getWorldEdit(); if (worldEdit == null) { // world edit not installed sender.sendMessage("This method requires WorldEdit installed and running."); return true; } if (args.length == 0) { // command is invalid. let the player know sender.sendMessage("Must specify a team as this zone's owner."); return true; } // START is a sentinel Team object representing the start region AutoRefTeam t, START = new AutoRefTeam(); String tname = args[0]; t = "start".equals(tname) ? START : match.teamNameLookup(tname); if (t == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + tname + ChatColor.RESET + "is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); return true; } Selection sel = worldEdit.getSelection(player); if ((sel instanceof CuboidSelection)) { CuboidSelection csel = (CuboidSelection) sel; CuboidRegion reg = new CuboidRegion( new Vector3(csel.getNativeMinimumPoint()), new Vector3(csel.getNativeMaximumPoint()) ); // sentinel value represents the start region if (t == START) { // set the start region to the selection match.setStartRegion(reg); sender.sendMessage("Region now marked as " + "the start region!"); } else { AutoRefRegion areg = new AutoRefRegion(reg); if (args.length >= 2) for (String f : args[1].split(",")) areg.toggle(f); // add the region to the team, announce t.getRegions().add(areg); sender.sendMessage("Region now marked as " + t.getName() + "'s zone!"); } } return true; } if ("matchinfo".equalsIgnoreCase(cmd.getName())) { if (match != null) match.sendMatchInfo(player); else sender.sendMessage(ChatColor.GRAY + this.getName() + " is not running for this world!"); return true; } if ("jointeam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode()) { // get the target team AutoRefTeam team = args.length > 0 ? match.teamNameLookup(args[0]) : match.getArbitraryTeam(); if (team == null) { // team name is invalid. let the player know if (args.length > 0) { sender.sendMessage(ChatColor.DARK_GRAY + args[0] + ChatColor.RESET + "is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } return true; } // if there are players specified on the command line, add them if (args.length >= 2 && player.hasPermission("autoreferee.referee")) for (int i = 1; i < args.length; ++i) { Player target = getServer().getPlayer(args[i]); if (target != null) match.joinTeam(target, team, true); } // otherwise, add yourself else match.joinTeam(player, team, player.hasPermission("autoreferee.referee")); return true; } if ("leaveteam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode()) { // if there are players specified on the command line, remove them if (args.length >= 1 && player.hasPermission("autoreferee.referee")) for (int i = 0; i < args.length; ++i) { Player target = getServer().getPlayer(args[i]); if (target != null) match.leaveTeam(target, true); } // otherwise, remove yourself else match.leaveTeam(player, player.hasPermission("autoreferee.referee")); return true; } if ("viewinventory".equalsIgnoreCase(cmd.getName()) && args.length == 1 && match != null && player != null) { if (!match.isReferee(player)) { sender.sendMessage("You do not have permission."); return true; } AutoRefPlayer target = match.getPlayer(getServer().getPlayer(args[0])); if (target != null) target.showInventory(player); return true; } if ("ready".equalsIgnoreCase(cmd.getName()) && match != null && match.getCurrentState().isBeforeMatch()) { boolean rstate = true; if (args.length > 0) { String rstr = args[0].toLowerCase(); rstate = !rstr.startsWith("f") && !rstr.startsWith("n"); } if (match.isReferee(player)) { // attempt to set the ready delay if one is specified if (args.length > 0) try { match.setReadyDelay(Integer.parseInt(args[0])); } catch (NumberFormatException e) { }; match.setRefereeReady(rstate); } else { AutoRefTeam team = match.getPlayerTeam(player); if (team != null) team.setReady(rstate); } match.checkTeamsStart(); return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { World world = null; Player player = null; if (sender instanceof Player) { player = (Player) sender; world = player.getWorld(); } else world = consoleWorld; AutoRefMatch match = getMatch(world); // reparse the args properly using the string tokenizer from org.apache.commons args = new StrTokenizer(StringUtils.join(args, ' '), StrMatcher.splitMatcher(), StrMatcher.quoteMatcher()).setTrimmerMatcher(StrMatcher.trimMatcher()).getTokenArray(); if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.configure")) { // CMD: /autoref cfg ... if (args.length > 1 && "cfg".equalsIgnoreCase(args[0])) { // CMD: /autoref cfg save if (args.length >= 2 && "save".equalsIgnoreCase(args[1]) && match != null) { match.saveWorldConfiguration(); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " saved."); } // CMD: /autoref init if (args.length >= 2 && "init".equalsIgnoreCase(args[1])) { // if there is not yet a match object for this map if (match == null) { addMatch(match = new AutoRefMatch(world, false)); match.saveWorldConfiguration(); match.setCurrentState(MatchStatus.NONE); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " generated."); } else sender.sendMessage(this.getName() + " already initialized for " + match.worldConfig.getString("map.name", "this map") + "."); } // CMD: /autoref cfg reload if (args.length >= 2 && "reload".equalsIgnoreCase(args[1]) && match != null) { match.reload(); sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " reload complete!"); } return true; } // CMD: /autoref archive [zip] if (args.length >= 1 && "archive".equalsIgnoreCase(args[0]) && match != null) try { // LAST MINUTE CLEANUP!!! match.clearEntities(); world.setTime(match.getStartTime()); // save the world and configuration first world.save(); match.saveWorldConfiguration(); File archiveFolder = null; if (args.length >= 2 && "zip".equalsIgnoreCase(args[1])) archiveFolder = match.distributeMap(); else archiveFolder = match.archiveMapData(); String resp = String.format("%s %s", match.getVersionString(), archiveFolder == null ? "failed to archive." : "archived!"); sender.sendMessage(ChatColor.GREEN + resp); getLogger().info(resp); return true; } catch (Exception e) { return false; } // CMD: /autoref debug [console] if (args.length >= 1 && "debug".equalsIgnoreCase(args[0]) && match != null) { if (match.isDebugMode()) { match.setDebug(null); return true; } boolean consoleDebug = args.length >= 2 && "console".equalsIgnoreCase(args[1]); match.setDebug(consoleDebug ? getServer().getConsoleSender() : sender); return true; } // CMD: /autoref tool <type> if (args.length >= 1 && "tool".equalsIgnoreCase(args[0])) { // get the tool for setting win condition if (args.length >= 2 && "wincond".equalsIgnoreCase(args[1])) { // get the tool used to set the win conditions int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.win-condition", null), Material.GOLD_SPADE); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given win condition tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on a block to set it as a win-condition."); return true; } // get the tool for setting starting mechanisms if (args.length >= 2 && "startmech".equalsIgnoreCase(args[1])) { // get the tool used to set the starting mechanisms int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.start-mechanism", null), Material.GOLD_AXE); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given start mechanism tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on a device to set it as a starting mechanism."); return true; } // get the tool for setting protected entities if (args.length >= 2 && "protect".equalsIgnoreCase(args[1])) { // get the tool used to set the starting mechanisms int toolID = ZoneListener.parseTool(getConfig().getString( "config-mode.tools.protect-entities", null), Material.GOLD_SWORD); ItemStack toolitem = new ItemStack(toolID); // add to the inventory and switch to holding it PlayerInventory inv = player.getInventory(); inv.addItem(toolitem); // let the player know what the tool is and how to use it sender.sendMessage("Given entity protection tool: " + toolitem.getType().name()); sender.sendMessage("Right-click on an entity to protect it from butchering."); return true; } } // CMD: /autoref nocraft if (args.length >= 1 && "nocraft".equalsIgnoreCase(args[0]) && match != null) { ItemStack item = player.getItemInHand(); if (item != null) match.addIllegalCraft(BlockData.fromItemStack(item)); return true; } // CMD: /autoref setspawn <team> if (args.length >= 2 && "setspawn".equalsIgnoreCase(args[0]) && match != null && player != null) { AutoRefTeam team = match.teamNameLookup(args[1]); if (team == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else { team.setSpawnLocation(player.getLocation()); String coords = BlockVector3.fromLocation(player.getLocation()).toCoords(); sender.sendMessage(ChatColor.GRAY + "Spawn set to " + coords + " for " + team.getName()); } return true; } } if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.admin")) { // CMD: /autoref world <world> if (args.length == 2 && "world".equalsIgnoreCase(args[0])) { consoleWorld = getServer().getWorld(args[1]); if (consoleWorld != null) sender.sendMessage("Selected world " + consoleWorld.getName()); return consoleWorld != null; } // CMD: /autoref load <map> [<custom>] if (args.length >= 2 && "load".equalsIgnoreCase(args[0])) try { // get generate a map name from the args String mapName = args[1]; // may specify a custom world name as the 3rd argument String customName = args.length >= 3 ? args[2] : null; // get world setup for match sender.sendMessage(ChatColor.GREEN + "Please wait..."); AutoRefMap.loadMap(sender, mapName, customName); return true; } catch (Exception e) { e.printStackTrace(); return true; } // CMD: /autoref unload if (args.length == 1 && "unload".equalsIgnoreCase(args[0]) && match != null) { match.destroy(); return true; } // CMD: /autoref reload if (args.length == 1 && "reload".equalsIgnoreCase(args[0]) && match != null) try { AutoRefMap map = AutoRefMap.getMap(match.getMapName()); if (map == null || !map.isInstalled()) { sender.sendMessage(ChatColor.DARK_GRAY + "No archive of this map exists " + match.getMapName()); return true; } sender.sendMessage(ChatColor.DARK_GRAY + "Preparing a new copy of " + map.getVersionString()); AutoRefMatch newmatch = AutoRefMap.createMatch(map, null); for (Player p : match.getWorld().getPlayers()) p.teleport(newmatch.getWorldSpawn()); match.destroy(); return true; } catch (Exception e) { e.printStackTrace(); return true; } // CMD: /autoref maplist if (args.length == 1 && "maplist".equalsIgnoreCase(args[0])) { List<AutoRefMap> maps = Lists.newArrayList(AutoRefMap.getAvailableMaps()); Collections.sort(maps); sender.sendMessage(ChatColor.GOLD + String.format("Available Maps (%d):", maps.size())); for (AutoRefMap mapInfo : maps) { ChatColor color = mapInfo.isInstalled() ? ChatColor.WHITE : ChatColor.DARK_GRAY; sender.sendMessage("* " + color + mapInfo.getVersionString()); } return true; } // CMD: /autoref update [force] if (args.length >= 1 && "update".equalsIgnoreCase(args[0])) { boolean force = (args.length >= 2 && args[1].startsWith("f")); AutoRefMap.getUpdates(sender, force); return true; } // CMD: /autoref state [<new state>] if (args.length >= 1 && "state".equalsIgnoreCase(args[0]) && match != null && match.isDebugMode()) try { if (args.length >= 2) match.setCurrentState(MatchStatus.valueOf(args[1].toUpperCase())); getLogger().info("Match Status is now " + match.getCurrentState().name()); return true; } catch (Exception e) { return false; } // CMD: /autoref autoinvite <players...> if (args.length > 1 && "autoinvite".equalsIgnoreCase(args[0])) { for (int i = 1; i < args.length; ++i) { // first, remove this player from all expected player lists OfflinePlayer opl = getServer().getOfflinePlayer(args[i]); for (AutoRefMatch m : getMatches()) m.removeExpectedPlayer(opl); // add them to the expected players list match.addExpectedPlayer(opl); // if this player cannot be found, skip Player invited = getServer().getPlayer(args[i]); if (invited == null) continue; // if this player is already busy competing in a match, skip AutoRefMatch m = getMatch(invited.getWorld()); if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue; // otherwise, let's drag them in (no asking) match.acceptInvitation(invited); } return true; } // CMD: /autoref send <msg> [<recipient>] if (args.length >= 2 && "send".equalsIgnoreCase(args[0]) && match != null && match.isDebugMode()) { Set<Player> targets = match.getReferees(); if (args.length >= 3) targets = Sets.newHashSet(getServer().getPlayer(args[2])); for (Player ref : targets) if (ref != null) ref.sendPluginMessage(this, AutoReferee.REFEREE_PLUGIN_CHANNEL, args[1].getBytes()); return true; } } if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.referee")) { // CMD: /autoref teamname <currentname> <newname> if (args.length == 3 && "teamname".equalsIgnoreCase(args[0]) && match != null) { AutoRefTeam team = null; for (AutoRefTeam t : match.getTeams()) if (t.matches(args[1])) team = t; if (team == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else team.setName(args[2]); return true; } // CMD: /autoref hud ... if (args.length >= 1 && "hud".equalsIgnoreCase(args[0]) && match != null) { // CMD: /autoref hud swap if (args.length >= 2 && "swap".equalsIgnoreCase(args[1])) { match.messageReferee(player, "match", match.getWorld().getName(), "swap"); return true; } } // CMD: /autoref swapteams <team1> <team2> if (args.length == 3 && "swapteams".equalsIgnoreCase(args[0]) && match != null) { AutoRefTeam team1 = null, team2 = null; for (AutoRefTeam t : match.getTeams()) { if (t.matches(args[1])) team1 = t; if (t.matches(args[2])) team2 = t; } if (team1 == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else if (team2 == null) { sender.sendMessage(ChatColor.DARK_GRAY + args[2] + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } else AutoRefTeam.switchTeams(team1, team2); return true; } // CMD: /autoref countdown if (args.length == 1 && "countdown".equalsIgnoreCase(args[0]) && match != null) { match.startCountdown(0, false); return true; } } if ("autoref".equalsIgnoreCase(cmd.getName())) { // CMD: /autoref invite <players...> if (args.length > 1 && "invite".equalsIgnoreCase(args[0]) && match != null && match.getCurrentState().isBeforeMatch()) { // who is doing the inviting String from = (sender instanceof Player) ? match.getPlayerName(player) : "This server"; for (int i = 1; i < args.length; ++i) { // if this player cannot be found, skip Player invited = getServer().getPlayer(args[i]); if (invited == null) continue; // if this player is already busy competing in a match, skip AutoRefMatch m = getMatch(invited.getWorld()); if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue; // otherwise, invite them if (invited.getWorld() != match.getWorld()) new Conversation(this, invited, new InvitationPrompt(match, from)).begin(); } return true; } // CMD: /autoref version if (args.length >= 1 && "version".equalsIgnoreCase(args[0])) { sender.sendMessage(ChatColor.DARK_GRAY + "This server is running " + ChatColor.BLUE + this.getDescription().getFullName()); return true; } } if ("zones".equalsIgnoreCase(cmd.getName()) && match != null) { Set<AutoRefTeam> lookupTeams = null; // if a team has been specified as an argument if (args.length > 1) { AutoRefTeam t = match.teamNameLookup(args[1]); if (t == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + args[1] + ChatColor.RESET + " is not a valid team."); return true; } lookupTeams = Sets.newHashSet(); lookupTeams.add(t); } // otherwise, just print all the teams else lookupTeams = match.getTeams(); // sanity check... if (lookupTeams == null) return false; // for all the teams being looked up for (AutoRefTeam team : lookupTeams) { // print team-name header sender.sendMessage(team.getName() + "'s Regions:"); // print all the regions owned by this team if (team.getRegions().size() > 0) for (CuboidRegion reg : team.getRegions()) { Vector3 mn = reg.getMinimumPoint(), mx = reg.getMaximumPoint(); sender.sendMessage(" (" + mn.toCoords() + ") => (" + mx.toCoords() + ")"); } // if there are no regions, print None else sender.sendMessage(" <None>"); } return true; } if ("zone".equalsIgnoreCase(cmd.getName()) && match != null) { WorldEditPlugin worldEdit = getWorldEdit(); if (worldEdit == null) { // world edit not installed sender.sendMessage("This method requires WorldEdit installed and running."); return true; } if (args.length == 0) { // command is invalid. let the player know sender.sendMessage("Must specify a team as this zone's owner."); return true; } // START is a sentinel Team object representing the start region AutoRefTeam t, START = new AutoRefTeam(); String tname = args[0]; t = "start".equals(tname) ? START : match.teamNameLookup(tname); if (t == null) { // team name is invalid. let the player know sender.sendMessage(ChatColor.DARK_GRAY + tname + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); return true; } Selection sel = worldEdit.getSelection(player); if ((sel instanceof CuboidSelection)) { CuboidSelection csel = (CuboidSelection) sel; CuboidRegion reg = new CuboidRegion( new Vector3(csel.getNativeMinimumPoint()), new Vector3(csel.getNativeMaximumPoint()) ); // sentinel value represents the start region if (t == START) { // set the start region to the selection match.setStartRegion(reg); sender.sendMessage("Region now marked as " + "the start region!"); } else { AutoRefRegion areg = new AutoRefRegion(reg); if (args.length >= 2) for (String f : args[1].split(",")) areg.toggle(f); // add the region to the team, announce t.getRegions().add(areg); sender.sendMessage("Region now marked as " + t.getName() + "'s zone!"); } } return true; } if ("matchinfo".equalsIgnoreCase(cmd.getName())) { if (match != null) match.sendMatchInfo(player); else sender.sendMessage(ChatColor.GRAY + this.getName() + " is not running for this world!"); return true; } if ("jointeam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode()) { // get the target team AutoRefTeam team = args.length > 0 ? match.teamNameLookup(args[0]) : match.getArbitraryTeam(); if (team == null) { // team name is invalid. let the player know if (args.length > 0) { sender.sendMessage(ChatColor.DARK_GRAY + args[0] + ChatColor.RESET + " is not a valid team."); sender.sendMessage("Teams are " + match.getTeamList()); } return true; } // if there are players specified on the command line, add them if (args.length >= 2 && player.hasPermission("autoreferee.referee")) for (int i = 1; i < args.length; ++i) { Player target = getServer().getPlayer(args[i]); if (target != null) match.joinTeam(target, team, true); } // otherwise, add yourself else match.joinTeam(player, team, player.hasPermission("autoreferee.referee")); return true; } if ("leaveteam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode()) { // if there are players specified on the command line, remove them if (args.length >= 1 && player.hasPermission("autoreferee.referee")) for (int i = 0; i < args.length; ++i) { Player target = getServer().getPlayer(args[i]); if (target != null) match.leaveTeam(target, true); } // otherwise, remove yourself else match.leaveTeam(player, player.hasPermission("autoreferee.referee")); return true; } if ("viewinventory".equalsIgnoreCase(cmd.getName()) && args.length == 1 && match != null && player != null) { if (!match.isReferee(player)) { sender.sendMessage("You do not have permission."); return true; } AutoRefPlayer target = match.getPlayer(getServer().getPlayer(args[0])); if (target != null) target.showInventory(player); return true; } if ("ready".equalsIgnoreCase(cmd.getName()) && match != null && match.getCurrentState().isBeforeMatch()) { boolean rstate = true; if (args.length > 0) { String rstr = args[0].toLowerCase(); rstate = !rstr.startsWith("f") && !rstr.startsWith("n"); } if (match.isReferee(player)) { // attempt to set the ready delay if one is specified if (args.length > 0) try { match.setReadyDelay(Integer.parseInt(args[0])); } catch (NumberFormatException e) { }; match.setRefereeReady(rstate); } else { AutoRefTeam team = match.getPlayerTeam(player); if (team != null) team.setReady(rstate); } match.checkTeamsStart(); return true; } return false; }
diff --git a/src/main/java/org/basex/query/util/pkg/ModuleLoader.java b/src/main/java/org/basex/query/util/pkg/ModuleLoader.java index 3f1c776d8..e0907a6e9 100644 --- a/src/main/java/org/basex/query/util/pkg/ModuleLoader.java +++ b/src/main/java/org/basex/query/util/pkg/ModuleLoader.java @@ -1,342 +1,342 @@ package org.basex.query.util.pkg; import static org.basex.query.QueryText.*; import static org.basex.query.util.Err.*; import static org.basex.util.Token.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import org.basex.core.*; import org.basex.io.*; import org.basex.query.*; import org.basex.query.util.pkg.Package.Component; import org.basex.query.util.pkg.Package.Dependency; import org.basex.util.*; import org.basex.util.hash.*; /** * Module loader. * * @author BaseX Team 2005-12, BSD License * @author Christian Gruen */ public final class ModuleLoader { /** Default class loader. */ private static final ClassLoader LOADER = Thread.currentThread().getContextClassLoader(); /** Cached URLs to be added to the class loader. */ private final ArrayList<URL> urls = new ArrayList<URL>(); /** Current class loader. */ private ClassLoader loader = LOADER; /** Java modules. */ private HashMap<Object, ArrayList<Method>> javaModules; /** Database context. */ private final Context context; /** * Constructor. * @param ctx database context */ public ModuleLoader(final Context ctx) { context = ctx; } /** * Closes opened jar files. */ public void close() { if(loader instanceof JarLoader) ((JarLoader) loader).close(); } /** * Adds a package from the repository or a Java class. * @param uri module uri * @param ii input info * @param qp query parser * @return if the package has been found * @throws QueryException query exception */ public boolean addImport(final byte[] uri, final InputInfo ii, final QueryParser qp) throws QueryException { // add EXPath package final TokenSet pkgs = context.repo.nsDict().get(uri); if(pkgs != null) { Version ver = null; byte[] nm = null; for(final byte[] name : pkgs) { final Version v = new Version(Package.version(name)); if(ver == null || v.compareTo(ver) > 0) { ver = v; nm = name; } } if(nm != null) { addRepo(nm, new TokenSet(), new TokenSet(), ii, qp); return true; } } // search module in repository: rewrite URI to file path final boolean java = startsWith(uri, JAVAPREF); String uriPath = uri2path(string(java ? substring(uri, JAVAPREF.length) : uri)); if(uriPath == null) return false; - final boolean suffix = IO.suffix(uriPath).isEmpty(); + final boolean suffix = !IO.suffix(uriPath).isEmpty(); if(!java) { // no "java:" prefix: first try to import module as XQuery final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; if(suffix) { // check if file has XQuery suffix final IOFile f = new IOFile(path); if(f.hasSuffix(IO.XQSUFFIXES)) return addModule(f, uri, qp); } else { // check for any file with XQuery suffix for(final String suf : IO.XQSUFFIXES) { if(addModule(new IOFile(path + suf), uri, qp)) return true; } } } // "java:" prefix, or no XQuery package found: try to load Java module uriPath = capitalize(uriPath); final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; final IOFile file = new IOFile(path + (suffix ? "" : IO.JARSUFFIX)); if(file.exists()) addURL(file); // try to create Java class instance addJava(uriPath, uri, ii); return true; } /** * Returns a reference to the specified class. * @param clz fully classified class name * @return found class, or {@code null} * @throws Throwable any exception or error: {@link ClassNotFoundException}, * {@link LinkageError} or {@link ExceptionInInitializerError}. */ public Class<?> findClass(final String clz) throws Throwable { // add cached URLs to class loader final int us = urls.size(); if(us != 0) { loader = new JarLoader(urls.toArray(new URL[us]), loader); urls.clear(); } // no external classes added: use default class loader return loader == LOADER ? Reflect.forName(clz) : Class.forName(clz, true, loader); } /** * Returns an instance of the specified Java module class. * @param clz class to be found * @return instance, or {@code null} */ public Object findImport(final String clz) { // check if class was imported as Java module if(javaModules != null) { for(final Object jm : javaModules.keySet()) { if(jm.getClass().getName().equals(clz)) return jm; } } return null; } // STATIC METHODS ===================================================================== /** * <p>Converts a URI to a directory path. The conversion is inspired by Zorba's * URI transformation * (http://www.zorba-xquery.com/html/documentation/2.2.0/zorba/uriresolvers):</p> * <ul> * <li>The URI authority is reversed, and dots are replaced by slashes.</li> * <li>The URI path is appended. If no path exists, a slash is appended.</li> * <li>If the resulting string ends with a slash, "index" is appended.</li> * <li>{@code null} is returned if the URI has an invalid syntax.</li> * </ul> * @param uri namespace uri * @return path, or {@code null} */ public static String uri2path(final String uri) { try { final URI u = new URI(uri); final TokenBuilder tb = new TokenBuilder(); final String auth = u.getAuthority(); if(auth != null) { // reverse authority, replace dots by slashes final String[] comp = auth.split("\\."); for(int c = comp.length - 1; c >= 0; c--) tb.add('/').add(comp[c]); } else { tb.add('/'); } // add remaining path String path = u.getPath(); if(path == null) return null; path = path.replace('.', '/'); // add slash or path tb.add(path.isEmpty() ? "/" : path); String pth = tb.toString(); // add "index" string if(pth.endsWith("/")) pth += "index"; return pth; } catch(final URISyntaxException ex) { Util.debug(ex); return null; } } /** * Capitalizes the last path segment. * @param path input path * @return capitalized path */ public static String capitalize(final String path) { final int i = path.lastIndexOf('/'); return i == -1 || i + 1 >= path.length() ? path : path.substring(0, i + 1) + Character.toUpperCase(path.charAt(i + 1)) + path.substring(i + 2); } // PRIVATE METHODS ==================================================================== /** * Parses the specified file as module if it exists. * @param file file to be added * @param uri namespace uri * @param qp query parser * @return {@code true} if file exists and was successfully parsed * @throws QueryException query exception */ private boolean addModule(final IOFile file, final byte[] uri, final QueryParser qp) throws QueryException { if(!file.exists()) return false; qp.module(token(file.path()), uri); return true; } /** * Loads a Java class. * @param path file path * @param uri original URI * @param ii input info * @throws QueryException query exception */ private void addJava(final String path, final byte[] uri, final InputInfo ii) throws QueryException { final String cp = path.replace('/', '.').substring(1); Class<?> clz = null; try { clz = findClass(cp); } catch(final ClassNotFoundException ex) { NOMODULE.thrw(ii, uri); // expected exception } catch(final Throwable th) { Util.debug(th); MODINIT.thrw(ii, th); } final boolean qm = clz.getSuperclass() == QueryModule.class; final Object jm = Reflect.get(clz); if(jm == null) NOINST.thrw(ii, cp); // add all public methods of the class (ignore methods from super classes) final ArrayList<Method> list = new ArrayList<Method>(); for(final Method m : clz.getMethods()) { // if class is inherited from {@link QueryModule}, no super methods are accepted if(!qm || m.getDeclaringClass() == clz) list.add(m); } // add class and its methods to module cache if(javaModules == null) javaModules = new HashMap<Object, ArrayList<Method>>(); javaModules.put(jm, list); } /** * Adds a package from the package repository. * @param name package name * @param toLoad list with packages to be loaded * @param loaded already loaded packages * @param ii input info * @param qp query parser * @throws QueryException query exception */ private void addRepo(final byte[] name, final TokenSet toLoad, final TokenSet loaded, final InputInfo ii, final QueryParser qp) throws QueryException { // return if package is already loaded if(loaded.contains(name)) return; // find package in package dictionary final byte[] pDir = context.repo.pkgDict().get(name); if(pDir == null) BXRE_NOTINST.thrw(ii, name); final IOFile pkgDir = context.repo.path(string(pDir)); // parse package descriptor final IO pkgDesc = new IOFile(pkgDir, PkgText.DESCRIPTOR); if(!pkgDesc.exists()) Util.debug(PkgText.MISSDESC, string(name)); final Package pkg = new PkgParser(context.repo, ii).parse(pkgDesc); // check if package contains a jar descriptor final IOFile jarDesc = new IOFile(pkgDir, PkgText.JARDESC); // add jars to classpath if(jarDesc.exists()) addJar(jarDesc, pkgDir, string(pkg.abbrev), ii); // package has dependencies -> they have to be loaded first => put package // in list with packages to be loaded if(pkg.dep.size() != 0) toLoad.add(name); for(final Dependency d : pkg.dep) { if(d.pkg != null) { // we consider only package dependencies here final byte[] depPkg = new PkgValidator(context.repo, ii).depPkg(d); if(depPkg == null) { BXRE_NOTINST.thrw(ii, string(d.pkg)); } else { if(toLoad.contains(depPkg)) CIRCMODULE.thrw(ii); addRepo(depPkg, toLoad, loaded, ii, qp); } } } for(final Component comp : pkg.comps) { final String p = new IOFile(new IOFile(pkgDir, string(pkg.abbrev)), string(comp.file)).path(); qp.module(token(p), comp.uri); } if(toLoad.id(name) != 0) toLoad.delete(name); loaded.add(name); } /** * Adds the jar files registered in jarDesc. * @param jarDesc jar descriptor * @param pkgDir package directory * @param modDir module directory * @param ii input info * @throws QueryException query exception */ private void addJar(final IOFile jarDesc, final IOFile pkgDir, final String modDir, final InputInfo ii) throws QueryException { // add new URLs final JarDesc desc = new JarParser(context, ii).parse(jarDesc); for(final byte[] u : desc.jars) { addURL(new IOFile(new IOFile(pkgDir, modDir), string(u))); } } /** * Adds a URL to the cache. * @param jar jar file to be added */ private void addURL(final IOFile jar) { try { urls.add(new URL(jar.url())); } catch(final MalformedURLException ex) { Util.errln(ex.getMessage()); } } }
true
true
public boolean addImport(final byte[] uri, final InputInfo ii, final QueryParser qp) throws QueryException { // add EXPath package final TokenSet pkgs = context.repo.nsDict().get(uri); if(pkgs != null) { Version ver = null; byte[] nm = null; for(final byte[] name : pkgs) { final Version v = new Version(Package.version(name)); if(ver == null || v.compareTo(ver) > 0) { ver = v; nm = name; } } if(nm != null) { addRepo(nm, new TokenSet(), new TokenSet(), ii, qp); return true; } } // search module in repository: rewrite URI to file path final boolean java = startsWith(uri, JAVAPREF); String uriPath = uri2path(string(java ? substring(uri, JAVAPREF.length) : uri)); if(uriPath == null) return false; final boolean suffix = IO.suffix(uriPath).isEmpty(); if(!java) { // no "java:" prefix: first try to import module as XQuery final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; if(suffix) { // check if file has XQuery suffix final IOFile f = new IOFile(path); if(f.hasSuffix(IO.XQSUFFIXES)) return addModule(f, uri, qp); } else { // check for any file with XQuery suffix for(final String suf : IO.XQSUFFIXES) { if(addModule(new IOFile(path + suf), uri, qp)) return true; } } } // "java:" prefix, or no XQuery package found: try to load Java module uriPath = capitalize(uriPath); final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; final IOFile file = new IOFile(path + (suffix ? "" : IO.JARSUFFIX)); if(file.exists()) addURL(file); // try to create Java class instance addJava(uriPath, uri, ii); return true; }
public boolean addImport(final byte[] uri, final InputInfo ii, final QueryParser qp) throws QueryException { // add EXPath package final TokenSet pkgs = context.repo.nsDict().get(uri); if(pkgs != null) { Version ver = null; byte[] nm = null; for(final byte[] name : pkgs) { final Version v = new Version(Package.version(name)); if(ver == null || v.compareTo(ver) > 0) { ver = v; nm = name; } } if(nm != null) { addRepo(nm, new TokenSet(), new TokenSet(), ii, qp); return true; } } // search module in repository: rewrite URI to file path final boolean java = startsWith(uri, JAVAPREF); String uriPath = uri2path(string(java ? substring(uri, JAVAPREF.length) : uri)); if(uriPath == null) return false; final boolean suffix = !IO.suffix(uriPath).isEmpty(); if(!java) { // no "java:" prefix: first try to import module as XQuery final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; if(suffix) { // check if file has XQuery suffix final IOFile f = new IOFile(path); if(f.hasSuffix(IO.XQSUFFIXES)) return addModule(f, uri, qp); } else { // check for any file with XQuery suffix for(final String suf : IO.XQSUFFIXES) { if(addModule(new IOFile(path + suf), uri, qp)) return true; } } } // "java:" prefix, or no XQuery package found: try to load Java module uriPath = capitalize(uriPath); final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; final IOFile file = new IOFile(path + (suffix ? "" : IO.JARSUFFIX)); if(file.exists()) addURL(file); // try to create Java class instance addJava(uriPath, uri, ii); return true; }
diff --git a/src/lib/com/izforge/izpack/util/MultiLineLabel.java b/src/lib/com/izforge/izpack/util/MultiLineLabel.java index 42fcdf40..c56cde6e 100644 --- a/src/lib/com/izforge/izpack/util/MultiLineLabel.java +++ b/src/lib/com/izforge/izpack/util/MultiLineLabel.java @@ -1,645 +1,645 @@ /* * $Id$ * IzPack version * Copyright (C) 1997 - 2002 Elmar Grom * * File : MultiLineLabel.java * Description : A swing component to display static text that spans * multiple lines. * Author's email : [email protected] * Author's Website : http://www.izforge.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.izforge.izpack.util; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.util.Vector; import javax.swing.JComponent; /*---------------------------------------------------------------------------*/ /** * <BR> * <code>MultiLineLabel</code> may be used in place of javax.swing.JLabel. * <BR> <BR> * This class implements a component that is capable of displaying multiple * lines of text. Line breaks are inserted automatically whenever a line of * text extends beyond the predefined maximum line length. Line breaks will * only be inserted between words, except where a single word is longer than * the maximum line length. Line breaks may be forced at any location in the * text by inserting a newline (\n). White space that is not valuable (i.e. is * placed at the beginning of a new line or at the very beginning or end of * the text) is removed. * <br><br> * <b>Note:</b> you can set the maximum width of the label either through one * of the constructors or you can call <code>setMaxWidth()</code> explicitly. * If this is not set, <code>MultiLineLabel</code> will derive its width from * the parent component. * * @version 0.0.1 / 05-15-97 * @version 1.0 / 04-13-02 * @author Elmar Grom */ /*---------------------------------------------------------------------------* * Reviving some old code here that was written before there was swing. * The original was written to work with awt. I had to do some masaging to * make it a JComponent and I hope it behaves like a reasonably good mannered * swing component. *---------------------------------------------------------------------------*/ public class MultiLineLabel extends JComponent { public static final int LEFT = 0; // alignment constants public static final int CENTER = 1; public static final int RIGHT = 2; public static final int DEFAULT_MARGIN = 10; public static final int DEFAULT_ALIGN = LEFT; public static final int LEAST_ALLOWED = 200; // default setting for maxAllowed private static final int FOUND = 0; // constants for string search. private static final int NOT_FOUND = 1; private static final int NOT_DONE = 0; private static final int DONE = 1; private static final char [] WHITE_SPACE = {' ','\n','\t'}; private static final char [] SPACES = {' ','\t'}; private static final char NEW_LINE = '\n'; protected Vector line = new Vector ();// text lines to display protected String labelText; // text lines to display protected int numLines; // the number of lines protected int marginHeight; // top and bottom margins protected int marginWidth; // left and right margins protected int lineHeight; // total height of the font protected int lineAscent; // font height above the baseline protected int lineDescent; // font hight below the baseline protected int [] lineWidth; // width of each line protected int maxWidth; // width of the widest line private int maxAllowed = LEAST_ALLOWED; // max width allowed to use private boolean maxAllowedSet = false; // signals if the max allowed width has been explicitly set protected int alignment = LEFT; // default text alignment /*-------------------------------------------------------------------*/ /** * Constructor * * @param text the text to be displayed * @param horMargin the horizontal margin for the label * @param vertMargin the vertical margin for the label * @param maxWidth the maximum allowed width of the text * @param justify the text alignment for the label */ /*-------------------------------------------------------------------* * <detailed description / implementation details if applicable> *-------------------------------------------------------------------*/ public MultiLineLabel (String text, int horMargin, int vertMargin, int maxWidth, int justify) { this.labelText = text; this.marginWidth = horMargin; this.marginHeight = vertMargin; this.maxAllowed = maxWidth; this.maxAllowedSet = true; this.alignment = justify; } /*-------------------------------------------------------------------*/ /** * Constructor using default max-width and alignment. * * @param label the text to be displayed * @param marginWidth the horizontal margin for the label * @param marginHeight the vertical margin for the label */ /*-------------------------------------------------------------------* * <detailed description / implementation details if applicable> *-------------------------------------------------------------------*/ public MultiLineLabel (String label, int marginWidth, int marginHeight) { this.labelText = label; this.marginWidth = marginWidth; this.marginHeight = marginHeight; } /*-------------------------------------------------------------------*/ /** * Constructor using default max-width, and margin. * * @param label the text to be displayed * @param alignment the text alignment for the label */ /*-------------------------------------------------------------------* * <detailed description / implementation details if applicable> *-------------------------------------------------------------------*/ public MultiLineLabel (String label, int alignment) { this.labelText = label; this.alignment = alignment; } /*-------------------------------------------------------------------*/ /** * Constructor using default max-width, alignment, * and margin. * * @param label the text to be displayed */ /*-------------------------------------------------------------------* * <detailed description / implementation details if applicable> *-------------------------------------------------------------------*/ public MultiLineLabel (String label) { this.labelText = label; } /*-------------------------------------------------------------------*/ /** * This method searches the target string for occurences of any of the * characters in the source string. The return value is the position of the * first hit. Based on the mode parameter the hit position is either the * position where any of the source characters first was found or the first * position where none of the source characters where found. * * * @return position of the first occurence * @param target the text to be searched * @param start the start position for the search * @param source the list of characters to be searched for * @param mode the search mode * FOUND = reports first found * NOT_FOUND = reports first not found */ /*-------------------------------------------------------------------* * <detailed description / implementation details if applicable> *-------------------------------------------------------------------*/ int getPosition (String target, int start, char [] source, int mode) { int status; int position; int scan; int targetEnd; int sourceLength; char temp; targetEnd = (target.length () - 1); sourceLength = source.length; position = start; if (mode == FOUND) { status = NOT_DONE; while (status != DONE) { position++; if (!(position < targetEnd)) // end of string reached, the next { // statement would cause a runtime error return (targetEnd); } temp = target.charAt (position); for (scan = 0; scan < sourceLength; scan++) // walk through the source { // string and compare each char if (source [scan] == temp) { status = DONE; } } } return (position); } else if (mode == NOT_FOUND) { status = NOT_DONE; while (status != DONE) { position++; if (!(position < targetEnd)) // end of string reached, the next { // statement would cause a runtime error return (targetEnd); } temp = target.charAt (position); status = DONE; for (scan = 0; scan < sourceLength; scan++) // walk through the source { // string and compare each char if (source [scan] == temp) { status = NOT_DONE; } } } return (position); } return (0); } /*-------------------------------------------------------------------*/ /** * This method scans the input string until the max allowed width is reached. * The return value indicates the position just before this happens. * * * @return position character position just before the string is too long * @param word word to break */ /*-------------------------------------------------------------------* * <detailed description / implementation details if applicable> *-------------------------------------------------------------------*/ int breakWord (String word, FontMetrics fm) { int width; int currentPos; int endPos; width = 0; currentPos = 0; endPos = word.length () - 1; // make sure we don't end up with a negative position if (endPos <= 0) { return (currentPos); } // seek the position where the word first is longer than allowed while ((width < maxAllowed) && (currentPos < endPos) ) { currentPos++; width = fm.stringWidth (labelText.substring (0, currentPos)); } // adjust to get the chatacter just before (this should make it a bit // shorter than allowed!) if (currentPos != endPos) { currentPos--; } return (currentPos); } /*-------------------------------------------------------------------*/ /** * This method breaks the label text up into multiple lines of text. * Line breaks are established based on the maximum available space. * A new line is started whenever a line break is encountered, even * if the permissible length is not yet reached. Words are broken * only if a single word happens to be longer than one line. */ /*-------------------------------------------------------------------*/ private void divideLabel () { int width; int startPos; int currentPos; int lastPos; int endPos; line.clear (); FontMetrics fm = this.getFontMetrics (this.getFont ()); startPos = 0; currentPos = startPos; lastPos = currentPos; endPos = (labelText.length () - 1); while (currentPos < endPos) { width = 0; // ---------------------------------------------------------------- // find the first substring that occupies more than the granted space. // Break at the end of the string or a line break // ---------------------------------------------------------------- while ( (width < maxAllowed) && (currentPos < endPos) && (labelText.charAt (currentPos) != NEW_LINE)) { lastPos = currentPos; currentPos = getPosition (labelText, currentPos, WHITE_SPACE, FOUND); width = fm.stringWidth (labelText.substring (startPos, currentPos)); } // ---------------------------------------------------------------- // if we have a line break we want to copy everything up to currentPos // ---------------------------------------------------------------- if (labelText.charAt (currentPos) == NEW_LINE) { lastPos = currentPos; } // ---------------------------------------------------------------- // if we are at the end of the string we want to copy everything up to // the last character. Since there seems to be a problem to get the last // character if the substring definition ends at the very last character // we have to call a different substring function than normal. // ---------------------------------------------------------------- - if (currentPos == endPos) + if (currentPos == endPos && width <= maxAllowed) { lastPos = currentPos; String s = labelText.substring (startPos); line.addElement (s); } // ---------------------------------------------------------------- // in all other cases copy the substring that we have found to fit and // add it as a new line of text to the line vector. // ---------------------------------------------------------------- else { // ------------------------------------------------------------ // make sure it's not a single word. If so we must break it at the // proper location. // ------------------------------------------------------------ if (lastPos == startPos) { lastPos = startPos + breakWord (labelText.substring (startPos, currentPos), fm); } String s = labelText.substring (startPos, lastPos); line.addElement (s); } // ---------------------------------------------------------------- // seek for the end of the white space to cut out any unnecessary spaces // and tabs and set the new start condition. // ---------------------------------------------------------------- startPos = getPosition (labelText, lastPos, SPACES, NOT_FOUND); currentPos = startPos; } numLines = line.size (); lineWidth = new int [numLines]; } /*-------------------------------------------------------------------*/ /** * This method finds the font size, each line width and the widest line. * */ /*-------------------------------------------------------------------*/ protected void measure () { if (!maxAllowedSet) { maxAllowed = getParent ().getSize ().width; } // return if width is too small if (maxAllowed < (20)) { return; } FontMetrics fm = this.getFontMetrics (this.getFont ()); // return if no font metrics available if (fm == null) { return; } divideLabel (); this.lineHeight = fm.getHeight (); this.lineDescent = fm.getDescent (); this.maxWidth = 0; for (int i = 0; i < numLines; i++) { this.lineWidth[i] = fm.stringWidth ((String)this.line.elementAt (i)); if (this.lineWidth[i] > this.maxWidth) { this.maxWidth = this.lineWidth[i]; } } } /*-------------------------------------------------------------------*/ /** * This method draws the label. * * @param graphics the device context */ /*-------------------------------------------------------------------*/ public void paint (Graphics graphics) { int x; int y; measure (); Dimension d = this.getSize (); y = lineAscent + (d.height - (numLines * lineHeight)) / 2; for (int i = 0; i < numLines; i++) { y += lineHeight; switch (alignment) { case LEFT : x = marginWidth; break; case CENTER : x = (d.width - lineWidth[i]) / 2; break; case RIGHT : x = d.width - marginWidth - lineWidth[i]; break; default : x = (d.width - lineWidth[i]) / 2; } graphics.drawString ((String)line.elementAt (i), x, y); } } /*-------------------------------------------------------------------*/ /** * This method may be used to set the label text * * @param labelText the text to be displayed */ /*-------------------------------------------------------------------*/ public void setText (String labelText) { this.labelText = labelText; repaint (); } /*-------------------------------------------------------------------*/ /** * This method may be used to set the font that should be used to draw the * label * * @param font font to be used within the label */ /*-------------------------------------------------------------------*/ public void setFont (Font font) { super.setFont (font); repaint (); } /*-------------------------------------------------------------------*/ /** * This method may be used to set the color in which the text should be drawn * * @param color the text color */ /*-------------------------------------------------------------------*/ public void setColor (Color color) { super.setForeground (color); repaint (); } /*-------------------------------------------------------------------*/ /** * This method may be used to set the text alignment for the label * * @param alignment the alignment, possible values are LEFT, CENTER, RIGHT */ /*-------------------------------------------------------------------*/ public void setJustify (int alignment) { this.alignment = alignment; repaint (); } /*-------------------------------------------------------------------*/ /** * This method may be used to set the max allowed line width * * @param width the max allowed line width in pixels */ /*-------------------------------------------------------------------*/ public void setMaxWidth (int width) { this.maxAllowed = width; this.maxAllowedSet = true; repaint (); } /*-------------------------------------------------------------------*/ /** * This method may be used to set the horizontal margin * * @param margin the margin to the left and to the right of the label */ /*-------------------------------------------------------------------*/ public void setMarginWidth (int margin) { this.marginWidth = margin; repaint (); } /*-------------------------------------------------------------------*/ /** * This method may be used to set the vertical margin for the label * * @param margin the margin on the top and bottom of the label */ /*-------------------------------------------------------------------*/ public void setMarginHeight (int margin) { this.marginHeight = margin; repaint (); } /*-------------------------------------------------------------------*/ /** * Moves and resizes this component. The new location of the top-left * corner is specified by <code>x</code> and <code>y</code>, and the * new size is specified by <code>width</code> and <code>height</code>. * * @param x The new x-coordinate of this component. * @param y The new y-coordinate of this component. * @param width The new width of this component. * @param height The new height of this component. */ /*-------------------------------------------------------------------*/ public void setBounds (int x, int y, int width, int height) { super.setBounds (x, y, width, height); this.maxAllowed = width; this.maxAllowedSet = true; } /*-------------------------------------------------------------------*/ /** * This method may be used to retrieve the text alignment for the label * * @return alignment the text alignment currently in use for the label */ /*-------------------------------------------------------------------*/ public int getAlignment () { return (this.alignment); } /*-------------------------------------------------------------------*/ /** * This method may be used to retrieve the horizontal margin for the label * * @return marginWidth the margin currently in use to the left and right of * the label */ /*-------------------------------------------------------------------*/ public int getMarginWidth () { return (this.marginWidth); } /*-------------------------------------------------------------------*/ /** * This method may be used to retrieve the vertical margin for the label * * @return marginHeight the margin currently in use on the top and bottom of * the label */ /*-------------------------------------------------------------------*/ public int getMarginHeight () { return (this.marginHeight); } /*-------------------------------------------------------------------*/ /** * This method is typically used by the layout manager, it reports the * necessary space to display the label comfortably. */ /*-------------------------------------------------------------------*/ public Dimension getPreferredSize () { measure (); return (new Dimension (maxAllowed, (numLines * (lineHeight + lineAscent + lineDescent)) + (2 * marginHeight))); } /*-------------------------------------------------------------------*/ /** * This method is typically used by the layout manager, it reports the * absolute minimum space required to display the entire label. * */ /*-------------------------------------------------------------------*/ public Dimension getMinimumSize () { measure (); return (new Dimension (maxAllowed, (numLines * (lineHeight + lineAscent + lineDescent)) + (2 * marginHeight))); } /*-------------------------------------------------------------------*/ /** * This method is called by the system after this object is first created. * */ /*-------------------------------------------------------------------*/ public void addNotify () { super.addNotify (); // invoke the superclass } } /*---------------------------------------------------------------------------*/
true
true
private void divideLabel () { int width; int startPos; int currentPos; int lastPos; int endPos; line.clear (); FontMetrics fm = this.getFontMetrics (this.getFont ()); startPos = 0; currentPos = startPos; lastPos = currentPos; endPos = (labelText.length () - 1); while (currentPos < endPos) { width = 0; // ---------------------------------------------------------------- // find the first substring that occupies more than the granted space. // Break at the end of the string or a line break // ---------------------------------------------------------------- while ( (width < maxAllowed) && (currentPos < endPos) && (labelText.charAt (currentPos) != NEW_LINE)) { lastPos = currentPos; currentPos = getPosition (labelText, currentPos, WHITE_SPACE, FOUND); width = fm.stringWidth (labelText.substring (startPos, currentPos)); } // ---------------------------------------------------------------- // if we have a line break we want to copy everything up to currentPos // ---------------------------------------------------------------- if (labelText.charAt (currentPos) == NEW_LINE) { lastPos = currentPos; } // ---------------------------------------------------------------- // if we are at the end of the string we want to copy everything up to // the last character. Since there seems to be a problem to get the last // character if the substring definition ends at the very last character // we have to call a different substring function than normal. // ---------------------------------------------------------------- if (currentPos == endPos) { lastPos = currentPos; String s = labelText.substring (startPos); line.addElement (s); } // ---------------------------------------------------------------- // in all other cases copy the substring that we have found to fit and // add it as a new line of text to the line vector. // ---------------------------------------------------------------- else { // ------------------------------------------------------------ // make sure it's not a single word. If so we must break it at the // proper location. // ------------------------------------------------------------ if (lastPos == startPos) { lastPos = startPos + breakWord (labelText.substring (startPos, currentPos), fm); } String s = labelText.substring (startPos, lastPos); line.addElement (s); } // ---------------------------------------------------------------- // seek for the end of the white space to cut out any unnecessary spaces // and tabs and set the new start condition. // ---------------------------------------------------------------- startPos = getPosition (labelText, lastPos, SPACES, NOT_FOUND); currentPos = startPos; } numLines = line.size (); lineWidth = new int [numLines]; }
private void divideLabel () { int width; int startPos; int currentPos; int lastPos; int endPos; line.clear (); FontMetrics fm = this.getFontMetrics (this.getFont ()); startPos = 0; currentPos = startPos; lastPos = currentPos; endPos = (labelText.length () - 1); while (currentPos < endPos) { width = 0; // ---------------------------------------------------------------- // find the first substring that occupies more than the granted space. // Break at the end of the string or a line break // ---------------------------------------------------------------- while ( (width < maxAllowed) && (currentPos < endPos) && (labelText.charAt (currentPos) != NEW_LINE)) { lastPos = currentPos; currentPos = getPosition (labelText, currentPos, WHITE_SPACE, FOUND); width = fm.stringWidth (labelText.substring (startPos, currentPos)); } // ---------------------------------------------------------------- // if we have a line break we want to copy everything up to currentPos // ---------------------------------------------------------------- if (labelText.charAt (currentPos) == NEW_LINE) { lastPos = currentPos; } // ---------------------------------------------------------------- // if we are at the end of the string we want to copy everything up to // the last character. Since there seems to be a problem to get the last // character if the substring definition ends at the very last character // we have to call a different substring function than normal. // ---------------------------------------------------------------- if (currentPos == endPos && width <= maxAllowed) { lastPos = currentPos; String s = labelText.substring (startPos); line.addElement (s); } // ---------------------------------------------------------------- // in all other cases copy the substring that we have found to fit and // add it as a new line of text to the line vector. // ---------------------------------------------------------------- else { // ------------------------------------------------------------ // make sure it's not a single word. If so we must break it at the // proper location. // ------------------------------------------------------------ if (lastPos == startPos) { lastPos = startPos + breakWord (labelText.substring (startPos, currentPos), fm); } String s = labelText.substring (startPos, lastPos); line.addElement (s); } // ---------------------------------------------------------------- // seek for the end of the white space to cut out any unnecessary spaces // and tabs and set the new start condition. // ---------------------------------------------------------------- startPos = getPosition (labelText, lastPos, SPACES, NOT_FOUND); currentPos = startPos; } numLines = line.size (); lineWidth = new int [numLines]; }
diff --git a/src/edu/msu/egit/training/Nick.java b/src/edu/msu/egit/training/Nick.java index 9b83538..c5ce8b8 100644 --- a/src/edu/msu/egit/training/Nick.java +++ b/src/edu/msu/egit/training/Nick.java @@ -1,8 +1,8 @@ package edu.msu.egit.training; public class Nick { public static void main(String[] args){ - System.out.println("Hey Doctor Nick!"); + System.out.println("Hey Doctor Nick!"); System.out.println("There is no java, only Zuul!"); } }
true
true
public static void main(String[] args){ System.out.println("Hey Doctor Nick!"); System.out.println("There is no java, only Zuul!"); }
public static void main(String[] args){ System.out.println("Hey Doctor Nick!"); System.out.println("There is no java, only Zuul!"); }
diff --git a/src/fi/helsinki/cs/tmc/actions/SubmitExerciseAction.java b/src/fi/helsinki/cs/tmc/actions/SubmitExerciseAction.java index 841076c..87988c6 100644 --- a/src/fi/helsinki/cs/tmc/actions/SubmitExerciseAction.java +++ b/src/fi/helsinki/cs/tmc/actions/SubmitExerciseAction.java @@ -1,174 +1,175 @@ package fi.helsinki.cs.tmc.actions; import fi.helsinki.cs.tmc.data.Exercise; import fi.helsinki.cs.tmc.data.SubmissionResult; import fi.helsinki.cs.tmc.model.CourseDb; import fi.helsinki.cs.tmc.model.ProjectMediator; import fi.helsinki.cs.tmc.model.ServerAccess; import fi.helsinki.cs.tmc.model.SubmissionResultWaiter; import fi.helsinki.cs.tmc.model.TmcProjectInfo; import fi.helsinki.cs.tmc.ui.TestResultDisplayer; import fi.helsinki.cs.tmc.utilities.BgTaskListener; import fi.helsinki.cs.tmc.ui.ConvenientDialogDisplayer; import fi.helsinki.cs.tmc.utilities.BgTask; import fi.helsinki.cs.tmc.utilities.CancellableCallable; import fi.helsinki.cs.tmc.utilities.CancellableRunnable; import fi.helsinki.cs.tmc.utilities.zip.NbProjectZipper; import java.net.URI; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import org.netbeans.api.progress.ProgressUtils; import org.netbeans.api.project.Project; import org.openide.filesystems.FileUtil; import org.openide.nodes.Node; import org.openide.util.NbBundle.Messages; // The action annotations don't work properly with NodeAction (NB 7.0) // so this action is declared manually in layer.xml. @Messages("CTL_SubmitExerciseAction=Su&bmit") public final class SubmitExerciseAction extends AbstractTmcRunAction { private static final Logger log = Logger.getLogger(SubmitExerciseAction.class.getName()); private ServerAccess serverAccess; private CourseDb courseDb; private NbProjectZipper zipper; private ProjectMediator projectMediator; private TestResultDisplayer resultDisplayer; private ConvenientDialogDisplayer dialogDisplayer; public SubmitExerciseAction() { this.serverAccess = new ServerAccess(); this.courseDb = CourseDb.getInstance(); this.zipper = NbProjectZipper.getDefault(); this.projectMediator = ProjectMediator.getInstance(); this.resultDisplayer = TestResultDisplayer.getInstance(); this.dialogDisplayer = ConvenientDialogDisplayer.getDefault(); putValue("noIconInMenu", Boolean.TRUE); } @Override protected CourseDb getCourseDb() { return courseDb; } @Override protected ProjectMediator getProjectMediator() { return projectMediator; } @Override protected void performAction(Node[] nodes) { performAction(projectsFromNodes(nodes).toArray(new Project[0])); } /*package (for tests)*/ void performAction(Project ... projects) { for (Project nbProject : projects) { TmcProjectInfo tmcProject = projectMediator.wrapProject(nbProject); submitProject(tmcProject); } } private void submitProject(final TmcProjectInfo project) { final Exercise exercise = projectMediator.tryGetExerciseForProject(project, courseDb); if (exercise == null || !exercise.isReturnable()) { return; } projectMediator.saveAllFiles(); // Oh what a mess :/ final BgTaskListener<URI> uriListener = new BgTaskListener<URI>() { @Override public void bgTaskReady(URI submissionUri) { final ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Waiting for results from server."); final SubmissionResultWaiter waiter = new SubmissionResultWaiter(submissionUri, progressHandle); ProgressUtils.showProgressDialogAndRun(new CancellableRunnable() { @Override public void run() { try { progressHandle.switchToIndeterminate(); final SubmissionResult result = waiter.call(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { resultDisplayer.showSubmissionResult(result); exercise.setAttempted(true); if (result.getStatus() == SubmissionResult.Status.OK) { exercise.setCompleted(true); } courseDb.save(); } }); } catch (InterruptedException ex) { } catch (TimeoutException ex) { log.log(Level.INFO, "Timeout waiting for results from server.", ex); dialogDisplayer.displayError("This is taking too long.\nPlease try again in a few minutes or ask someone to look into the problem."); } catch (Exception ex) { log.log(Level.INFO, "Error waiting for results from server.", ex); + dialogDisplayer.displayError("Error trying to get test results.", ex); } } @Override public boolean cancel() { return waiter.cancel(); } }, progressHandle, true); } @Override public void bgTaskCancelled() { } @Override public void bgTaskFailed(Throwable ex) { log.log(Level.INFO, "Error submitting exercise.", ex); dialogDisplayer.displayError("Error submitting exercise.", ex); } }; BgTask.start("Zipping up " + exercise.getName(), new Callable<byte[]>() { @Override public byte[] call() throws Exception { return zipper.zipProjectSources(FileUtil.toFile(project.getProjectDir())); } }, new BgTaskListener<byte[]>() { @Override public void bgTaskReady(byte[] zipData) { CancellableCallable<URI> task = serverAccess.getSubmittingExerciseTask(exercise, zipData); BgTask.start("Sending " + exercise.getName(), task, uriListener); } @Override public void bgTaskCancelled() { uriListener.bgTaskCancelled(); } @Override public void bgTaskFailed(Throwable ex) { uriListener.bgTaskFailed(ex); } }); } @Override public String getName() { return "Su&bmit"; } @Override protected String iconResource() { // The setting in layer.xml doesn't work with NodeAction return "fi/helsinki/cs/tmc/actions/submit.png"; } }
true
true
private void submitProject(final TmcProjectInfo project) { final Exercise exercise = projectMediator.tryGetExerciseForProject(project, courseDb); if (exercise == null || !exercise.isReturnable()) { return; } projectMediator.saveAllFiles(); // Oh what a mess :/ final BgTaskListener<URI> uriListener = new BgTaskListener<URI>() { @Override public void bgTaskReady(URI submissionUri) { final ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Waiting for results from server."); final SubmissionResultWaiter waiter = new SubmissionResultWaiter(submissionUri, progressHandle); ProgressUtils.showProgressDialogAndRun(new CancellableRunnable() { @Override public void run() { try { progressHandle.switchToIndeterminate(); final SubmissionResult result = waiter.call(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { resultDisplayer.showSubmissionResult(result); exercise.setAttempted(true); if (result.getStatus() == SubmissionResult.Status.OK) { exercise.setCompleted(true); } courseDb.save(); } }); } catch (InterruptedException ex) { } catch (TimeoutException ex) { log.log(Level.INFO, "Timeout waiting for results from server.", ex); dialogDisplayer.displayError("This is taking too long.\nPlease try again in a few minutes or ask someone to look into the problem."); } catch (Exception ex) { log.log(Level.INFO, "Error waiting for results from server.", ex); } } @Override public boolean cancel() { return waiter.cancel(); } }, progressHandle, true); } @Override public void bgTaskCancelled() { } @Override public void bgTaskFailed(Throwable ex) { log.log(Level.INFO, "Error submitting exercise.", ex); dialogDisplayer.displayError("Error submitting exercise.", ex); } }; BgTask.start("Zipping up " + exercise.getName(), new Callable<byte[]>() { @Override public byte[] call() throws Exception { return zipper.zipProjectSources(FileUtil.toFile(project.getProjectDir())); } }, new BgTaskListener<byte[]>() { @Override public void bgTaskReady(byte[] zipData) { CancellableCallable<URI> task = serverAccess.getSubmittingExerciseTask(exercise, zipData); BgTask.start("Sending " + exercise.getName(), task, uriListener); } @Override public void bgTaskCancelled() { uriListener.bgTaskCancelled(); } @Override public void bgTaskFailed(Throwable ex) { uriListener.bgTaskFailed(ex); } }); }
private void submitProject(final TmcProjectInfo project) { final Exercise exercise = projectMediator.tryGetExerciseForProject(project, courseDb); if (exercise == null || !exercise.isReturnable()) { return; } projectMediator.saveAllFiles(); // Oh what a mess :/ final BgTaskListener<URI> uriListener = new BgTaskListener<URI>() { @Override public void bgTaskReady(URI submissionUri) { final ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Waiting for results from server."); final SubmissionResultWaiter waiter = new SubmissionResultWaiter(submissionUri, progressHandle); ProgressUtils.showProgressDialogAndRun(new CancellableRunnable() { @Override public void run() { try { progressHandle.switchToIndeterminate(); final SubmissionResult result = waiter.call(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { resultDisplayer.showSubmissionResult(result); exercise.setAttempted(true); if (result.getStatus() == SubmissionResult.Status.OK) { exercise.setCompleted(true); } courseDb.save(); } }); } catch (InterruptedException ex) { } catch (TimeoutException ex) { log.log(Level.INFO, "Timeout waiting for results from server.", ex); dialogDisplayer.displayError("This is taking too long.\nPlease try again in a few minutes or ask someone to look into the problem."); } catch (Exception ex) { log.log(Level.INFO, "Error waiting for results from server.", ex); dialogDisplayer.displayError("Error trying to get test results.", ex); } } @Override public boolean cancel() { return waiter.cancel(); } }, progressHandle, true); } @Override public void bgTaskCancelled() { } @Override public void bgTaskFailed(Throwable ex) { log.log(Level.INFO, "Error submitting exercise.", ex); dialogDisplayer.displayError("Error submitting exercise.", ex); } }; BgTask.start("Zipping up " + exercise.getName(), new Callable<byte[]>() { @Override public byte[] call() throws Exception { return zipper.zipProjectSources(FileUtil.toFile(project.getProjectDir())); } }, new BgTaskListener<byte[]>() { @Override public void bgTaskReady(byte[] zipData) { CancellableCallable<URI> task = serverAccess.getSubmittingExerciseTask(exercise, zipData); BgTask.start("Sending " + exercise.getName(), task, uriListener); } @Override public void bgTaskCancelled() { uriListener.bgTaskCancelled(); } @Override public void bgTaskFailed(Throwable ex) { uriListener.bgTaskFailed(ex); } }); }
diff --git a/src/org/iplant/pipeline/client/dnd/DragCreator.java b/src/org/iplant/pipeline/client/dnd/DragCreator.java index 6a06910..02fdc63 100644 --- a/src/org/iplant/pipeline/client/dnd/DragCreator.java +++ b/src/org/iplant/pipeline/client/dnd/DragCreator.java @@ -1,257 +1,257 @@ /* * Copyright 2012 Oregon State University. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package org.iplant.pipeline.client.dnd; import org.iplant.pipeline.client.json.App; import org.iplant.pipeline.client.json.IPCType; import org.iplant.pipeline.client.json.Input; import org.iplant.pipeline.client.json.Output; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Element; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONBoolean; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.google.gwt.user.client.ui.Image; public class DragCreator { private static IPCType draggedRecord; public static final int MOVE = 1; public static final int COPY = 2; public static final int DELETE = 3; public static Element dragImageElement = getNOImageElement(); public static JavaScriptObject dragEvent; public static native void addDrag(Element element, IPCType rec, DragListener listener) /*-{ function handleDragStart(e) { var dragIcon = [email protected]::getDragImage(Lorg/iplant/pipeline/client/json/IPCType;)(rec); e.dataTransfer.setDragImage(dragIcon, -10, -10); //e.dataTransfer.effectAllowed = 'copy'; @org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = rec; [email protected]::dragStart(Lorg/iplant/pipeline/client/json/IPCType;)(rec); e.dataTransfer.effectAllowed = 'all'; if (element.getAttribute("data-downloadurl") != null) { e.dataTransfer.setData("DownloadURL", element.getAttribute("data-downloadurl")); } else { e.dataTransfer.setData('Text',[email protected]::getId()()); // required otherwise doesn't work @org.iplant.pipeline.client.dnd.DragCreator::dragEvent = dragIcon; } } function handleDragOver(e) { if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if(e.preventDefault) e.preventDefault(); var canDrop = [email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec); if (canDrop) e.dataTransfer.dropEffect = 'copy'; else { e.dataTransfer.dropEffect = 'move'; } return false; } function handleDragEnter(e) { if(e.preventDefault) - event.preventDefault(); + e.preventDefault(); // this / e.target is the current hover target. [email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec); return true; } function handleDragLeave(e) { [email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function handleDrop(e) { // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if (e.preventDefault) e.preventDefault(); var data = e.dataTransfer.getData('Text'); if (data && isNaN(data)) { // //item is an json app from iplant var obj = eval("(" + data + ")"); var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj); @org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app; } [email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function handleDragEnd(e) { [email protected]::dragEnd(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } element.addEventListener('dragstart', handleDragStart, false); element.addEventListener('dragenter', handleDragEnter, false); element.addEventListener('dragover', handleDragOver, false); element.addEventListener('dragleave', handleDragLeave, false); element.addEventListener('drop', handleDrop, false); element.addEventListener('dragend', handleDragEnd, false); }-*/; public static native void addDrop(Element element, IPCType rec, DropListener listener) /*-{ function handleDragOver(e) { if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if(e.preventDefault) e.preventDefault(); var canDrop = [email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec); if (canDrop) e.dataTransfer.dropEffect = 'copy'; else { e.dataTransfer.dropEffect = 'move'; } return false; } function handleDragEnter(e) { if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if(e.preventDefault) e.preventDefault(); var canDrop = [email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec); if (canDrop) e.dataTransfer.dropEffect = 'copy'; else { e.dataTransfer.dropEffect = 'move'; } return false; } function handleDragLeave(e) { [email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function handleDrop(e) { // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if (e.preventDefault) e.preventDefault(); var data = e.dataTransfer.getData('Text'); if (isNaN(data)) { // //item is an json app from iplant var obj = eval("(" + data + ")"); var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj); @org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app; } [email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function addEvent(el, type, fn) { if (el && el.nodeName || el === window) { el.addEventListener(type, fn, false); } else if (el && el.length) { for ( var i = 0; i < el.length; i++) { addEvent(el[i], type, fn); } } } // addEvent(element, 'dragenter', handleDragEnter); addEvent(element, 'dragover', handleDragOver); addEvent(element, 'dragleave', handleDragLeave); addEvent(element, 'drop', handleDrop); }-*/; public static IPCType getDragSource() { return draggedRecord; } private static App createApp(String name, String description, String id) { App app = new App(); app.setName(name); app.setDescription(description); app.setId(1); app.setID(id); return app; } private static App createApp(com.google.gwt.core.client.JavaScriptObject json) { return createApp(new JSONObject(json)); } public static App createApp(JSONObject json) { App app = new App(); app.setName(((JSONString) json.get("name")).stringValue()); app.setDescription(((JSONString) json.get("description")).stringValue()); app.setId(1); app.setID(((JSONString) json.get("id")).stringValue()); JSONArray inputs = (JSONArray) json.get("inputs"); app.setInputJson(inputs); for (int i = 0; i < inputs.size(); i++) { Input input = new Input(); JSONObject obj = (JSONObject) inputs.get(i); JSONObject dataObj = (JSONObject) obj.get("data_object"); if (dataObj != null) { input.setName(((JSONString) dataObj.get("name")).stringValue()); input.setDescription(((JSONString) dataObj.get("description")).stringValue()); input.setId(1); input.setRequired(((JSONBoolean) dataObj.get("required")).booleanValue()); input.setType("File:" + ((JSONString) dataObj.get("format")).stringValue()); input.setID(((JSONString) dataObj.get("id")).stringValue()); app.addInput(input); } } JSONArray outputs = (JSONArray) json.get("outputs"); app.setOutputJson(outputs); for (int i = 0; i < outputs.size(); i++) { Output output = new Output(); JSONObject obj = (JSONObject) outputs.get(i); JSONObject dataObj = (JSONObject) obj.get("data_object"); if (dataObj != null) { output.setName(((JSONString) dataObj.get("name")).stringValue()); output.setDescription(((JSONString) dataObj.get("description")).stringValue()); output.setId(1); output.setType(((JSONString) dataObj.get("format")).stringValue()); output.setID(((JSONString) dataObj.get("id")).stringValue()); app.addOutput(output); } } return app; } public static Element getImageElement(String src) { Image img = new Image(src); img.setWidth("20px"); img.setHeight("20px"); return img.getElement(); } public static Element getOKImageElement() { Image img = new Image("/images/add.png"); img.setWidth("20px"); img.setHeight("20px"); return img.getElement(); } public static Element getNOImageElement() { Image img = new Image("/images/down.png"); img.setWidth("20px"); img.setHeight("20px"); return img.getElement(); } }
true
true
public static native void addDrag(Element element, IPCType rec, DragListener listener) /*-{ function handleDragStart(e) { var dragIcon = [email protected]::getDragImage(Lorg/iplant/pipeline/client/json/IPCType;)(rec); e.dataTransfer.setDragImage(dragIcon, -10, -10); //e.dataTransfer.effectAllowed = 'copy'; @org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = rec; [email protected]::dragStart(Lorg/iplant/pipeline/client/json/IPCType;)(rec); e.dataTransfer.effectAllowed = 'all'; if (element.getAttribute("data-downloadurl") != null) { e.dataTransfer.setData("DownloadURL", element.getAttribute("data-downloadurl")); } else { e.dataTransfer.setData('Text',[email protected]::getId()()); // required otherwise doesn't work @org.iplant.pipeline.client.dnd.DragCreator::dragEvent = dragIcon; } } function handleDragOver(e) { if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if(e.preventDefault) e.preventDefault(); var canDrop = [email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec); if (canDrop) e.dataTransfer.dropEffect = 'copy'; else { e.dataTransfer.dropEffect = 'move'; } return false; } function handleDragEnter(e) { if(e.preventDefault) event.preventDefault(); // this / e.target is the current hover target. [email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec); return true; } function handleDragLeave(e) { [email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function handleDrop(e) { // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if (e.preventDefault) e.preventDefault(); var data = e.dataTransfer.getData('Text'); if (data && isNaN(data)) { // //item is an json app from iplant var obj = eval("(" + data + ")"); var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj); @org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app; } [email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function handleDragEnd(e) { [email protected]::dragEnd(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } element.addEventListener('dragstart', handleDragStart, false); element.addEventListener('dragenter', handleDragEnter, false); element.addEventListener('dragover', handleDragOver, false); element.addEventListener('dragleave', handleDragLeave, false); element.addEventListener('drop', handleDrop, false); element.addEventListener('dragend', handleDragEnd, false); }-*/;
public static native void addDrag(Element element, IPCType rec, DragListener listener) /*-{ function handleDragStart(e) { var dragIcon = [email protected]::getDragImage(Lorg/iplant/pipeline/client/json/IPCType;)(rec); e.dataTransfer.setDragImage(dragIcon, -10, -10); //e.dataTransfer.effectAllowed = 'copy'; @org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = rec; [email protected]::dragStart(Lorg/iplant/pipeline/client/json/IPCType;)(rec); e.dataTransfer.effectAllowed = 'all'; if (element.getAttribute("data-downloadurl") != null) { e.dataTransfer.setData("DownloadURL", element.getAttribute("data-downloadurl")); } else { e.dataTransfer.setData('Text',[email protected]::getId()()); // required otherwise doesn't work @org.iplant.pipeline.client.dnd.DragCreator::dragEvent = dragIcon; } } function handleDragOver(e) { if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if(e.preventDefault) e.preventDefault(); var canDrop = [email protected]::dragOver(Lorg/iplant/pipeline/client/json/IPCType;)(rec); if (canDrop) e.dataTransfer.dropEffect = 'copy'; else { e.dataTransfer.dropEffect = 'move'; } return false; } function handleDragEnter(e) { if(e.preventDefault) e.preventDefault(); // this / e.target is the current hover target. [email protected]::dragEnter(Lorg/iplant/pipeline/client/json/IPCType;)(rec); return true; } function handleDragLeave(e) { [email protected]::dragLeave(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function handleDrop(e) { // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if (e.preventDefault) e.preventDefault(); var data = e.dataTransfer.getData('Text'); if (data && isNaN(data)) { // //item is an json app from iplant var obj = eval("(" + data + ")"); var app = @org.iplant.pipeline.client.dnd.DragCreator::createApp(Lcom/google/gwt/core/client/JavaScriptObject;)(obj); @org.iplant.pipeline.client.dnd.DragCreator::draggedRecord = app; } [email protected]::drop(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } function handleDragEnd(e) { [email protected]::dragEnd(Lorg/iplant/pipeline/client/json/IPCType;)(rec); } element.addEventListener('dragstart', handleDragStart, false); element.addEventListener('dragenter', handleDragEnter, false); element.addEventListener('dragover', handleDragOver, false); element.addEventListener('dragleave', handleDragLeave, false); element.addEventListener('drop', handleDrop, false); element.addEventListener('dragend', handleDragEnd, false); }-*/;
diff --git a/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/DocumentLayoutTagHandler.java b/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/DocumentLayoutTagHandler.java index 02769021..6f1847b4 100644 --- a/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/DocumentLayoutTagHandler.java +++ b/nuxeo-platform-forms-layout-client/src/main/java/org/nuxeo/ecm/platform/forms/layout/facelets/DocumentLayoutTagHandler.java @@ -1,127 +1,129 @@ /* * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * <a href="mailto:[email protected]">Anahide Tchertchian</a> * * $Id: DocumentLayoutTagHandler.java 26053 2007-10-16 01:45:43Z atchertchian $ */ package org.nuxeo.ecm.platform.forms.layout.facelets; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.el.ELException; import javax.faces.FacesException; import javax.faces.component.UIComponent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.platform.types.adapter.TypeInfo; import com.sun.facelets.FaceletContext; import com.sun.facelets.FaceletException; import com.sun.facelets.FaceletHandler; import com.sun.facelets.tag.CompositeFaceletHandler; import com.sun.facelets.tag.TagAttribute; import com.sun.facelets.tag.TagAttributes; import com.sun.facelets.tag.TagConfig; import com.sun.facelets.tag.TagHandler; /** * Document layout tag handler. * <p> * Computes layouts in given facelet context, for given mode and document * attributes. * <p> * Document must be resolved at the component tree construction so it cannot be * bound to an iteration value. * * @author <a href="mailto:[email protected]">Anahide Tchertchian</a> */ public class DocumentLayoutTagHandler extends TagHandler { @SuppressWarnings("unused") private static final Log log = LogFactory.getLog(DocumentLayoutTagHandler.class); protected final TagConfig config; protected final TagAttribute mode; protected final TagAttribute value; protected final TagAttribute template; protected final TagAttribute[] vars; protected final String[] reservedVarsArray = new String[] { "id", "name", "mode", "value", "template" }; public DocumentLayoutTagHandler(TagConfig config) { super(config); this.config = config; mode = getRequiredAttribute("mode"); value = getRequiredAttribute("value"); template = getAttribute("template"); vars = tag.getAttributes().getAll(); } /** * If resolved document has layouts, apply each of them. */ public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { Object document = value.getObject(ctx, DocumentModel.class); if (!(document instanceof DocumentModel)) { return; } TypeInfo typeInfo = ((DocumentModel) document).getAdapter(TypeInfo.class); if (typeInfo == null) { return; } String modeValue = mode.getValue(ctx); String[] layoutNames = typeInfo.getLayouts(modeValue); if (layoutNames == null || layoutNames.length == 0) { return; } FaceletHandlerHelper helper = new FaceletHandlerHelper(ctx, config); TagAttribute modeAttr = helper.createAttribute("mode", modeValue); List<FaceletHandler> handlers = new ArrayList<FaceletHandler>(); FaceletHandler leaf = new LeafFaceletHandler(); for (String layoutName : layoutNames) { TagAttributes attributes = FaceletHandlerHelper.getTagAttributes( - helper.createAttribute("name", layoutName), modeAttr, - value, template); + helper.createAttribute("name", layoutName), modeAttr, value); + if (template != null) { + FaceletHandlerHelper.addTagAttribute(attributes, template); + } // add other variables put on original tag List<String> reservedVars = Arrays.asList(reservedVarsArray); for (TagAttribute var : vars) { String localName = var.getLocalName(); if (!reservedVars.contains(localName)) { FaceletHandlerHelper.addTagAttribute(attributes, var); } } TagConfig tagConfig = TagConfigFactory.createTagConfig(config, attributes, leaf); handlers.add(new LayoutTagHandler(tagConfig)); } CompositeFaceletHandler composite = new CompositeFaceletHandler( handlers.toArray(new FaceletHandler[] {})); composite.apply(ctx, parent); } }
true
true
public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { Object document = value.getObject(ctx, DocumentModel.class); if (!(document instanceof DocumentModel)) { return; } TypeInfo typeInfo = ((DocumentModel) document).getAdapter(TypeInfo.class); if (typeInfo == null) { return; } String modeValue = mode.getValue(ctx); String[] layoutNames = typeInfo.getLayouts(modeValue); if (layoutNames == null || layoutNames.length == 0) { return; } FaceletHandlerHelper helper = new FaceletHandlerHelper(ctx, config); TagAttribute modeAttr = helper.createAttribute("mode", modeValue); List<FaceletHandler> handlers = new ArrayList<FaceletHandler>(); FaceletHandler leaf = new LeafFaceletHandler(); for (String layoutName : layoutNames) { TagAttributes attributes = FaceletHandlerHelper.getTagAttributes( helper.createAttribute("name", layoutName), modeAttr, value, template); // add other variables put on original tag List<String> reservedVars = Arrays.asList(reservedVarsArray); for (TagAttribute var : vars) { String localName = var.getLocalName(); if (!reservedVars.contains(localName)) { FaceletHandlerHelper.addTagAttribute(attributes, var); } } TagConfig tagConfig = TagConfigFactory.createTagConfig(config, attributes, leaf); handlers.add(new LayoutTagHandler(tagConfig)); } CompositeFaceletHandler composite = new CompositeFaceletHandler( handlers.toArray(new FaceletHandler[] {})); composite.apply(ctx, parent); }
public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { Object document = value.getObject(ctx, DocumentModel.class); if (!(document instanceof DocumentModel)) { return; } TypeInfo typeInfo = ((DocumentModel) document).getAdapter(TypeInfo.class); if (typeInfo == null) { return; } String modeValue = mode.getValue(ctx); String[] layoutNames = typeInfo.getLayouts(modeValue); if (layoutNames == null || layoutNames.length == 0) { return; } FaceletHandlerHelper helper = new FaceletHandlerHelper(ctx, config); TagAttribute modeAttr = helper.createAttribute("mode", modeValue); List<FaceletHandler> handlers = new ArrayList<FaceletHandler>(); FaceletHandler leaf = new LeafFaceletHandler(); for (String layoutName : layoutNames) { TagAttributes attributes = FaceletHandlerHelper.getTagAttributes( helper.createAttribute("name", layoutName), modeAttr, value); if (template != null) { FaceletHandlerHelper.addTagAttribute(attributes, template); } // add other variables put on original tag List<String> reservedVars = Arrays.asList(reservedVarsArray); for (TagAttribute var : vars) { String localName = var.getLocalName(); if (!reservedVars.contains(localName)) { FaceletHandlerHelper.addTagAttribute(attributes, var); } } TagConfig tagConfig = TagConfigFactory.createTagConfig(config, attributes, leaf); handlers.add(new LayoutTagHandler(tagConfig)); } CompositeFaceletHandler composite = new CompositeFaceletHandler( handlers.toArray(new FaceletHandler[] {})); composite.apply(ctx, parent); }
diff --git a/src/main/java/tconstruct/modifiers/armor/ActiveTinkerArmor.java b/src/main/java/tconstruct/modifiers/armor/ActiveTinkerArmor.java index b4c3c4bb0..f8dafd30b 100644 --- a/src/main/java/tconstruct/modifiers/armor/ActiveTinkerArmor.java +++ b/src/main/java/tconstruct/modifiers/armor/ActiveTinkerArmor.java @@ -1,73 +1,76 @@ package tconstruct.modifiers.armor; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.*; import net.minecraft.world.World; import tconstruct.TConstruct; import tconstruct.armor.player.TPlayerStats; import tconstruct.library.armor.*; import tconstruct.library.modifier.*; public class ActiveTinkerArmor extends ActiveArmorMod { @Override public void onArmorTick (World world, EntityPlayer player, ItemStack itemStack, ArmorCore armor, ArmorPart type) { NBTTagCompound tag = itemStack.getTagCompound().getCompoundTag(((IModifyable) itemStack.getItem()).getBaseTagName()); if (tag.hasKey("Moss")) { int chance = tag.getInteger("Moss"); int check = world.canBlockSeeTheSky((int) player.posX, (int) player.posY, (int) player.posZ) ? 350 : 1150; if (TConstruct.random.nextInt(check) < chance) { int current = tag.getInteger("Damage"); - if (current > 0) - tag.setInteger("Damage", current - 1); + if (current > 0) { + current--; + tag.setInteger("Damage", current); + itemStack.setItemDamage(current); + } } } if (type == ArmorPart.Head) { TPlayerStats stats = TPlayerStats.get(player); if (stats.activeGoggles) { if (tag.getBoolean("Night Vision")) player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 15 * 20, 0, true)); } /*List list = world.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.addCoord(0.0D, 0.0D, 0.0D).expand(5.0D, 5.0D, 5.0D)); //TODO: Add modifier code for (int k = 0; k < list.size(); k++) { EntityItem entity = (EntityItem) list.get(k); entity.onCollideWithPlayer(player); }*/ } if (type == ArmorPart.Chest) { if (player.isSneaking() && tag.getBoolean("Stealth")) player.addPotionEffect(new PotionEffect(Potion.invisibility.id, 2, 0, true)); /*int sprintboost = tag.getInteger("Sprint Assist"); if (player.isSprinting() && sprintboost > 0) player.moveEntityWithHeading(-player.moveStrafing * 0.1f * sprintboost, player.moveForward * 0.2F * sprintboost); //Max of 0-1*/ } if (type == ArmorPart.Feet) { if (player.isInWater()) { if (!player.isSneaking() && tag.getBoolean("WaterWalk") && player.motionY <= 0) { player.motionY = 0; } if (tag.getBoolean("LeadBoots")) { if (player.motionY > 0) player.motionY *= 0.5f; else if (player.motionY < 0) player.motionY *= 1.5f; } } } } }
true
true
public void onArmorTick (World world, EntityPlayer player, ItemStack itemStack, ArmorCore armor, ArmorPart type) { NBTTagCompound tag = itemStack.getTagCompound().getCompoundTag(((IModifyable) itemStack.getItem()).getBaseTagName()); if (tag.hasKey("Moss")) { int chance = tag.getInteger("Moss"); int check = world.canBlockSeeTheSky((int) player.posX, (int) player.posY, (int) player.posZ) ? 350 : 1150; if (TConstruct.random.nextInt(check) < chance) { int current = tag.getInteger("Damage"); if (current > 0) tag.setInteger("Damage", current - 1); } } if (type == ArmorPart.Head) { TPlayerStats stats = TPlayerStats.get(player); if (stats.activeGoggles) { if (tag.getBoolean("Night Vision")) player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 15 * 20, 0, true)); } /*List list = world.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.addCoord(0.0D, 0.0D, 0.0D).expand(5.0D, 5.0D, 5.0D)); //TODO: Add modifier code for (int k = 0; k < list.size(); k++) { EntityItem entity = (EntityItem) list.get(k); entity.onCollideWithPlayer(player); }*/ } if (type == ArmorPart.Chest) { if (player.isSneaking() && tag.getBoolean("Stealth")) player.addPotionEffect(new PotionEffect(Potion.invisibility.id, 2, 0, true)); /*int sprintboost = tag.getInteger("Sprint Assist"); if (player.isSprinting() && sprintboost > 0) player.moveEntityWithHeading(-player.moveStrafing * 0.1f * sprintboost, player.moveForward * 0.2F * sprintboost); //Max of 0-1*/ } if (type == ArmorPart.Feet) { if (player.isInWater()) { if (!player.isSneaking() && tag.getBoolean("WaterWalk") && player.motionY <= 0) { player.motionY = 0; } if (tag.getBoolean("LeadBoots")) { if (player.motionY > 0) player.motionY *= 0.5f; else if (player.motionY < 0) player.motionY *= 1.5f; } } } }
public void onArmorTick (World world, EntityPlayer player, ItemStack itemStack, ArmorCore armor, ArmorPart type) { NBTTagCompound tag = itemStack.getTagCompound().getCompoundTag(((IModifyable) itemStack.getItem()).getBaseTagName()); if (tag.hasKey("Moss")) { int chance = tag.getInteger("Moss"); int check = world.canBlockSeeTheSky((int) player.posX, (int) player.posY, (int) player.posZ) ? 350 : 1150; if (TConstruct.random.nextInt(check) < chance) { int current = tag.getInteger("Damage"); if (current > 0) { current--; tag.setInteger("Damage", current); itemStack.setItemDamage(current); } } } if (type == ArmorPart.Head) { TPlayerStats stats = TPlayerStats.get(player); if (stats.activeGoggles) { if (tag.getBoolean("Night Vision")) player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 15 * 20, 0, true)); } /*List list = world.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.addCoord(0.0D, 0.0D, 0.0D).expand(5.0D, 5.0D, 5.0D)); //TODO: Add modifier code for (int k = 0; k < list.size(); k++) { EntityItem entity = (EntityItem) list.get(k); entity.onCollideWithPlayer(player); }*/ } if (type == ArmorPart.Chest) { if (player.isSneaking() && tag.getBoolean("Stealth")) player.addPotionEffect(new PotionEffect(Potion.invisibility.id, 2, 0, true)); /*int sprintboost = tag.getInteger("Sprint Assist"); if (player.isSprinting() && sprintboost > 0) player.moveEntityWithHeading(-player.moveStrafing * 0.1f * sprintboost, player.moveForward * 0.2F * sprintboost); //Max of 0-1*/ } if (type == ArmorPart.Feet) { if (player.isInWater()) { if (!player.isSneaking() && tag.getBoolean("WaterWalk") && player.motionY <= 0) { player.motionY = 0; } if (tag.getBoolean("LeadBoots")) { if (player.motionY > 0) player.motionY *= 0.5f; else if (player.motionY < 0) player.motionY *= 1.5f; } } } }
diff --git a/generator/org.eclipse.emf.texo.generator/src/org/eclipse/emf/texo/generator/SourceMerger.java b/generator/org.eclipse.emf.texo.generator/src/org/eclipse/emf/texo/generator/SourceMerger.java index 3df003d5..5a2e6acc 100755 --- a/generator/org.eclipse.emf.texo.generator/src/org/eclipse/emf/texo/generator/SourceMerger.java +++ b/generator/org.eclipse.emf.texo.generator/src/org/eclipse/emf/texo/generator/SourceMerger.java @@ -1,186 +1,186 @@ /** * <copyright> * * Copyright (c) 2009, 2010 Springsite BV (The Netherlands) and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Martin Taal - Initial API and implementation * * </copyright> * * $Id: SourceMerger.java,v 1.14 2011/08/25 12:34:30 mtaal Exp $ */ package org.eclipse.emf.texo.generator; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.eclipse.emf.codegen.merge.java.JControlModel; import org.eclipse.emf.codegen.merge.java.JMerger; import org.eclipse.emf.codegen.merge.java.facade.ast.ASTFacadeHelper; import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.common.util.DiagnosticException; import org.eclipse.emf.common.util.WrappedException; import org.eclipse.emf.texo.utils.Check; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.xpand2.output.FileHandle; /** * Receives the java output of a generate action and the target location. Reads the current source from there and merges * the generation output and the current content. Also takes care of resolving and organizing imports. * * @see ImportResolver * @see EclipseGeneratorUtils * @see JMerger * @author <a href="[email protected]">Martin Taal</a> */ public class SourceMerger extends MergingOutputHandler { private JControlModel jControlModel; private Object codeFormatter; private IJavaProject javaProject; /** * Does the merge operation and returns the new content if the content has really changed, otherwise null is returned. */ @Override protected void merge(final FileHandle fileHandle) { final String targetLocation = fileHandle.getAbsolutePath(); // final String targetLocation = fileHandle.getAbsolutePath(); final File targetFile = new File(targetLocation); Check.isNotNull(targetFile, "Targetfile is null, for outlet " //$NON-NLS-1$ + fileHandle.getOutlet().getPath()); final String generatedSource = fileHandle.getBuffer().toString(); try { // if exists merge with it if (targetFile.exists()) { mergeImportAndFormat(fileHandle, targetFile); return; } // does not yet exist do the basic things // resolve imports String source = organizeImports(targetLocation, generatedSource); // and format source = EclipseGeneratorUtils.formatSource(source, getCodeFormatter()); fileHandle.setBuffer(source); } catch (final IllegalStateException c) { throw c; // rethrow to prevent to many exceptions } catch (final Exception e) { // catch them all throw new IllegalStateException("Exception while merging and saving source file in sourcemerger " //$NON-NLS-1$ + targetLocation + " " + e.getMessage() + " " + e + "\n" + generatedSource, e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } private void mergeImportAndFormat(final FileHandle fileHandle, final File targetFile) throws Exception { final String targetLocation = targetFile.getAbsolutePath(); final JControlModel localJControlModel = getJControlModel(); final JMerger jMerger = new JMerger(localJControlModel); jMerger.setFixInterfaceBrace(localJControlModel.getFacadeHelper().fixInterfaceBrace()); final String generatedSource = fileHandle.getBuffer().toString(); final String source = organizeImports(targetLocation, generatedSource); try { jMerger.setSourceCompilationUnit(jMerger.createCompilationUnitForContents(source)); } catch (final WrappedException e) { // something wrong in the code // itself throw new IllegalStateException("Syntax error in generated source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(e) + "\nSource>>>>>>>>>>>>>>>>>>>>>>>>>\n" + source, e); //$NON-NLS-1$ //$NON-NLS-2$ } final InputStream is = new FileInputStream(targetFile); String newSource = ""; //$NON-NLS-1$ int location = 0; try { - jMerger.setTargetCompilationUnit(jMerger.createCompilationUnitForInputStream(is)); + jMerger.setTargetCompilationUnit(jMerger.createCompilationUnitForInputStream(is, "UTF-8")); //$NON-NLS-1$ location = 1; jMerger.merge(); location = 2; newSource = jMerger.getTargetCompilationUnitContents(); // again organize imports after the merge location = 3; newSource = organizeImports(targetLocation, newSource); location = 4; newSource = EclipseGeneratorUtils.formatSource(newSource, getCodeFormatter()); // TODO: check if target is read only! jControlModel.getFacadeHelper().reset(); location = 5; fileHandle.setBuffer(newSource); } catch (final WrappedException e) { // something wrong in the code // itself throw new IllegalStateException( "Syntax error in current source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(e) + " location " + location + " old source \n" + source + " new source \n" + newSource, e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } catch (final Throwable t) { throw new IllegalStateException( "Throwable caught for current source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(t) + " location " + location + " old source \n" + source + " new source \n" + newSource, t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } finally { is.close(); } } private String organizeImports(final String location, final String source) throws Exception { final ImportResolver importResolver = new ImportResolver(); importResolver.setJavaProject(javaProject); importResolver.setSource(source); final String resolvedSource = importResolver.resolve(); return resolvedSource; } private String getExceptionMessage(final Throwable t) { if (t.getCause() instanceof DiagnosticException) { final DiagnosticException d = (DiagnosticException) t.getCause(); final StringBuilder message = new StringBuilder(d.getDiagnostic().getMessage()); for (final Diagnostic cd : d.getDiagnostic().getChildren()) { message.append("\n\t").append(cd.getMessage()); //$NON-NLS-1$ } return message.toString(); } return t.getMessage(); } private JControlModel getJControlModel() { if (jControlModel == null) { jControlModel = new JControlModel(); jControlModel.initialize(new ASTFacadeHelper(), this.getClass().getResource("texo-merge.xml").toExternalForm()); //$NON-NLS-1$ } return jControlModel; } private Object getCodeFormatter() { if (codeFormatter == null) { codeFormatter = ToolFactory.createCodeFormatter(javaProject.getOptions(true)); } return codeFormatter; } @Override protected String[] getSupportedExtensions() { return new String[] { ".java" }; //$NON-NLS-1$ } @Override public void setProjectName(final String projectName) { super.setProjectName(projectName); javaProject = EclipseGeneratorUtils.getJavaProject(projectName); } }
true
true
private void mergeImportAndFormat(final FileHandle fileHandle, final File targetFile) throws Exception { final String targetLocation = targetFile.getAbsolutePath(); final JControlModel localJControlModel = getJControlModel(); final JMerger jMerger = new JMerger(localJControlModel); jMerger.setFixInterfaceBrace(localJControlModel.getFacadeHelper().fixInterfaceBrace()); final String generatedSource = fileHandle.getBuffer().toString(); final String source = organizeImports(targetLocation, generatedSource); try { jMerger.setSourceCompilationUnit(jMerger.createCompilationUnitForContents(source)); } catch (final WrappedException e) { // something wrong in the code // itself throw new IllegalStateException("Syntax error in generated source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(e) + "\nSource>>>>>>>>>>>>>>>>>>>>>>>>>\n" + source, e); //$NON-NLS-1$ //$NON-NLS-2$ } final InputStream is = new FileInputStream(targetFile); String newSource = ""; //$NON-NLS-1$ int location = 0; try { jMerger.setTargetCompilationUnit(jMerger.createCompilationUnitForInputStream(is)); location = 1; jMerger.merge(); location = 2; newSource = jMerger.getTargetCompilationUnitContents(); // again organize imports after the merge location = 3; newSource = organizeImports(targetLocation, newSource); location = 4; newSource = EclipseGeneratorUtils.formatSource(newSource, getCodeFormatter()); // TODO: check if target is read only! jControlModel.getFacadeHelper().reset(); location = 5; fileHandle.setBuffer(newSource); } catch (final WrappedException e) { // something wrong in the code // itself throw new IllegalStateException( "Syntax error in current source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(e) + " location " + location + " old source \n" + source + " new source \n" + newSource, e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } catch (final Throwable t) { throw new IllegalStateException( "Throwable caught for current source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(t) + " location " + location + " old source \n" + source + " new source \n" + newSource, t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } finally { is.close(); } }
private void mergeImportAndFormat(final FileHandle fileHandle, final File targetFile) throws Exception { final String targetLocation = targetFile.getAbsolutePath(); final JControlModel localJControlModel = getJControlModel(); final JMerger jMerger = new JMerger(localJControlModel); jMerger.setFixInterfaceBrace(localJControlModel.getFacadeHelper().fixInterfaceBrace()); final String generatedSource = fileHandle.getBuffer().toString(); final String source = organizeImports(targetLocation, generatedSource); try { jMerger.setSourceCompilationUnit(jMerger.createCompilationUnitForContents(source)); } catch (final WrappedException e) { // something wrong in the code // itself throw new IllegalStateException("Syntax error in generated source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(e) + "\nSource>>>>>>>>>>>>>>>>>>>>>>>>>\n" + source, e); //$NON-NLS-1$ //$NON-NLS-2$ } final InputStream is = new FileInputStream(targetFile); String newSource = ""; //$NON-NLS-1$ int location = 0; try { jMerger.setTargetCompilationUnit(jMerger.createCompilationUnitForInputStream(is, "UTF-8")); //$NON-NLS-1$ location = 1; jMerger.merge(); location = 2; newSource = jMerger.getTargetCompilationUnitContents(); // again organize imports after the merge location = 3; newSource = organizeImports(targetLocation, newSource); location = 4; newSource = EclipseGeneratorUtils.formatSource(newSource, getCodeFormatter()); // TODO: check if target is read only! jControlModel.getFacadeHelper().reset(); location = 5; fileHandle.setBuffer(newSource); } catch (final WrappedException e) { // something wrong in the code // itself throw new IllegalStateException( "Syntax error in current source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(e) + " location " + location + " old source \n" + source + " new source \n" + newSource, e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } catch (final Throwable t) { throw new IllegalStateException( "Throwable caught for current source for " + targetLocation //$NON-NLS-1$ + " :" + getExceptionMessage(t) + " location " + location + " old source \n" + source + " new source \n" + newSource, t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } finally { is.close(); } }
diff --git a/src/main/java/net/krinsoft/killsuite/listeners/EntityListener.java b/src/main/java/net/krinsoft/killsuite/listeners/EntityListener.java index 7101bbb..7d8bc8a 100644 --- a/src/main/java/net/krinsoft/killsuite/listeners/EntityListener.java +++ b/src/main/java/net/krinsoft/killsuite/listeners/EntityListener.java @@ -1,187 +1,189 @@ package net.krinsoft.killsuite.listeners; import net.krinsoft.killsuite.KillSuite; import net.krinsoft.killsuite.Monster; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.Tameable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDeathEvent; import java.io.*; import java.text.DecimalFormat; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; /** * @author krinsdeath */ @SuppressWarnings("unused") public class EntityListener implements Listener { private Set<UUID> reasons = new HashSet<UUID>(); private final KillSuite plugin; public EntityListener(KillSuite plugin) { this.plugin = plugin; load(); } @EventHandler(priority = EventPriority.NORMAL) void entityDeath(EntityDeathEvent event) { long n = System.nanoTime(); String world = event.getEntity().getWorld().getName(); if (!plugin.validWorld(world)) { return; } if (!(event.getEntity() instanceof LivingEntity)) { return; } // see if the event was an entity killing another entity if (event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) { // cast to entity damage by entity to check the cause of the damage EntityDamageByEntityEvent evt = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause(); Player killer; boolean pet = false; if (evt.getDamager() instanceof Player) { // damager was a player killer = (Player) evt.getDamager(); } else if (evt.getDamager() instanceof Projectile) { // damager was a projectile if (((Projectile)evt.getDamager()).getShooter() instanceof Player) { // shooter was a player killer = (Player) ((Projectile)evt.getDamager()).getShooter(); } else { // shooter was a monster reasons.remove(event.getEntity().getUniqueId()); return; } } else if (evt.getDamager() instanceof Tameable && ((Tameable)evt.getDamager()).isTamed() && ((Tameable)evt.getDamager()).getOwner() != null && ((Tameable)evt.getDamager()).getOwner() instanceof Player) { pet = true; killer = (Player) ((Tameable)evt.getDamager()).getOwner(); } else { reasons.remove(event.getEntity().getUniqueId()); return; } double mod = 1; if (reasons.contains(event.getEntity().getUniqueId())) { plugin.debug("Encountered spawned mob."); // check if the admin wants to pay users for spawner mobs if (plugin.getConfig().getBoolean("economy.spawner.payout", true)) { // diminish the payout mod = plugin.getConfig().getDouble("economy.spawner.diminish", 0.50); } else { plugin.debug("Payout disabled for spawner mobs."); // cancel the tracking / reward reasons.remove(event.getEntity().getUniqueId()); return; } } Monster monster = Monster.getType(event.getEntity()); double error = plugin.getManager().getKiller(killer.getName()).update(monster.getName()); if (error > 0) { double amount = 0; if (plugin.getBank() != null) { // economy is enabled // multivariable calculus ensues -> try { if (!monster.getCategory().equalsIgnoreCase("players")) { List<Double> range = plugin.getConfig().getDoubleList("economy." + monster.getCategory() + "." + monster.getName()); double min = range.get(0); double max = range.get(1); amount = Double.valueOf(new DecimalFormat("#.##").format(min + (Math.random() * ((max - min))))); } else { Player dead = (Player) event.getEntity(); List<Double> range = plugin.getConfig().getDoubleList("economy.players.reward"); double min = range.get(0); double max = range.get(1); amount = Double.valueOf(new DecimalFormat("#.##").format(min + (Math.random() * ((max - min))))); if (plugin.getConfig().getBoolean("economy.players.percentage")) { double balance = plugin.getBank().getBalance(dead, -1); amount = balance * (amount / 100); } if (plugin.getConfig().getBoolean("economy.players.realism")) { double balance = plugin.getBank().getBalance(dead, -1); if (amount > balance) { amount = balance; } plugin.getBank().take(dead, amount, -1); } } amount = plugin.diminishReturn(killer, amount); amount = amount * mod; long bank = System.nanoTime(); plugin.getBank().give(killer, amount, -1); plugin.profile("bank.update", System.nanoTime() - bank); } catch (NullPointerException e) { plugin.debug(e.getLocalizedMessage() + ": Found null path at 'economy." + monster.getCategory() + "." + monster.getName() + "' in 'config.yml'"); } catch (ArrayIndexOutOfBoundsException e) { plugin.debug(e.getLocalizedMessage() + ": Invalid list at 'economy." + monster.getCategory() + "." + monster.getName() + "'"); + } catch (IndexOutOfBoundsException e) { + plugin.getLogger().warning(e.getLocalizedMessage() + ": Invalid economy list in config.yml! Probable culprit: " + monster.getCategory() + "/" + monster.getName()); } } // report the earnings plugin.report(killer, monster, amount, pet); } else { plugin.getLogger().warning("An error occurred while incrementing the monster count for '" + killer.getName() + "'!"); plugin.getLogger().warning(plugin.getManager().getKiller(killer.getName()).toString()); } } n = System.nanoTime() - n; reasons.remove(event.getEntity().getUniqueId()); plugin.profile("entity.death", n); } @EventHandler void creatureSpawn(CreatureSpawnEvent event) { if (!plugin.validWorld(event.getEntity().getWorld().getName())) { return; } UUID id = event.getEntity().getUniqueId(); if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && !reasons.contains(id)) { reasons.add(id); } } public void save() { try { File idFile = new File(plugin.getDataFolder(), "uuid_spawner.dat"); if (!idFile.exists()) { //noinspection ResultOfMethodCallIgnored idFile.createNewFile(); } FileOutputStream fileOut = new FileOutputStream(idFile); ObjectOutputStream objOut = new ObjectOutputStream(fileOut); objOut.writeObject(reasons); objOut.close(); } catch (FileNotFoundException e) { plugin.getLogger().warning(e.getMessage()); } catch (IOException e) { plugin.getLogger().warning(e.getMessage()); } } void load() { try { File idFile = new File(plugin.getDataFolder(), "uuid_spawner.dat"); if (idFile.exists()) { FileInputStream fileIn = new FileInputStream(idFile); ObjectInputStream objIn = new ObjectInputStream(fileIn); //noinspection unchecked reasons = (Set<UUID>) objIn.readObject(); objIn.close(); fileIn.close(); //noinspection ResultOfMethodCallIgnored idFile.delete(); } } catch (FileNotFoundException e) { plugin.getLogger().warning(e.getMessage()); } catch (IOException e) { plugin.getLogger().warning(e.getMessage()); } catch (ClassNotFoundException e) { plugin.getLogger().warning(e.getMessage()); } } }
true
true
void entityDeath(EntityDeathEvent event) { long n = System.nanoTime(); String world = event.getEntity().getWorld().getName(); if (!plugin.validWorld(world)) { return; } if (!(event.getEntity() instanceof LivingEntity)) { return; } // see if the event was an entity killing another entity if (event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) { // cast to entity damage by entity to check the cause of the damage EntityDamageByEntityEvent evt = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause(); Player killer; boolean pet = false; if (evt.getDamager() instanceof Player) { // damager was a player killer = (Player) evt.getDamager(); } else if (evt.getDamager() instanceof Projectile) { // damager was a projectile if (((Projectile)evt.getDamager()).getShooter() instanceof Player) { // shooter was a player killer = (Player) ((Projectile)evt.getDamager()).getShooter(); } else { // shooter was a monster reasons.remove(event.getEntity().getUniqueId()); return; } } else if (evt.getDamager() instanceof Tameable && ((Tameable)evt.getDamager()).isTamed() && ((Tameable)evt.getDamager()).getOwner() != null && ((Tameable)evt.getDamager()).getOwner() instanceof Player) { pet = true; killer = (Player) ((Tameable)evt.getDamager()).getOwner(); } else { reasons.remove(event.getEntity().getUniqueId()); return; } double mod = 1; if (reasons.contains(event.getEntity().getUniqueId())) { plugin.debug("Encountered spawned mob."); // check if the admin wants to pay users for spawner mobs if (plugin.getConfig().getBoolean("economy.spawner.payout", true)) { // diminish the payout mod = plugin.getConfig().getDouble("economy.spawner.diminish", 0.50); } else { plugin.debug("Payout disabled for spawner mobs."); // cancel the tracking / reward reasons.remove(event.getEntity().getUniqueId()); return; } } Monster monster = Monster.getType(event.getEntity()); double error = plugin.getManager().getKiller(killer.getName()).update(monster.getName()); if (error > 0) { double amount = 0; if (plugin.getBank() != null) { // economy is enabled // multivariable calculus ensues -> try { if (!monster.getCategory().equalsIgnoreCase("players")) { List<Double> range = plugin.getConfig().getDoubleList("economy." + monster.getCategory() + "." + monster.getName()); double min = range.get(0); double max = range.get(1); amount = Double.valueOf(new DecimalFormat("#.##").format(min + (Math.random() * ((max - min))))); } else { Player dead = (Player) event.getEntity(); List<Double> range = plugin.getConfig().getDoubleList("economy.players.reward"); double min = range.get(0); double max = range.get(1); amount = Double.valueOf(new DecimalFormat("#.##").format(min + (Math.random() * ((max - min))))); if (plugin.getConfig().getBoolean("economy.players.percentage")) { double balance = plugin.getBank().getBalance(dead, -1); amount = balance * (amount / 100); } if (plugin.getConfig().getBoolean("economy.players.realism")) { double balance = plugin.getBank().getBalance(dead, -1); if (amount > balance) { amount = balance; } plugin.getBank().take(dead, amount, -1); } } amount = plugin.diminishReturn(killer, amount); amount = amount * mod; long bank = System.nanoTime(); plugin.getBank().give(killer, amount, -1); plugin.profile("bank.update", System.nanoTime() - bank); } catch (NullPointerException e) { plugin.debug(e.getLocalizedMessage() + ": Found null path at 'economy." + monster.getCategory() + "." + monster.getName() + "' in 'config.yml'"); } catch (ArrayIndexOutOfBoundsException e) { plugin.debug(e.getLocalizedMessage() + ": Invalid list at 'economy." + monster.getCategory() + "." + monster.getName() + "'"); } } // report the earnings plugin.report(killer, monster, amount, pet); } else { plugin.getLogger().warning("An error occurred while incrementing the monster count for '" + killer.getName() + "'!"); plugin.getLogger().warning(plugin.getManager().getKiller(killer.getName()).toString()); } } n = System.nanoTime() - n; reasons.remove(event.getEntity().getUniqueId()); plugin.profile("entity.death", n); }
void entityDeath(EntityDeathEvent event) { long n = System.nanoTime(); String world = event.getEntity().getWorld().getName(); if (!plugin.validWorld(world)) { return; } if (!(event.getEntity() instanceof LivingEntity)) { return; } // see if the event was an entity killing another entity if (event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) { // cast to entity damage by entity to check the cause of the damage EntityDamageByEntityEvent evt = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause(); Player killer; boolean pet = false; if (evt.getDamager() instanceof Player) { // damager was a player killer = (Player) evt.getDamager(); } else if (evt.getDamager() instanceof Projectile) { // damager was a projectile if (((Projectile)evt.getDamager()).getShooter() instanceof Player) { // shooter was a player killer = (Player) ((Projectile)evt.getDamager()).getShooter(); } else { // shooter was a monster reasons.remove(event.getEntity().getUniqueId()); return; } } else if (evt.getDamager() instanceof Tameable && ((Tameable)evt.getDamager()).isTamed() && ((Tameable)evt.getDamager()).getOwner() != null && ((Tameable)evt.getDamager()).getOwner() instanceof Player) { pet = true; killer = (Player) ((Tameable)evt.getDamager()).getOwner(); } else { reasons.remove(event.getEntity().getUniqueId()); return; } double mod = 1; if (reasons.contains(event.getEntity().getUniqueId())) { plugin.debug("Encountered spawned mob."); // check if the admin wants to pay users for spawner mobs if (plugin.getConfig().getBoolean("economy.spawner.payout", true)) { // diminish the payout mod = plugin.getConfig().getDouble("economy.spawner.diminish", 0.50); } else { plugin.debug("Payout disabled for spawner mobs."); // cancel the tracking / reward reasons.remove(event.getEntity().getUniqueId()); return; } } Monster monster = Monster.getType(event.getEntity()); double error = plugin.getManager().getKiller(killer.getName()).update(monster.getName()); if (error > 0) { double amount = 0; if (plugin.getBank() != null) { // economy is enabled // multivariable calculus ensues -> try { if (!monster.getCategory().equalsIgnoreCase("players")) { List<Double> range = plugin.getConfig().getDoubleList("economy." + monster.getCategory() + "." + monster.getName()); double min = range.get(0); double max = range.get(1); amount = Double.valueOf(new DecimalFormat("#.##").format(min + (Math.random() * ((max - min))))); } else { Player dead = (Player) event.getEntity(); List<Double> range = plugin.getConfig().getDoubleList("economy.players.reward"); double min = range.get(0); double max = range.get(1); amount = Double.valueOf(new DecimalFormat("#.##").format(min + (Math.random() * ((max - min))))); if (plugin.getConfig().getBoolean("economy.players.percentage")) { double balance = plugin.getBank().getBalance(dead, -1); amount = balance * (amount / 100); } if (plugin.getConfig().getBoolean("economy.players.realism")) { double balance = plugin.getBank().getBalance(dead, -1); if (amount > balance) { amount = balance; } plugin.getBank().take(dead, amount, -1); } } amount = plugin.diminishReturn(killer, amount); amount = amount * mod; long bank = System.nanoTime(); plugin.getBank().give(killer, amount, -1); plugin.profile("bank.update", System.nanoTime() - bank); } catch (NullPointerException e) { plugin.debug(e.getLocalizedMessage() + ": Found null path at 'economy." + monster.getCategory() + "." + monster.getName() + "' in 'config.yml'"); } catch (ArrayIndexOutOfBoundsException e) { plugin.debug(e.getLocalizedMessage() + ": Invalid list at 'economy." + monster.getCategory() + "." + monster.getName() + "'"); } catch (IndexOutOfBoundsException e) { plugin.getLogger().warning(e.getLocalizedMessage() + ": Invalid economy list in config.yml! Probable culprit: " + monster.getCategory() + "/" + monster.getName()); } } // report the earnings plugin.report(killer, monster, amount, pet); } else { plugin.getLogger().warning("An error occurred while incrementing the monster count for '" + killer.getName() + "'!"); plugin.getLogger().warning(plugin.getManager().getKiller(killer.getName()).toString()); } } n = System.nanoTime() - n; reasons.remove(event.getEntity().getUniqueId()); plugin.profile("entity.death", n); }
diff --git a/src/de/schauderhaft/degraph/demo/person/persistence/DBPersonRepository.java b/src/de/schauderhaft/degraph/demo/person/persistence/DBPersonRepository.java index f9e7082..bb4c064 100644 --- a/src/de/schauderhaft/degraph/demo/person/persistence/DBPersonRepository.java +++ b/src/de/schauderhaft/degraph/demo/person/persistence/DBPersonRepository.java @@ -1,15 +1,16 @@ package de.schauderhaft.degraph.demo.person.persistence; import java.util.List; import de.schauderhaft.degraph.demo.person.domain.Person; import de.schauderhaft.degraph.demo.person.domain.PersonRepository; public class DBPersonRepository implements PersonRepository { @Override public void saveOrUpdate(List<Person> persons) { // new Order(); + // new ConsolePersonView(); } }
true
true
public void saveOrUpdate(List<Person> persons) { // new Order(); }
public void saveOrUpdate(List<Person> persons) { // new Order(); // new ConsolePersonView(); }
diff --git a/framework/src/play/db/DBPlugin.java b/framework/src/play/db/DBPlugin.java index 991028d1..9fe11aec 100644 --- a/framework/src/play/db/DBPlugin.java +++ b/framework/src/play/db/DBPlugin.java @@ -1,172 +1,172 @@ package play.db; import com.mchange.v2.c3p0.ConnectionCustomizer; import play.Play; import play.PlayPlugin; import play.mvc.Http; import play.mvc.Http.Request; import play.mvc.Http.Response; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The DB plugin */ public class DBPlugin extends PlayPlugin { org.h2.tools.Server h2Server; @Override public boolean rawInvocation(Request request, Response response) throws Exception { if (Play.mode.isDev() && request.path.equals("/@db")) { - response.status = Http.StatusCode.MOVED; + response.status = Http.StatusCode.FOUND; String serverOptions[] = new String[] { }; // For H2 embeded database, we'll also start the Web console if (h2Server != null) { h2Server.stop(); } String domain = request.domain; if (domain.equals("")) { domain = "localhost"; } if (!domain.equals("localhost")) { serverOptions = new String[] {"-webAllowOthers"}; } h2Server = org.h2.tools.Server.createWebServer(serverOptions); h2Server.start(); response.setHeader("Location", "http://" + domain + ":8082/"); return true; } return false; } @Override public void onApplicationStart() { System.setProperty("com.mchange.v2.log.MLog", "com.mchange.v2.log.FallbackMLog"); System.setProperty("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "OFF"); List<String> dbConfigNames = new ArrayList<String>(1); // first we must look for and configure the default dbConfig if (isDefaultDBConfigPresent(Play.configuration)) { // Can only add default db config-name if it is present in config-file. // Must do this to be able to detect if user removes default db config from config file dbConfigNames.add(DBConfig.defaultDbConfigName); } //look for other configurations dbConfigNames.addAll(detectedExtraDBConfigs(Play.configuration)); DB.setConfigurations(dbConfigNames); } /** * @return true if default db config properties is found */ protected boolean isDefaultDBConfigPresent(Properties props) { Pattern pattern = Pattern.compile("^db(?:$|\\..*)"); for( String propName : props.stringPropertyNames()) { Matcher m = pattern.matcher(propName); if (m.find()) { return true; } } return false; } /** * Looks for extra db configs in config. * * Properties starting with 'db_' * @return list of all extra db config names found */ protected Set<String> detectedExtraDBConfigs(Properties props) { Set<String> names = new LinkedHashSet<String>(0); //preserve order Pattern pattern = Pattern.compile("^db\\_([^\\.]+)(?:$|\\..*)"); for( String propName : props.stringPropertyNames()) { Matcher m = pattern.matcher(propName); if (m.find()) { String configName = m.group(1); if (!names.contains(configName)) { names.add(configName); } } } return names; } @Override public void onApplicationStop() { if (Play.mode.isProd()) { DB.destroy(); } } @Override public String getStatus() { return DB.getStatus(); } @Override public void invocationFinally() { DB.close(); } /** * Needed because DriverManager will not load a driver outside of the system classloader */ public static class ProxyDriver implements Driver { private Driver driver; ProxyDriver(Driver d) { this.driver = d; } /* * JDK 7 compatibility */ public Logger getParentLogger() { return null; } public boolean acceptsURL(String u) throws SQLException { return this.driver.acceptsURL(u); } public Connection connect(String u, Properties p) throws SQLException { return this.driver.connect(u, p); } public int getMajorVersion() { return this.driver.getMajorVersion(); } public int getMinorVersion() { return this.driver.getMinorVersion(); } public DriverPropertyInfo[] getPropertyInfo(String u, Properties p) throws SQLException { return this.driver.getPropertyInfo(u, p); } public boolean jdbcCompliant() { return this.driver.jdbcCompliant(); } } }
true
true
public boolean rawInvocation(Request request, Response response) throws Exception { if (Play.mode.isDev() && request.path.equals("/@db")) { response.status = Http.StatusCode.MOVED; String serverOptions[] = new String[] { }; // For H2 embeded database, we'll also start the Web console if (h2Server != null) { h2Server.stop(); } String domain = request.domain; if (domain.equals("")) { domain = "localhost"; } if (!domain.equals("localhost")) { serverOptions = new String[] {"-webAllowOthers"}; } h2Server = org.h2.tools.Server.createWebServer(serverOptions); h2Server.start(); response.setHeader("Location", "http://" + domain + ":8082/"); return true; } return false; }
public boolean rawInvocation(Request request, Response response) throws Exception { if (Play.mode.isDev() && request.path.equals("/@db")) { response.status = Http.StatusCode.FOUND; String serverOptions[] = new String[] { }; // For H2 embeded database, we'll also start the Web console if (h2Server != null) { h2Server.stop(); } String domain = request.domain; if (domain.equals("")) { domain = "localhost"; } if (!domain.equals("localhost")) { serverOptions = new String[] {"-webAllowOthers"}; } h2Server = org.h2.tools.Server.createWebServer(serverOptions); h2Server.start(); response.setHeader("Location", "http://" + domain + ":8082/"); return true; } return false; }
diff --git a/src/main/java/org/trancecode/xproc/PipelineFactory.java b/src/main/java/org/trancecode/xproc/PipelineFactory.java index c053b792..0308a2c9 100644 --- a/src/main/java/org/trancecode/xproc/PipelineFactory.java +++ b/src/main/java/org/trancecode/xproc/PipelineFactory.java @@ -1,224 +1,224 @@ /* * Copyright (C) 2008 TranceCode Software * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.trancecode.xproc; import org.trancecode.xml.Location; import org.trancecode.xproc.parser.PipelineParser; import org.trancecode.xproc.parser.StepFactory; import org.trancecode.xproc.step.Choose; import org.trancecode.xproc.step.CountStepFactory; import org.trancecode.xproc.step.ForEach; import org.trancecode.xproc.step.IdentityStepFactory; import org.trancecode.xproc.step.LoadStepFactory; import org.trancecode.xproc.step.Otherwise; import org.trancecode.xproc.step.StoreStepFactory; import org.trancecode.xproc.step.When; import org.trancecode.xproc.step.XsltStepFactory; import java.util.Map; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.QName; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** * @author Herve Quiroz * @version $Revision$ */ public class PipelineFactory { public static final Map<QName, StepFactory> DEFAULT_LIBRARY = newDefaultLibrary(); private final XLogger log = XLoggerFactory.getXLogger(getClass()); private Processor processor = new Processor(false); private URIResolver uriResolver = processor.getUnderlyingConfiguration().getURIResolver(); private Map<QName, StepFactory> library = getDefaultLibrary(); public Pipeline newPipeline(final Source source) { log.entry(source); assert source != null; if (processor == null) { processor = new Processor(false); } // TODO final PipelineParser parser = new PipelineParser(this, source, getLibrary()); parser.parse(); final org.trancecode.xproc.step.Pipeline pipeline = parser.getPipeline(); if (pipeline == null) { throw new PipelineException("no pipeline could be parsed from %s", source.getSystemId()); } // TODO pass the parsed pipeline to the runnable pipeline return new Pipeline(processor, uriResolver, pipeline); } public Map<QName, StepFactory> newPipelineLibrary(final Source source) { final PipelineParser parser = new PipelineParser(this, source, getLibrary()); parser.parse(); // TODO return null; } private static StepFactory newUnsupportedStepFactory(final QName stepType) { return new StepFactory() { @Override public Step newStep(final String name, final Location location) { throw new UnsupportedOperationException("step type = " + stepType + " ; name = " + name + " ; location = " + location); } }; } private static void addUnsupportedStepFactory(final QName stepType, final Map<QName, StepFactory> library) { assert !library.containsKey(stepType); library.put(stepType, newUnsupportedStepFactory(stepType)); } public static Map<QName, StepFactory> getDefaultLibrary() { return DEFAULT_LIBRARY; } private static Map<QName, StepFactory> newDefaultLibrary() { final Map<QName, StepFactory> library = Maps.newHashMap(); // Core steps library.put(XProcSteps.CHOOSE, Choose.FACTORY); library.put(XProcSteps.FOR_EACH, ForEach.FACTORY); library.put(XProcSteps.OTHERWISE, Otherwise.FACTORY); library.put(XProcSteps.WHEN, When.FACTORY); // Required steps library.put(XProcSteps.COUNT, CountStepFactory.INSTANCE); library.put(XProcSteps.IDENTITY, IdentityStepFactory.INSTANCE); library.put(XProcSteps.LOAD, LoadStepFactory.INSTANCE); library.put(XProcSteps.STORE, StoreStepFactory.INSTANCE); library.put(XProcSteps.XSLT, XsltStepFactory.INSTANCE); // Unsupported core steps addUnsupportedStepFactory(XProcSteps.GROUP, library); addUnsupportedStepFactory(XProcSteps.TRY, library); // Unsupported required steps addUnsupportedStepFactory(XProcSteps.ADD_ATTRIBUTE, library); addUnsupportedStepFactory(XProcSteps.ADD_XML_BASE, library); addUnsupportedStepFactory(XProcSteps.COMPARE, library); addUnsupportedStepFactory(XProcSteps.DELETE, library); addUnsupportedStepFactory(XProcSteps.DIRECTORY_LIST, library); addUnsupportedStepFactory(XProcSteps.ERROR, library); addUnsupportedStepFactory(XProcSteps.ESCAPE_MARKUP, library); addUnsupportedStepFactory(XProcSteps.FILTER, library); addUnsupportedStepFactory(XProcSteps.HTTP_REQUEST, library); addUnsupportedStepFactory(XProcSteps.INSERT, library); addUnsupportedStepFactory(XProcSteps.LABEL_ELEMENT, library); addUnsupportedStepFactory(XProcSteps.MAKE_ABSOLUTE_URIS, library); addUnsupportedStepFactory(XProcSteps.NAMESPACE_RENAME, library); addUnsupportedStepFactory(XProcSteps.PACK, library); addUnsupportedStepFactory(XProcSteps.PARAMETERS, library); addUnsupportedStepFactory(XProcSteps.RENAME, library); addUnsupportedStepFactory(XProcSteps.REPLACE, library); addUnsupportedStepFactory(XProcSteps.SET_ATTRIBUTES, library); addUnsupportedStepFactory(XProcSteps.SINK, library); addUnsupportedStepFactory(XProcSteps.SPLIT_SEQUENCE, library); addUnsupportedStepFactory(XProcSteps.STRING_REPLACE, library); addUnsupportedStepFactory(XProcSteps.UNESCAPE_MARKUP, library); addUnsupportedStepFactory(XProcSteps.UNWRAP, library); addUnsupportedStepFactory(XProcSteps.WRAP, library); - addUnsupportedStepFactory(XProcSteps.XINXLUDE, library); + addUnsupportedStepFactory(XProcSteps.XINCLUDE, library); // Unsupported optional steps addUnsupportedStepFactory(XProcSteps.EXEC, library); addUnsupportedStepFactory(XProcSteps.HASH, library); addUnsupportedStepFactory(XProcSteps.UUID, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_RELANXNG, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_SCHEMATRON, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_SCHEMA, library); addUnsupportedStepFactory(XProcSteps.WWW_FORM_URL_DECODE, library); addUnsupportedStepFactory(XProcSteps.WWW_FORM_URL_ENCODE, library); addUnsupportedStepFactory(XProcSteps.XQUERY, library); addUnsupportedStepFactory(XProcSteps.XSL_FORMATTER, library); return ImmutableMap.copyOf(library); } public Map<QName, StepFactory> getLibrary() { return library; } public void setLibrary(final Map<QName, StepFactory> library) { assert library != null; this.library = library; } public void setUriResolver(final URIResolver uriResolver) { this.uriResolver = uriResolver; } public void setProcessor(final Processor processor) { assert processor != null; this.processor = processor; } public URIResolver getUriResolver() { return this.uriResolver; } public Processor getProcessor() { return this.processor; } }
true
true
private static Map<QName, StepFactory> newDefaultLibrary() { final Map<QName, StepFactory> library = Maps.newHashMap(); // Core steps library.put(XProcSteps.CHOOSE, Choose.FACTORY); library.put(XProcSteps.FOR_EACH, ForEach.FACTORY); library.put(XProcSteps.OTHERWISE, Otherwise.FACTORY); library.put(XProcSteps.WHEN, When.FACTORY); // Required steps library.put(XProcSteps.COUNT, CountStepFactory.INSTANCE); library.put(XProcSteps.IDENTITY, IdentityStepFactory.INSTANCE); library.put(XProcSteps.LOAD, LoadStepFactory.INSTANCE); library.put(XProcSteps.STORE, StoreStepFactory.INSTANCE); library.put(XProcSteps.XSLT, XsltStepFactory.INSTANCE); // Unsupported core steps addUnsupportedStepFactory(XProcSteps.GROUP, library); addUnsupportedStepFactory(XProcSteps.TRY, library); // Unsupported required steps addUnsupportedStepFactory(XProcSteps.ADD_ATTRIBUTE, library); addUnsupportedStepFactory(XProcSteps.ADD_XML_BASE, library); addUnsupportedStepFactory(XProcSteps.COMPARE, library); addUnsupportedStepFactory(XProcSteps.DELETE, library); addUnsupportedStepFactory(XProcSteps.DIRECTORY_LIST, library); addUnsupportedStepFactory(XProcSteps.ERROR, library); addUnsupportedStepFactory(XProcSteps.ESCAPE_MARKUP, library); addUnsupportedStepFactory(XProcSteps.FILTER, library); addUnsupportedStepFactory(XProcSteps.HTTP_REQUEST, library); addUnsupportedStepFactory(XProcSteps.INSERT, library); addUnsupportedStepFactory(XProcSteps.LABEL_ELEMENT, library); addUnsupportedStepFactory(XProcSteps.MAKE_ABSOLUTE_URIS, library); addUnsupportedStepFactory(XProcSteps.NAMESPACE_RENAME, library); addUnsupportedStepFactory(XProcSteps.PACK, library); addUnsupportedStepFactory(XProcSteps.PARAMETERS, library); addUnsupportedStepFactory(XProcSteps.RENAME, library); addUnsupportedStepFactory(XProcSteps.REPLACE, library); addUnsupportedStepFactory(XProcSteps.SET_ATTRIBUTES, library); addUnsupportedStepFactory(XProcSteps.SINK, library); addUnsupportedStepFactory(XProcSteps.SPLIT_SEQUENCE, library); addUnsupportedStepFactory(XProcSteps.STRING_REPLACE, library); addUnsupportedStepFactory(XProcSteps.UNESCAPE_MARKUP, library); addUnsupportedStepFactory(XProcSteps.UNWRAP, library); addUnsupportedStepFactory(XProcSteps.WRAP, library); addUnsupportedStepFactory(XProcSteps.XINXLUDE, library); // Unsupported optional steps addUnsupportedStepFactory(XProcSteps.EXEC, library); addUnsupportedStepFactory(XProcSteps.HASH, library); addUnsupportedStepFactory(XProcSteps.UUID, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_RELANXNG, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_SCHEMATRON, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_SCHEMA, library); addUnsupportedStepFactory(XProcSteps.WWW_FORM_URL_DECODE, library); addUnsupportedStepFactory(XProcSteps.WWW_FORM_URL_ENCODE, library); addUnsupportedStepFactory(XProcSteps.XQUERY, library); addUnsupportedStepFactory(XProcSteps.XSL_FORMATTER, library); return ImmutableMap.copyOf(library); }
private static Map<QName, StepFactory> newDefaultLibrary() { final Map<QName, StepFactory> library = Maps.newHashMap(); // Core steps library.put(XProcSteps.CHOOSE, Choose.FACTORY); library.put(XProcSteps.FOR_EACH, ForEach.FACTORY); library.put(XProcSteps.OTHERWISE, Otherwise.FACTORY); library.put(XProcSteps.WHEN, When.FACTORY); // Required steps library.put(XProcSteps.COUNT, CountStepFactory.INSTANCE); library.put(XProcSteps.IDENTITY, IdentityStepFactory.INSTANCE); library.put(XProcSteps.LOAD, LoadStepFactory.INSTANCE); library.put(XProcSteps.STORE, StoreStepFactory.INSTANCE); library.put(XProcSteps.XSLT, XsltStepFactory.INSTANCE); // Unsupported core steps addUnsupportedStepFactory(XProcSteps.GROUP, library); addUnsupportedStepFactory(XProcSteps.TRY, library); // Unsupported required steps addUnsupportedStepFactory(XProcSteps.ADD_ATTRIBUTE, library); addUnsupportedStepFactory(XProcSteps.ADD_XML_BASE, library); addUnsupportedStepFactory(XProcSteps.COMPARE, library); addUnsupportedStepFactory(XProcSteps.DELETE, library); addUnsupportedStepFactory(XProcSteps.DIRECTORY_LIST, library); addUnsupportedStepFactory(XProcSteps.ERROR, library); addUnsupportedStepFactory(XProcSteps.ESCAPE_MARKUP, library); addUnsupportedStepFactory(XProcSteps.FILTER, library); addUnsupportedStepFactory(XProcSteps.HTTP_REQUEST, library); addUnsupportedStepFactory(XProcSteps.INSERT, library); addUnsupportedStepFactory(XProcSteps.LABEL_ELEMENT, library); addUnsupportedStepFactory(XProcSteps.MAKE_ABSOLUTE_URIS, library); addUnsupportedStepFactory(XProcSteps.NAMESPACE_RENAME, library); addUnsupportedStepFactory(XProcSteps.PACK, library); addUnsupportedStepFactory(XProcSteps.PARAMETERS, library); addUnsupportedStepFactory(XProcSteps.RENAME, library); addUnsupportedStepFactory(XProcSteps.REPLACE, library); addUnsupportedStepFactory(XProcSteps.SET_ATTRIBUTES, library); addUnsupportedStepFactory(XProcSteps.SINK, library); addUnsupportedStepFactory(XProcSteps.SPLIT_SEQUENCE, library); addUnsupportedStepFactory(XProcSteps.STRING_REPLACE, library); addUnsupportedStepFactory(XProcSteps.UNESCAPE_MARKUP, library); addUnsupportedStepFactory(XProcSteps.UNWRAP, library); addUnsupportedStepFactory(XProcSteps.WRAP, library); addUnsupportedStepFactory(XProcSteps.XINCLUDE, library); // Unsupported optional steps addUnsupportedStepFactory(XProcSteps.EXEC, library); addUnsupportedStepFactory(XProcSteps.HASH, library); addUnsupportedStepFactory(XProcSteps.UUID, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_RELANXNG, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_SCHEMATRON, library); addUnsupportedStepFactory(XProcSteps.VALIDATE_WITH_SCHEMA, library); addUnsupportedStepFactory(XProcSteps.WWW_FORM_URL_DECODE, library); addUnsupportedStepFactory(XProcSteps.WWW_FORM_URL_ENCODE, library); addUnsupportedStepFactory(XProcSteps.XQUERY, library); addUnsupportedStepFactory(XProcSteps.XSL_FORMATTER, library); return ImmutableMap.copyOf(library); }
diff --git a/src/net/sf/freecol/client/control/InGameController.java b/src/net/sf/freecol/client/control/InGameController.java index 2dc940459..1280f8a56 100644 --- a/src/net/sf/freecol/client/control/InGameController.java +++ b/src/net/sf/freecol/client/control/InGameController.java @@ -1,3574 +1,3574 @@ package net.sf.freecol.client.control; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import javax.swing.SwingUtilities; import net.sf.freecol.FreeCol; import net.sf.freecol.client.ClientOptions; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.client.gui.Canvas; import net.sf.freecol.client.gui.GUI; import net.sf.freecol.client.gui.InGameMenuBar; import net.sf.freecol.client.gui.i18n.Messages; import net.sf.freecol.client.gui.panel.ChoiceItem; import net.sf.freecol.client.gui.panel.EventPanel; import net.sf.freecol.client.gui.panel.FreeColDialog; import net.sf.freecol.client.gui.sound.SfxLibrary; import net.sf.freecol.client.networking.Client; import net.sf.freecol.common.Specification; import net.sf.freecol.common.model.Building; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTile; import net.sf.freecol.common.model.DiplomaticTrade; import net.sf.freecol.common.model.Europe; import net.sf.freecol.common.model.FoundingFather; import net.sf.freecol.common.model.FreeColGameObject; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.GoalDecider; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsContainer; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.IndianSettlement; import net.sf.freecol.common.model.Location; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Nameable; import net.sf.freecol.common.model.Ownable; import net.sf.freecol.common.model.PathNode; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Settlement; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.TradeRoute; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.common.model.WorkLocation; import net.sf.freecol.common.model.Map.Position; import net.sf.freecol.common.model.TradeRoute.Stop; import net.sf.freecol.common.networking.Message; import net.sf.freecol.common.networking.NetworkConstants; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * The controller that will be used while the game is played. */ public final class InGameController implements NetworkConstants { private static final Logger logger = Logger.getLogger(InGameController.class.getName()); public static final String COPYRIGHT = "Copyright (C) 2003-2007 The FreeCol Team"; public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html"; public static final String REVISION = "$Revision$"; private final FreeColClient freeColClient; /** * Sets that the turn will be ended when all going-to units have been moved. */ private boolean endingTurn = false; /** * Sets that all going-to orders should be executed. */ private boolean executeGoto = false; /** * A hash map of messages to be ignored. */ private HashMap<String, Integer> messagesToIgnore = new HashMap<String, Integer>(); /** * A list of save game files. */ private ArrayList<File> allSaveGames = new ArrayList<File>(); /** * The constructor to use. * * @param freeColClient The main controller. */ public InGameController(FreeColClient freeColClient) { this.freeColClient = freeColClient; } /** * Opens a dialog where the user should specify the filename and saves the * game. */ public void saveGame() { final Canvas canvas = freeColClient.getCanvas(); String fileName = freeColClient.getMyPlayer().getName() + "_" + freeColClient.getMyPlayer().getNationAsString() + "_" + freeColClient.getGame().getTurn().toSaveGameString(); fileName = fileName.replaceAll(" ", "_"); if (freeColClient.getMyPlayer().isAdmin() && freeColClient.getFreeColServer() != null) { final File file = canvas.showSaveDialog(FreeCol.getSaveDirectory(), fileName); if (file != null) { saveGame(file); } } } /** * Saves the game to the given file. * * @param file The <code>File</code>. */ public void saveGame(final File file) { final Canvas canvas = freeColClient.getCanvas(); canvas.showStatusPanel(Messages.message("status.savingGame")); Thread t = new Thread() { public void run() { try { freeColClient.getFreeColServer().saveGame(file, freeColClient.getMyPlayer().getUsername()); SwingUtilities.invokeLater(new Runnable() { public void run() { canvas.closeStatusPanel(); canvas.requestFocusInWindow(); } }); } catch (IOException e) { SwingUtilities.invokeLater(new Runnable() { public void run() { canvas.errorMessage("couldNotSaveGame"); } }); } } }; t.start(); } /** * Opens a dialog where the user should specify the filename and loads the * game. */ public void loadGame() { Canvas canvas = freeColClient.getCanvas(); File file = canvas.showLoadDialog(FreeCol.getSaveDirectory()); if (file == null) { return; } if (!file.isFile()) { canvas.errorMessage("fileNotFound"); return; } if (!canvas.showConfirmDialog("stopCurrentGame.text", "stopCurrentGame.yes", "stopCurrentGame.no")) { return; } freeColClient.getConnectController().quitGame(true); canvas.removeInGameComponents(); freeColClient.getConnectController().loadGame(file); } /** * Sets the "debug mode" to be active or not. Calls * {@link FreeCol#setInDebugMode(boolean)} and reinitialize the * <code>FreeColMenuBar</code>. * * @param debug Should be set to <code>true</code> in order to enable * debug mode. */ public void setInDebugMode(boolean debug) { FreeCol.setInDebugMode(debug); freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient)); freeColClient.getCanvas().updateJMenuBar(); } /** * Declares independence for the home country. */ public void declareIndependence() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); if (freeColClient.getMyPlayer().getSoL() < 50) { canvas.showInformationMessage("declareIndependence.notMajority", new String[][] { { "%percentage%", Integer.toString(freeColClient.getMyPlayer().getSoL()) } }); return; } if (!canvas.showConfirmDialog("declareIndependence.areYouSure.text", "declareIndependence.areYouSure.yes", "declareIndependence.areYouSure.no")) { return; } Element declareIndependenceElement = Message.createNewRootElement("declareIndependence"); freeColClient.getMyPlayer().declareIndependence(); freeColClient.getActionManager().update(); freeColClient.getClient().sendAndWait(declareIndependenceElement); freeColClient.getMyPlayer().setMonarch(null); canvas.showDeclarationDialog(); } /** * Sends a public chat message. * * @param message The chat message. */ public void sendChat(String message) { Element chatElement = Message.createNewRootElement("chat"); chatElement.setAttribute("message", message); chatElement.setAttribute("privateChat", "false"); freeColClient.getClient().sendAndWait(chatElement); } /** * Sets <code>player</code> as the new <code>currentPlayer</code> of the * game. * * @param currentPlayer The player. */ public void setCurrentPlayer(Player currentPlayer) { logger.finest("Setting current player " + currentPlayer.getName()); Game game = freeColClient.getGame(); game.setCurrentPlayer(currentPlayer); if (freeColClient.getMyPlayer().equals(currentPlayer)) { // Autosave the game: if (freeColClient.getFreeColServer() != null) { final int turnNumber = freeColClient.getGame().getTurn().getNumber(); final int savegamePeriod = freeColClient.getClientOptions().getInteger(ClientOptions.AUTOSAVE_PERIOD); if (savegamePeriod == 1 || (savegamePeriod != 0 && turnNumber % savegamePeriod == 0)) { final String filename = Messages.message("clientOptions.savegames.autosave.fileprefix") + '-' + freeColClient.getGame().getTurn().toSaveGameString() + ".fsg"; File saveGameFile = new File(FreeCol.getAutosaveDirectory(), filename); saveGame(saveGameFile); int generations = freeColClient.getClientOptions().getInteger(ClientOptions.AUTOSAVE_GENERATIONS); if (generations > 0) { allSaveGames.add(saveGameFile); if (allSaveGames.size() > generations) { File fileToDelete = allSaveGames.remove(0); fileToDelete.delete(); } } } } removeUnitsOutsideLOS(); if (currentPlayer.checkEmigrate()) { if (currentPlayer.hasFather(FreeCol.getSpecification().getFoundingFather("model.foundingFather.williamBrewster"))) { emigrateUnitInEurope(freeColClient.getCanvas().showEmigrationPanel()); } else { emigrateUnitInEurope(0); } } if (!freeColClient.isSingleplayer()) { freeColClient.playSound(SfxLibrary.ANTHEM_BASE + currentPlayer.getNationType().getIndex()); } checkTradeRoutesInEurope(); displayModelMessages(true); nextActiveUnit(); } logger.finest("Exiting method setCurrentPlayer()"); } /** * Renames a <code>Renameable</code>. * * @param object The object to rename. */ public void rename(Nameable object) { if (!(object instanceof Ownable) || ((Ownable) object).getOwner() != freeColClient.getMyPlayer()) { return; } String name = null; if (object instanceof Colony) { name = freeColClient.getCanvas().showInputDialog("renameColony.text", object.getName(), "renameColony.yes", "renameColony.no"); } else if (object instanceof Unit) { name = freeColClient.getCanvas().showInputDialog("renameUnit.text", object.getName(), "renameUnit.yes", "renameUnit.no"); } if (name != null) { object.setName(name); Element renameElement = Message.createNewRootElement("rename"); renameElement.setAttribute("nameable", ((FreeColGameObject) object).getID()); renameElement.setAttribute("name", name); freeColClient.getClient().sendAndWait(renameElement); } } /** * Removes the units we cannot see anymore from the map. */ private void removeUnitsOutsideLOS() { Player player = freeColClient.getMyPlayer(); Map map = freeColClient.getGame().getMap(); player.resetCanSeeTiles(); Iterator<Position> tileIterator = map.getWholeMapIterator(); while (tileIterator.hasNext()) { Tile t = map.getTile(tileIterator.next()); if (t != null && !player.canSee(t) && t.getFirstUnit() != null) { if (t.getFirstUnit().getOwner() == player) { logger.warning("Could not see one of my own units!"); } t.disposeAllUnits(); } } player.resetCanSeeTiles(); } /** * Uses the active unit to build a colony. */ public void buildColony() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); GUI gui = freeColClient.getGUI(); Unit unit = freeColClient.getGUI().getActiveUnit(); if (unit == null || !unit.canBuildColony()) { return; } Tile tile = unit.getTile(); if (tile == null) { return; } if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_COLONY_WARNINGS)) { boolean landLocked = true; int lumber = 0; int food = tile.potential(Goods.FOOD); int ore = 0; boolean ownedByEuropeans = false; boolean ownedBySelf = false; boolean ownedByIndians = false; if (tile.secondaryGoods() == Goods.ORE) { ore = 3; } Map map = game.getMap(); Iterator<Position> tileIterator = map.getAdjacentIterator(tile.getPosition()); while (tileIterator.hasNext()) { Tile newTile = map.getTile(tileIterator.next()); if (newTile.isLand()) { lumber += newTile.potential(Goods.LUMBER); food += newTile.potential(Goods.FOOD); ore += newTile.potential(Goods.ORE); Player tileOwner = newTile.getOwner(); if (tileOwner == unit.getOwner()) { if (newTile.getOwningSettlement() != null) { // we are using newTile ownedBySelf = true; } else { Iterator<Position> ownTileIt = map.getAdjacentIterator(newTile.getPosition()); while (ownTileIt.hasNext()) { Colony colony = map.getTile(ownTileIt.next()).getColony(); if (colony != null && colony.getOwner() == unit.getOwner()) { // newTile can be used from an own colony ownedBySelf = true; break; } } } - } else if (tileOwner.isEuropean()) { + } else if (tileOwner != null && tileOwner.isEuropean()) { ownedByEuropeans = true; } else if (tileOwner != null) { ownedByIndians = true; } } else { landLocked = false; } } ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>(); if (landLocked) { messages.add(new ModelMessage(unit, "buildColony.landLocked", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.fish"))); } if (food < 8) { messages.add(new ModelMessage(unit, "buildColony.noFood", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.food"))); } if (lumber < 4) { messages.add(new ModelMessage(unit, "buildColony.noLumber", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.lumber"))); } if (ore < 2) { messages.add(new ModelMessage(unit, "buildColony.noOre", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.ore"))); } if (ownedBySelf) { messages.add(new ModelMessage(unit, "buildColony.ownLand", null, ModelMessage.WARNING)); } if (ownedByEuropeans) { messages.add(new ModelMessage(unit, "buildColony.EuropeanLand", null, ModelMessage.WARNING)); } if (ownedByIndians) { messages.add(new ModelMessage(unit, "buildColony.IndianLand", null, ModelMessage.WARNING)); } if (messages.size() > 0) { ModelMessage[] modelMessages = messages.toArray(new ModelMessage[0]); if (!freeColClient.getCanvas().showConfirmDialog(modelMessages, "buildColony.yes", "buildColony.no")) { return; } } } String name = freeColClient.getCanvas().showInputDialog("nameColony.text", freeColClient.getMyPlayer().getDefaultColonyName(), "nameColony.yes", "nameColony.no"); if (name == null) { // The user cancelled the action. return; } else if (freeColClient.getMyPlayer().getColony(name) != null) { // colony name must be unique (per Player) freeColClient.getCanvas().showInformationMessage("nameColony.notUnique", new String[][] { { "%name%", name } }); return; } Element buildColonyElement = Message.createNewRootElement("buildColony"); buildColonyElement.setAttribute("name", name); buildColonyElement.setAttribute("unit", unit.getID()); Element reply = client.ask(buildColonyElement); if (reply.getTagName().equals("buildColonyConfirmed")) { if (reply.getElementsByTagName("update").getLength() > 0) { Element updateElement = (Element) reply.getElementsByTagName("update").item(0); freeColClient.getInGameInputHandler().update(updateElement); } Colony colony = (Colony) game.getFreeColGameObject(((Element) reply.getChildNodes().item(0)) .getAttribute("ID")); if (colony == null) { colony = new Colony(game, (Element) reply.getChildNodes().item(0)); } else { colony.readFromXMLElement((Element) reply.getChildNodes().item(0)); } changeWorkType(unit, Goods.FOOD); unit.buildColony(colony); for(Unit unitInTile : tile.getUnitList()) { if (unitInTile.canCarryTreasure()) { checkCashInTreasureTrain(unitInTile); } } gui.setActiveUnit(null); gui.setSelectedTile(colony.getTile().getPosition()); } else { // Handle errormessage. } } /** * Moves the active unit in a specified direction. This may result in an * attack, move... action. * * @param direction The direction in which to move the Unit. */ public void moveActiveUnit(int direction) { Unit unit = freeColClient.getGUI().getActiveUnit(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (unit != null) { clearGotoOrders(unit); move(unit, direction); //centers unit if option "always center" is active if(freeColClient.getClientOptions().getBoolean(ClientOptions.ALWAYS_CENTER)){ Position unitPosition = unit.getTile().getPosition(); freeColClient.getGUI().setFocus(unitPosition); } } // else: nothing: There is no active unit that can be moved. } /** * Selects a destination for this unit. Europe and the player's colonies are * valid destinations. * * @param unit The unit for which to select a destination. */ public void selectDestination(Unit unit) { final Player player = freeColClient.getMyPlayer(); Map map = freeColClient.getGame().getMap(); final ArrayList<ChoiceItem> destinations = new ArrayList<ChoiceItem>(); if (unit.isNaval() && unit.getOwner().canMoveToEurope()) { PathNode path = map.findPathToEurope(unit, unit.getTile()); if (path != null) { int turns = path.getTotalTurns(); destinations.add(new ChoiceItem(player.getEurope() + " (" + turns + ")", player.getEurope())); } else if (unit.getTile() != null && (unit.getTile().getType().canSailToEurope() || map.isAdjacentToMapEdge(unit.getTile()))) { destinations.add(new ChoiceItem(player.getEurope() + " (0)", player.getEurope())); } } final Settlement inSettlement = (unit.getTile() != null) ? unit.getTile().getSettlement() : null; // Search for destinations we can reach: map.search(unit, new GoalDecider() { public PathNode getGoal() { return null; } public boolean check(Unit u, PathNode p) { if (p.getTile().getSettlement() != null && p.getTile().getSettlement().getOwner() == player && p.getTile().getSettlement() != inSettlement) { Settlement s = p.getTile().getSettlement(); int turns = p.getTurns(); destinations.add(new ChoiceItem(s.toString() + " (" + turns + ")", s)); } return false; } public boolean hasSubGoals() { return false; } }, Integer.MAX_VALUE); Canvas canvas = freeColClient.getCanvas(); ChoiceItem choice = (ChoiceItem) canvas.showChoiceDialog(Messages.message("selectDestination.text"), Messages .message("selectDestination.cancel"), destinations.toArray()); if (choice == null) { // user aborted return; } Location destination = (Location) choice.getObject(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { setDestination(unit, destination); return; } if (destination instanceof Europe && unit.getTile() != null && (unit.getTile().getType().canSailToEurope() || map.isAdjacentToMapEdge(unit.getTile()))) { moveToEurope(unit); nextActiveUnit(); } else { setDestination(unit, destination); moveToDestination(unit); } } /** * Sets the destination of the given unit and send the server a message for this action. * * @param unit The <code>Unit</code>. * @param destination The <code>Location</code>. * @see Unit#setDestination(Location) */ public void setDestination(Unit unit, Location destination) { Element setDestinationElement = Message.createNewRootElement("setDestination"); setDestinationElement.setAttribute("unit", unit.getID()); if (destination != null) { setDestinationElement.setAttribute("destination", destination.getID()); } unit.setDestination(destination); freeColClient.getClient().sendAndWait(setDestinationElement); } /** * Moves the given unit towards the destination given by * {@link Unit#getDestination()}. * * @param unit The unit to move. */ public void moveToDestination(Unit unit) { final Canvas canvas = freeColClient.getCanvas(); final Map map = freeColClient.getGame().getMap(); final Location destination = unit.getDestination(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { canvas.showInformationMessage("notYourTurn"); return; } // Unit can be waiting to load and continuing with a trade route if (destination.getTile() == unit.getTile()) { // try to load and follow the trade route if (unit.getTradeRoute() != null) { followTradeRoute(unit); } return; } PathNode path; if (destination instanceof Europe) { path = map.findPathToEurope(unit, unit.getTile()); } else { if (destination.getTile() == null) { // Destination is an abandoned colony, for example clearGotoOrders(unit); return; } path = map.findPath(unit, unit.getTile(), destination.getTile()); } if (path == null) { canvas.showInformationMessage("selectDestination.failed", new String[][] { { "%destination%", destination.getLocationName() } }); setDestination(unit, null); return; } boolean knownEnemyOnLastTile = path != null && path.getLastNode() != null && ((path.getLastNode().getTile().getFirstUnit() != null && path.getLastNode().getTile().getFirstUnit() .getOwner() != freeColClient.getMyPlayer()) || (path.getLastNode().getTile().getSettlement() != null && path .getLastNode().getTile().getSettlement().getOwner() != freeColClient.getMyPlayer())); while (path != null) { int mt = unit.getMoveType(path.getDirection()); switch (mt) { case Unit.MOVE: reallyMove(unit, path.getDirection()); break; case Unit.EXPLORE_LOST_CITY_RUMOUR: exploreLostCityRumour(unit, path.getDirection()); if (unit.isDisposed()) return; break; case Unit.MOVE_HIGH_SEAS: if (destination instanceof Europe) { moveToEurope(unit); path = null; } else if (path == path.getLastNode()) { move(unit, path.getDirection()); path = null; } else { reallyMove(unit, path.getDirection()); } break; case Unit.DISEMBARK: disembark(unit, path.getDirection()); path = null; break; default: if (path == path.getLastNode() && mt != Unit.ILLEGAL_MOVE && (mt != Unit.ATTACK || knownEnemyOnLastTile)) { move(unit, path.getDirection()); } else { Tile target = map.getNeighbourOrNull(path.getDirection(), unit.getTile()); int moveCost = unit.getMoveCost(target); if (unit.getMovesLeft() == 0 || (moveCost > unit.getMovesLeft() && (target.getFirstUnit() == null || target.getFirstUnit().getOwner() == unit .getOwner()) && (target.getSettlement() == null || target.getSettlement() .getOwner() == unit.getOwner()))) { // we can't go there now, but we don't want to wake up unit.setMovesLeft(0); nextActiveUnit(); return; } else { // Active unit to show path and permit to move it // manually freeColClient.getGUI().setActiveUnit(unit); return; } } } if (path != null) { path = path.next; } } if (unit.getTile() != null && destination instanceof Europe && map.isAdjacentToMapEdge(unit.getTile())) { moveToEurope(unit); } // we have reached our destination if (unit.getTradeRoute() != null) { if (unit.getCurrentStop().getLocation() != unit.getLocation()) { setDestination(unit, unit.getCurrentStop().getLocation()); moveToDestination(unit); return; } else { followTradeRoute(unit); } } else { setDestination(unit, null); } // Display a "cash in"-dialog if a treasure train have been // moved into a coastal colony: if (unit.canCarryTreasure() && checkCashInTreasureTrain(unit)) { unit = null; } if (unit != null && unit.getMovesLeft() > 0 && unit.getTile() != null) { freeColClient.getGUI().setActiveUnit(unit); } else if (freeColClient.getGUI().getActiveUnit() == unit) { nextActiveUnit(); } return; } private void checkTradeRoutesInEurope() { Europe europe = freeColClient.getMyPlayer().getEurope(); if (europe == null) { return; } List<Unit> units = europe.getUnitList(); for(Unit unit : units) { if (unit.getTradeRoute() != null) { followTradeRoute(unit); } } } private void followTradeRoute(Unit unit) { Stop stop = unit.getCurrentStop(); if (stop == null) { return; } Location location = unit.getLocation(); // TODO: Not all instances handled? if (location instanceof Tile) { logger.finer("Stopped in colony " + unit.getColony().getName()); stopInColony(unit); } else if (location instanceof Europe && unit.isInEurope()) { logger.finer("Stopped in Europe."); stopInEurope(unit); } } private void stopInColony(Unit unit) { Stop stop = unit.getCurrentStop(); Location location = unit.getColony(); int[] exportLevel = unit.getColony().getExportLevel(); // respect the lower limit for TradeRoute GoodsContainer warehouse = location.getGoodsContainer(); if (warehouse == null) { throw new IllegalStateException("No warehouse in a stop's location"); } // unload cargo that should not be on board and complete loaded goods // with less than 100 units ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo(); Iterator<Goods> goodsIterator = unit.getGoodsIterator(); test: while (goodsIterator.hasNext()) { Goods goods = goodsIterator.next(); for (int index = 0; index < goodsTypesToLoad.size(); index++) { GoodsType goodsType = goodsTypesToLoad.get(index); if (goods.getType() == goodsType) { if (goods.getAmount() < 100) { // comlete goods until 100 units // respect the lower limit for TradeRoute int amountPresent = warehouse.getGoodsCount(goodsType) - exportLevel[goodsType.getIndex()]; if (amountPresent > 0) { logger.finest("Automatically loading goods " + goods.getName()); int amountToLoad = Math.min(100 - goods.getAmount(), amountPresent); loadCargo(new Goods(freeColClient.getGame(), location, goods.getType(), amountToLoad), unit); } } // remove item: other items of the same type // may or may not be present goodsTypesToLoad.remove(index); continue test; } } // this type of goods was not in the cargo list: do not // unload more than the warehouse can store int capacity = ((Colony) location).getWarehouseCapacity() - warehouse.getGoodsCount(goods.getType()); if (capacity < goods.getAmount() && !freeColClient.getCanvas().showConfirmDialog(Messages.message("traderoute.warehouseCapacity", "%unit%", unit.getName(), "%colony%", ((Colony) location).getName(), "%amount%", String.valueOf(goods.getAmount() - capacity), "%goods%", goods.getName()), "yes", "no")) { logger.finest("Automatically unloading " + capacity + " " + goods.getName()); unloadCargo(new Goods(freeColClient.getGame(), unit, goods.getType(), capacity)); } else { logger.finest("Automatically unloading " + goods.getAmount() + " " + goods.getName()); unloadCargo(goods); } } // load cargo that should be on board for (GoodsType goodsType : goodsTypesToLoad) { // respect the lower limit for TradeRoute int amountPresent = warehouse.getGoodsCount(goodsType) - exportLevel[goodsType.getIndex()]; if (amountPresent > 0) { if (unit.getSpaceLeft() > 0) { logger.finest("Automatically loading goods " + goodsType.getName()); loadCargo(new Goods(freeColClient.getGame(), location, goodsType, Math.min(amountPresent, 100)), unit); } } } // TODO: do we want to load/unload units as well? // if so, when? updateCurrentStop(unit); } private void updateCurrentStop(Unit unit) { // Set destination to next stop's location Element updateCurrentStopElement = Message.createNewRootElement("updateCurrentStop"); updateCurrentStopElement.setAttribute("unit", unit.getID()); freeColClient.getClient().sendAndWait(updateCurrentStopElement); Stop stop = unit.nextStop(); // go to next stop, unit can already be there waiting to load if (stop != null && stop.getLocation() != unit.getColony()) { if (unit.isInEurope()) { moveToAmerica(unit); } else { moveToDestination(unit); } } } private void stopInEurope(Unit unit) { Stop stop = unit.getCurrentStop(); // unload cargo that should not be on board and complete loaded goods // with less than 100 units ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo(); Iterator<Goods> goodsIterator = unit.getGoodsIterator(); test: while (goodsIterator.hasNext()) { Goods goods = goodsIterator.next(); for (int index = 0; index < goodsTypesToLoad.size(); index++) { GoodsType goodsType = goodsTypesToLoad.get(index); if (goods.getType() == goodsType) { if (goods.getAmount() < 100) { logger.finest("Automatically loading goods " + goods.getName()); buyGoods(goods.getType(), (100 - goods.getAmount()), unit); } // remove item: other items of the same type // may or may not be present goodsTypesToLoad.remove(index); continue test; } } // this type of goods was not in the cargo list logger.finest("Automatically unloading " + goods.getName()); sellGoods(goods); } // load cargo that should be on board for (GoodsType goodsType : goodsTypesToLoad) { if (unit.getSpaceLeft() > 0) { logger.finest("Automatically loading goods " + goodsType.getName()); buyGoods(goodsType, 100, unit); } } // TODO: do we want to load/unload units as well? // if so, when? updateCurrentStop(unit); } /** * Moves the specified unit in a specified direction. This may result in an * attack, move... action. * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ public void move(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } // Be certain the tile we are about to move into has been updated by the // server: // Can be removed if we use 'client.ask' when moving: /* * try { while (game.getMap().getNeighbourOrNull(direction, * unit.getTile()) != null && * game.getMap().getNeighbourOrNull(direction, unit.getTile()).getType() == * Tile.UNEXPLORED) { Thread.sleep(5); } } catch (InterruptedException * ie) {} */ int move = unit.getMoveType(direction); switch (move) { case Unit.MOVE: reallyMove(unit, direction); break; case Unit.ATTACK: attack(unit, direction); break; case Unit.DISEMBARK: disembark(unit, direction); break; case Unit.EMBARK: embark(unit, direction); break; case Unit.MOVE_HIGH_SEAS: moveHighSeas(unit, direction); break; case Unit.ENTER_INDIAN_VILLAGE_WITH_SCOUT: scoutIndianSettlement(unit, direction); break; case Unit.ENTER_INDIAN_VILLAGE_WITH_MISSIONARY: useMissionary(unit, direction); break; case Unit.ENTER_INDIAN_VILLAGE_WITH_FREE_COLONIST: learnSkillAtIndianSettlement(unit, direction); break; case Unit.ENTER_FOREIGN_COLONY_WITH_SCOUT: scoutForeignColony(unit, direction); break; case Unit.ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS: //TODO: unify trade and negotiations Map map = freeColClient.getGame().getMap(); Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement(); if (settlement instanceof Colony) { negotiate(unit, direction); } else { tradeWithSettlement(unit, direction); } break; case Unit.EXPLORE_LOST_CITY_RUMOUR: exploreLostCityRumour(unit, direction); break; case Unit.ILLEGAL_MOVE: freeColClient.playSound(SfxLibrary.ILLEGAL_MOVE); break; default: throw new RuntimeException("unrecognised move: " + move); } // Display a "cash in"-dialog if a treasure train have been moved into a // colony: if (unit.canCarryTreasure()) { checkCashInTreasureTrain(unit); if (unit.isDisposed()) { nextActiveUnit(); } } nextModelMessage(); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getActionManager().update(); freeColClient.getCanvas().updateJMenuBar(); } }); } /** * Initiates a negotiation with a foreign power. The player * creates a DiplomaticTrade with the NegotiationDialog. The * DiplomaticTrade is sent to the other player. If the other * player accepts the offer, the trade is concluded. If not, this * method returns, since the next offer must come from the other * player. * * @param unit an <code>Unit</code> value * @param direction an <code>int</code> value */ private void negotiate(Unit unit, int direction) { Map map = freeColClient.getGame().getMap(); Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement(); Element spyElement = Message.createNewRootElement("spySettlement"); spyElement.setAttribute("unit", unit.getID()); spyElement.setAttribute("direction", String.valueOf(direction)); Element reply = freeColClient.getClient().ask(spyElement); if (reply != null) { NodeList childNodes = reply.getChildNodes(); settlement.readFromXMLElement((Element) childNodes.item(0)); } DiplomaticTrade agreement = freeColClient.getCanvas().showNegotiationDialog(unit, settlement, null); if (agreement != null) { unit.setMovesLeft(0); String nation = agreement.getRecipient().getNationAsString(); reply = null; do { Element diplomaticElement = Message.createNewRootElement("diplomaticTrade"); diplomaticElement.setAttribute("unit", unit.getID()); diplomaticElement.setAttribute("direction", String.valueOf(direction)); diplomaticElement.appendChild(agreement.toXMLElement(null, diplomaticElement.getOwnerDocument())); reply = freeColClient.getClient().ask(diplomaticElement); if (reply != null) { String accept = reply.getAttribute("accept"); if (accept != null && accept.equals("accept")) { freeColClient.getCanvas().showInformationMessage("negotiationDialog.offerAccepted", new String[][] {{"%nation%", nation}}); agreement.makeTrade(); return; } else { Element childElement = (Element) reply.getChildNodes().item(0); DiplomaticTrade proposal = new DiplomaticTrade(freeColClient.getGame(), childElement); agreement = freeColClient.getCanvas().showNegotiationDialog(unit, settlement, proposal); } } else if (agreement.isAccept()) { // We have accepted the contra-proposal agreement.makeTrade(); return; } } while (reply != null); freeColClient.getCanvas().showInformationMessage("negotiationDialog.offerRejected", new String[][] {{"%nation%", nation}}); } } /** * Enter in a foreign colony to spy it. * * @param unit an <code>Unit</code> value * @param direction an <code>int</code> value */ private void spy(Unit unit, int direction) { Game game = freeColClient.getGame(); Colony colony = game.getMap().getNeighbourOrNull(direction, unit.getTile()).getColony(); Element spyElement = Message.createNewRootElement("spySettlement"); spyElement.setAttribute("unit", unit.getID()); spyElement.setAttribute("direction", String.valueOf(direction)); Element reply = freeColClient.getClient().ask(spyElement); if (reply != null) { unit.setMovesLeft(0); NodeList childNodes = reply.getChildNodes(); colony.readFromXMLElement((Element) childNodes.item(0)); Tile tile = colony.getTile(); for(int i=1; i < childNodes.getLength(); i++) { Element unitElement = (Element) childNodes.item(i); Unit foreignUnit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (foreignUnit == null) { foreignUnit = new Unit(game, unitElement); } else { foreignUnit.readFromXMLElement(unitElement); } tile.add(foreignUnit); } freeColClient.getCanvas().showColonyPanel(colony); } } /** * Ask for explore a lost city rumour, and move unit if player accepts * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ private void exploreLostCityRumour(Unit unit, int direction) { if (freeColClient.getCanvas().showConfirmDialog("exploreLostCityRumour.text", "exploreLostCityRumour.yes", "exploreLostCityRumour.no")) { reallyMove(unit, direction); } } /** * Buys the given land from the indians. * * @param tile The land which should be bought from the indians. */ public void buyLand(Tile tile) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Element buyLandElement = Message.createNewRootElement("buyLand"); buyLandElement.setAttribute("tile", tile.getID()); freeColClient.getMyPlayer().buyLand(tile); freeColClient.getClient().sendAndWait(buyLandElement); freeColClient.getCanvas().updateGoldLabel(); } /** * Uses the given unit to trade with a <code>Settlement</code> in the * given direction. * * @param unit The <code>Unit</code> that is a carrier containing goods. * @param direction The direction the unit could move in order to enter the * <code>Settlement</code>. * @exception IllegalArgumentException if the unit is not a carrier, or if * there is no <code>Settlement</code> in the given * direction. * @see Settlement */ private void tradeWithSettlement(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); Client client = freeColClient.getClient(); if (!unit.isCarrier()) { throw new IllegalArgumentException("The unit has to be a carrier in order to trade!"); } Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement(); if (settlement == null) { throw new IllegalArgumentException("No settlement in given direction!"); } if (unit.getGoodsCount() == 0) { canvas.errorMessage("noGoodsOnboard"); return; } Goods goods = (Goods) canvas.showChoiceDialog(Messages.message("tradeProposition.text"), Messages .message("tradeProposition.cancel"), unit.getGoodsIterator()); if (goods == null) { // == Trade aborted by the player. return; } Element tradePropositionElement = Message.createNewRootElement("tradeProposition"); tradePropositionElement.setAttribute("unit", unit.getID()); tradePropositionElement.setAttribute("settlement", settlement.getID()); tradePropositionElement.appendChild(goods.toXMLElement(null, tradePropositionElement.getOwnerDocument())); Element reply = client.ask(tradePropositionElement); while (reply != null) { if (!reply.getTagName().equals("tradePropositionAnswer")) { logger.warning("Illegal reply."); throw new IllegalStateException(); } int gold = Integer.parseInt(reply.getAttribute("gold")); if (gold == NO_NEED_FOR_THE_GOODS) { canvas.showInformationMessage("noNeedForTheGoods", new String[][] { { "%goods%", goods.getName() } }); return; } else if (gold <= NO_TRADE) { canvas.showInformationMessage("noTrade"); return; } else { ChoiceItem[] objects = { new ChoiceItem(Messages.message("trade.takeOffer"), 1), new ChoiceItem(Messages.message("trade.moreGold"), 2), new ChoiceItem(Messages.message("trade.gift").replaceAll("%goods%", goods.getName()), 0), }; String text = Messages.message("trade.text").replaceAll("%nation%", settlement.getOwner().getNationAsString()); text = text.replaceAll("%goods%", goods.getName()); text = text.replaceAll("%gold%", Integer.toString(gold)); ChoiceItem ci = (ChoiceItem) canvas.showChoiceDialog(text, Messages.message("trade.cancel"), objects); if (ci == null) { // == Trade aborted by the player. return; } int ret = ci.getChoice(); if (ret == 1) { tradeWithSettlement(unit, settlement, goods, gold); return; } else if (ret == 0) { deliverGiftToSettlement(unit, settlement, goods); return; } } // Ask for more gold (ret == 2): tradePropositionElement = Message.createNewRootElement("tradeProposition"); tradePropositionElement.setAttribute("unit", unit.getID()); tradePropositionElement.setAttribute("settlement", settlement.getID()); tradePropositionElement.appendChild(goods.toXMLElement(null, tradePropositionElement.getOwnerDocument())); tradePropositionElement.setAttribute("gold", Integer.toString((gold * 11) / 10)); reply = client.ask(tradePropositionElement); } if (reply == null) { logger.warning("reply == null"); } } /** * Trades the given goods. The goods gets transferred from the given * <code>Unit</code> to the given <code>Settlement</code>, and the * {@link Unit#getOwner unit's owner} collects the payment. */ private void tradeWithSettlement(Unit unit, Settlement settlement, Goods goods, int gold) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element tradeElement = Message.createNewRootElement("trade"); tradeElement.setAttribute("unit", unit.getID()); tradeElement.setAttribute("settlement", settlement.getID()); tradeElement.setAttribute("gold", Integer.toString(gold)); tradeElement.appendChild(goods.toXMLElement(null, tradeElement.getOwnerDocument())); Element reply = client.ask(tradeElement); unit.trade(settlement, goods, gold); freeColClient.getCanvas().updateGoldLabel(); if (reply != null) { if (!reply.getTagName().equals("sellProposition")) { logger.warning("Illegal reply."); throw new IllegalStateException(); } ArrayList<Goods> goodsOffered = new ArrayList<Goods>(); NodeList childNodes = reply.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { goodsOffered.add(new Goods(freeColClient.getGame(), (Element) childNodes.item(i))); } Goods goodsToBuy = (Goods) freeColClient.getCanvas().showChoiceDialog(Messages.message("buyProposition.text"), Messages.message("buyProposition.cancel"), goodsOffered.iterator()); if (goodsToBuy != null) { buyFromSettlement(unit, goodsToBuy); } } nextActiveUnit(unit.getTile()); } /** * Uses the given unit to try buying the given goods from an * <code>IndianSettlement</code>. */ private void buyFromSettlement(Unit unit, Goods goods) { Canvas canvas = freeColClient.getCanvas(); Client client = freeColClient.getClient(); Element buyPropositionElement = Message.createNewRootElement("buyProposition"); buyPropositionElement.setAttribute("unit", unit.getID()); buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument())); Element reply = client.ask(buyPropositionElement); while (reply != null) { if (!reply.getTagName().equals("buyPropositionAnswer")) { logger.warning("Illegal reply."); throw new IllegalStateException(); } int gold = Integer.parseInt(reply.getAttribute("gold")); if (gold <= NO_TRADE) { canvas.showInformationMessage("noTrade"); return; } else { ChoiceItem[] objects = { new ChoiceItem(Messages.message("buy.takeOffer"), 1), new ChoiceItem(Messages.message("buy.moreGold"), 2), }; IndianSettlement settlement = (IndianSettlement) goods.getLocation(); String text = Messages.message("buy.text").replaceAll("%nation%", settlement.getOwner().getNationAsString()); text = text.replaceAll("%goods%", goods.getName()); text = text.replaceAll("%gold%", Integer.toString(gold)); ChoiceItem ci = (ChoiceItem) canvas.showChoiceDialog(text, Messages.message("buy.cancel"), objects); if (ci == null) { // == Trade aborted by the player. return; } int ret = ci.getChoice(); if (ret == 1) { buyFromSettlement(unit, goods, gold); return; } } // Ask for more gold (ret == 2): buyPropositionElement = Message.createNewRootElement("buyProposition"); buyPropositionElement.setAttribute("unit", unit.getID()); buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument())); buyPropositionElement.setAttribute("gold", Integer.toString((gold * 9) / 10)); reply = client.ask(buyPropositionElement); } } /** * Trades the given goods. The goods gets transferred from their location * to the given <code>Unit</code>, and the {@link Unit#getOwner unit's owner} * pays the given gold. */ private void buyFromSettlement(Unit unit, Goods goods, int gold) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element buyElement = Message.createNewRootElement("buy"); buyElement.setAttribute("unit", unit.getID()); buyElement.setAttribute("gold", Integer.toString(gold)); buyElement.appendChild(goods.toXMLElement(null, buyElement.getOwnerDocument())); client.ask(buyElement); IndianSettlement settlement = (IndianSettlement) goods.getLocation(); // add goods to settlement in order to client will be able to transfer the goods settlement.add(goods); unit.buy(settlement, goods, gold); freeColClient.getCanvas().updateGoldLabel(); } /** * Trades the given goods. The goods gets transferred from the given * <code>Unit</code> to the given <code>Settlement</code>. */ private void deliverGiftToSettlement(Unit unit, Settlement settlement, Goods goods) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element deliverGiftElement = Message.createNewRootElement("deliverGift"); deliverGiftElement.setAttribute("unit", unit.getID()); deliverGiftElement.setAttribute("settlement", settlement.getID()); deliverGiftElement.appendChild(goods.toXMLElement(null, deliverGiftElement.getOwnerDocument())); client.sendAndWait(deliverGiftElement); unit.deliverGift(settlement, goods); nextActiveUnit(unit.getTile()); } /** * Transfers the gold carried by this unit to the {@link Player owner}. * * @exception IllegalStateException if this unit is not a treasure train. or * if it cannot be cashed in at it's current location. */ private boolean checkCashInTreasureTrain(Unit unit) { Canvas canvas = freeColClient.getCanvas(); if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { canvas.showInformationMessage("notYourTurn"); return false; } Client client = freeColClient.getClient(); if (unit.canCashInTreasureTrain()) { boolean cash; if (unit.getOwner().getEurope() == null) { canvas.showInformationMessage("cashInTreasureTrain.text.independence", new String[][] { { "%nation%", unit.getOwner().getNationAsString() } }); cash = true; } else { int transportFee = unit.getTransportFee(); String message = (transportFee == 0) ? "cashInTreasureTrain.text.free" : "cashInTreasureTrain.text.pay"; cash = canvas.showConfirmDialog(message, "cashInTreasureTrain.yes", "cashInTreasureTrain.no"); } if (cash) { // Inform the server: Element cashInTreasureTrainElement = Message.createNewRootElement("cashInTreasureTrain"); cashInTreasureTrainElement.setAttribute("unit", unit.getID()); client.sendAndWait(cashInTreasureTrainElement); unit.cashInTreasureTrain(); freeColClient.getCanvas().updateGoldLabel(); return true; } } return false; } /** * Actually moves a unit in a specified direction. * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ private void reallyMove(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Client client = freeColClient.getClient(); // Inform the server: Element moveElement = Message.createNewRootElement("move"); moveElement.setAttribute("unit", unit.getID()); moveElement.setAttribute("direction", Integer.toString(direction)); // TODO: server can actually fail (illegal move)! // move before ask to server, to be in new tile in case there is a // rumours unit.move(direction); // client.send(moveElement); Element reply = client.ask(moveElement); freeColClient.getInGameInputHandler().handle(client.getConnection(), reply); if (reply.hasAttribute("movesSlowed")) { // ship slowed unit.setMovesLeft(unit.getMovesLeft() - Integer.parseInt(reply.getAttribute("movesSlowed"))); Unit slowedBy = (Unit) freeColClient.getGame().getFreeColGameObject(reply.getAttribute("slowedBy")); canvas.showInformationMessage("model.unit.slowed", new String[][] {{"%unit%", unit.getName()}, {"%enemyUnit%", slowedBy.getName()}, {"%enemyNation%", slowedBy.getOwner().getNationAsString()}}); } // set location again in order to meet with people player don't see // before move if (!unit.isDisposed()) { unit.setLocation(unit.getTile()); } if (unit.getTile().isLand() && !unit.getOwner().isNewLandNamed()) { String newLandName = canvas.showInputDialog("newLand.text", unit.getOwner().getNewLandName(), "newLand.yes", null); unit.getOwner().setNewLandName(newLandName); Element setNewLandNameElement = Message.createNewRootElement("setNewLandName"); setNewLandNameElement.setAttribute("newLandName", newLandName); client.sendAndWait(setNewLandNameElement); canvas.showEventDialog(EventPanel.FIRST_LANDING); } if (unit.getTile().getSettlement() != null && unit.isCarrier() && unit.getTradeRoute() == null && (unit.getDestination() == null || unit.getDestination().getTile() == unit.getTile())) { canvas.showColonyPanel((Colony) unit.getTile().getSettlement()); } else if (unit.getMovesLeft() <= 0 || unit.isDisposed()) { nextActiveUnit(unit.getTile()); } nextModelMessage(); } /** * Ask for attack or demand a tribute when attacking an indian settlement, * attack in other cases * * @param unit The unit to perform the attack. * @param direction The direction in which to attack. */ private void attack(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Tile target = freeColClient.getGame().getMap().getNeighbourOrNull(direction, unit.getTile()); if (target.getSettlement() != null && target.getSettlement() instanceof IndianSettlement && unit.isArmed()) { IndianSettlement settlement = (IndianSettlement) target.getSettlement(); switch (freeColClient.getCanvas().showArmedUnitIndianSettlementDialog(settlement)) { case FreeColDialog.SCOUT_INDIAN_SETTLEMENT_ATTACK: if (confirmHostileAction(unit, target) && confirmPreCombat(unit, target)) { reallyAttack(unit, direction); } return; case FreeColDialog.SCOUT_INDIAN_SETTLEMENT_CANCEL: return; case FreeColDialog.SCOUT_INDIAN_SETTLEMENT_TRIBUTE: Element demandMessage = Message.createNewRootElement("armedUnitDemandTribute"); demandMessage.setAttribute("unit", unit.getID()); demandMessage.setAttribute("direction", Integer.toString(direction)); Element reply = freeColClient.getClient().ask(demandMessage); if (reply != null && reply.getTagName().equals("armedUnitDemandTributeResult")) { String result = reply.getAttribute("result"); if (result.equals("agree")) { String amount = reply.getAttribute("amount"); unit.getOwner().modifyGold(Integer.parseInt(amount)); freeColClient.getCanvas().updateGoldLabel(); freeColClient.getCanvas().showInformationMessage("scoutSettlement.tributeAgree", new String[][] { { "%replace%", amount } }); } else if (result.equals("disagree")) { freeColClient.getCanvas().showInformationMessage("scoutSettlement.tributeDisagree"); } unit.setMovesLeft(0); } else { logger.warning("Server gave an invalid reply to an armedUnitDemandTribute message"); return; } nextActiveUnit(unit.getTile()); break; default: logger.warning("Incorrect response returned from Canvas.showArmedUnitIndianSettlementDialog()"); return; } } else { if (confirmHostileAction(unit, target) && confirmPreCombat(unit, target)) { reallyAttack(unit, direction); } return; } } /** * Check if an attack results in a transition from peace or cease fire to * war and, if so, warn the player. * * @param attacker The potential attacker. * @param target The target tile. * @return true to attack, false to abort. */ private boolean confirmHostileAction(Unit attacker, Tile target) { if (!attacker.hasAbility("model.ability.piracy")) { Player enemy; if (target.getSettlement() != null) { enemy = target.getSettlement().getOwner(); } else { Unit defender = target.getDefendingUnit(attacker); if (defender == null) { logger.warning("Attacking, but no defender - will try!"); return true; } if (defender.hasAbility("model.ability.piracy")) { // Privateers can be attacked and remain at peace return true; } enemy = defender.getOwner(); } switch (attacker.getOwner().getStance(enemy)) { case Player.CEASE_FIRE: return freeColClient.getCanvas().showConfirmDialog("model.diplomacy.attack.ceaseFire", "model.diplomacy.attack.confirm", "cancel", new String[][] { { "%replace%", enemy.getNationAsString() } }); case Player.PEACE: return freeColClient.getCanvas().showConfirmDialog("model.diplomacy.attack.peace", "model.diplomacy.attack.confirm", "cancel", new String[][] { { "%replace%", enemy.getNationAsString() } }); case Player.ALLIANCE: freeColClient.playSound(SfxLibrary.ILLEGAL_MOVE); freeColClient.getCanvas().showInformationMessage("model.diplomacy.attack.alliance", new String[][] { { "%replace%", enemy.getNationAsString() } }); return false; case Player.WAR: logger.finest("Player at war, no confirmation needed"); return true; default: logger.warning("Unknown stance " + attacker.getOwner().getStance(enemy)); return true; } } else { // Privateers can attack and remain at peace return true; } } /** * If the client options include a pre-combat dialog, allow the user to view * the odds and possibly cancel the attack. * * @param attacker The attacker. * @param target The target tile. * @return true to attack, false to abort. */ private boolean confirmPreCombat(Unit attacker, Tile target) { if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_PRECOMBAT)) { Settlement settlementOrNull = target.getSettlement(); // Don't tell the player how a settlement is defended! Unit defenderOrNull = settlementOrNull != null ? null : target.getDefendingUnit(attacker); return freeColClient.getCanvas().showPreCombatDialog(attacker, defenderOrNull, settlementOrNull); } return true; } /** * Performs an attack in a specified direction. Note that the server handles * the attack calculations here. * * @param unit The unit to perform the attack. * @param direction The direction in which to attack. */ private void reallyAttack(Unit unit, int direction) { Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); Tile target = game.getMap().getNeighbourOrNull(direction, unit.getTile()); if (unit.hasAbility("model.ability.bombard") || unit.isNaval()) { freeColClient.playSound(SfxLibrary.ARTILLERY); } Element attackElement = Message.createNewRootElement("attack"); attackElement.setAttribute("unit", unit.getID()); attackElement.setAttribute("direction", Integer.toString(direction)); // Get the result of the attack from the server: Element attackResultElement = client.ask(attackElement); if (attackResultElement != null) { int result = Integer.parseInt(attackResultElement.getAttribute("result")); int plunderGold = Integer.parseInt(attackResultElement.getAttribute("plunderGold")); // If a successful attack against a colony, we need to update the // tile: Element utElement = getChildElement(attackResultElement, Tile.getXMLElementTagName()); if (utElement != null) { Tile updateTile = (Tile) game.getFreeColGameObject(utElement.getAttribute("ID")); updateTile.readFromXMLElement(utElement); } // If there are captured goods, add to unit NodeList capturedGoods = attackResultElement.getElementsByTagName("capturedGoods"); for (int i = 0; i < capturedGoods.getLength(); ++i) { Element goods = (Element) capturedGoods.item(i); GoodsType type = FreeCol.getSpecification().getGoodsType(Integer.parseInt(goods.getAttribute("type"))); int amount = Integer.parseInt(goods.getAttribute("amount")); unit.getGoodsContainer().addGoods(type, amount); } // Get the defender: Element unitElement = getChildElement(attackResultElement, Unit.getXMLElementTagName()); Unit defender; if (unitElement != null) { defender = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (defender == null) { defender = new Unit(game, unitElement); } else { defender.readFromXMLElement(unitElement); } defender.setLocation(target); } else { // TODO: Erik - ensure this cannot happen! logger.log(Level.SEVERE, "Server reallyAttack did not return a defender!"); defender = target.getDefendingUnit(unit); if (defender == null) { throw new IllegalStateException("No defender available!"); } } if (!unit.isNaval()) { Unit winner; if (result >= Unit.ATTACK_EVADES) { winner = unit; } else { winner = defender; } if (winner.isArmed()) { if (winner.isMounted()) { if (winner.getType() == Unit.BRAVE) { freeColClient.playSound(SfxLibrary.MUSKETSHORSES); } else { freeColClient.playSound(SfxLibrary.DRAGOON); } } else { freeColClient.playSound(SfxLibrary.ATTACK); } } else if (winner.isMounted()) { freeColClient.playSound(SfxLibrary.DRAGOON); } } else { if (result >= Unit.ATTACK_GREAT_WIN || result <= Unit.ATTACK_GREAT_LOSS) { freeColClient.playSound(SfxLibrary.SUNK); } } try { unit.attack(defender, result, plunderGold); } catch (Exception e) { // Ignore the exception (the update further down will fix any // problems). LogRecord lr = new LogRecord(Level.WARNING, "Exception in reallyAttack"); lr.setThrown(e); logger.log(lr); } // Get the convert: Element convertElement = getChildElement(attackResultElement, "convert"); Unit convert; if (convertElement != null) { unitElement = (Element) convertElement.getFirstChild(); convert = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (convert == null) { convert = new Unit(game, unitElement); } else { convert.readFromXMLElement(unitElement); } convert.setLocation(convert.getLocation()); String nation = defender.getOwner().getNationAsString(); ModelMessage message = new ModelMessage(convert, "model.unit.newConvertFromAttack", new String[][] {{"%nation%", nation}}, ModelMessage.UNIT_ADDED); } if (defender.canCarryTreasure() && result >= Unit.ATTACK_WIN) { checkCashInTreasureTrain(defender); } if (!defender.isDisposed() && ((result == Unit.ATTACK_DONE_SETTLEMENT && unitElement != null) || defender.getLocation() == null || !defender.isVisibleTo(freeColClient.getMyPlayer()))) { defender.dispose(); } Element updateElement = getChildElement(attackResultElement, "update"); if (updateElement != null) { freeColClient.getInGameInputHandler().handle(client.getConnection(), updateElement); } if (unit.getMovesLeft() <= 0) { nextActiveUnit(unit.getTile()); } freeColClient.getCanvas().refresh(); } else { logger.log(Level.SEVERE, "Server returned null from reallyAttack!"); } } /** * Disembarks the specified unit in a specified direction. * * @param unit The unit to be disembarked. * @param direction The direction in which to disembark the Unit. */ private void disembark(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } // Make sure it is a carrier. if (!unit.isCarrier()) { throw new RuntimeException("Programming error: disembark called on non carrier."); } // Check if user wants to disembark. Canvas canvas = freeColClient.getCanvas(); if (!canvas.showConfirmDialog("disembark.text", "disembark.yes", "disembark.no")) { return; } Game game = freeColClient.getGame(); Tile destinationTile = game.getMap().getNeighbourOrNull(direction, unit.getTile()); unit.setStateToAllChildren(Unit.ACTIVE); // Disembark only the first unit. Unit toDisembark = unit.getFirstUnit(); if (toDisembark.getMovesLeft() > 0) { if (destinationTile.hasLostCityRumour()) { exploreLostCityRumour(toDisembark, direction); } else { reallyMove(toDisembark, direction); } } } /** * Embarks the specified unit in a specified direction. * * @param unit The unit to be embarked. * @param direction The direction in which to embark the Unit. */ private void embark(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Game game = freeColClient.getGame(); Client client = freeColClient.getClient(); GUI gui = freeColClient.getGUI(); Canvas canvas = freeColClient.getCanvas(); Tile destinationTile = game.getMap().getNeighbourOrNull(direction, unit.getTile()); Unit destinationUnit = null; if (destinationTile.getUnitCount() == 1) { destinationUnit = destinationTile.getFirstUnit(); } else { ArrayList<Unit> choices = new ArrayList<Unit>(); for (Unit nextUnit : destinationTile.getUnitList()) { if (nextUnit.getSpaceLeft() >= unit.getTakeSpace()) { choices.add(nextUnit); } else { break; } } if (choices.size() == 1) { destinationUnit = choices.get(0); } else if (choices.size() == 0) { throw new IllegalStateException(); } else { destinationUnit = (Unit) canvas.showChoiceDialog(Messages.message("embark.text"), Messages .message("embark.cancel"), choices.iterator()); if (destinationUnit == null) { // == user cancelled return; } } } unit.embark(destinationUnit); if (destinationUnit.getMovesLeft() > 0) { gui.setActiveUnit(destinationUnit); } else { nextActiveUnit(destinationUnit.getTile()); } Element embarkElement = Message.createNewRootElement("embark"); embarkElement.setAttribute("unit", unit.getID()); embarkElement.setAttribute("direction", Integer.toString(direction)); embarkElement.setAttribute("embarkOnto", destinationUnit.getID()); client.sendAndWait(embarkElement); } /** * Boards a specified unit onto a carrier. The carrier should be at the same * tile as the boarding unit. * * @param unit The unit who is going to board the carrier. * @param carrier The carrier. * @return <i>true</i> if the <code>unit</code> actually gets on the * <code>carrier</code>. */ public boolean boardShip(Unit unit, Unit carrier) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); throw new IllegalStateException("Not your turn."); } if (unit == null) { logger.warning("unit == null"); return false; } if (carrier == null) { logger.warning("Trying to load onto a non-existent carrier."); return false; } Client client = freeColClient.getClient(); if (unit.isCarrier()) { logger.warning("Trying to load a carrier onto another carrier."); return false; } freeColClient.playSound(SfxLibrary.LOAD_CARGO); Element boardShipElement = Message.createNewRootElement("boardShip"); boardShipElement.setAttribute("unit", unit.getID()); boardShipElement.setAttribute("carrier", carrier.getID()); unit.boardShip(carrier); client.sendAndWait(boardShipElement); return true; } /** * Clear the speciality of a <code>Unit</code>. That is, makes it a * <code>Unit.FREE_COLONIST</code>. * * @param unit The <code>Unit</code> to clear the speciality of. */ public void clearSpeciality(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element clearSpecialityElement = Message.createNewRootElement("clearSpeciality"); clearSpecialityElement.setAttribute("unit", unit.getID()); unit.clearSpeciality(); client.sendAndWait(clearSpecialityElement); } /** * Leave a ship. This method should only be invoked if the ship is in a * harbour. * * @param unit The unit who is going to leave the ship where it is located. */ public void leaveShip(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); unit.leaveShip(); Element leaveShipElement = Message.createNewRootElement("leaveShip"); leaveShipElement.setAttribute("unit", unit.getID()); client.sendAndWait(leaveShipElement); } /** * Loads a cargo onto a carrier. * * @param goods The goods which are going aboard the carrier. * @param carrier The carrier. */ public void loadCargo(Goods goods, Unit carrier) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (carrier == null) { throw new NullPointerException(); } freeColClient.playSound(SfxLibrary.LOAD_CARGO); Client client = freeColClient.getClient(); goods.adjustAmount(); Element loadCargoElement = Message.createNewRootElement("loadCargo"); loadCargoElement.setAttribute("carrier", carrier.getID()); loadCargoElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), loadCargoElement .getOwnerDocument())); goods.loadOnto(carrier); client.sendAndWait(loadCargoElement); } /** * Unload cargo. This method should only be invoked if the unit carrying the * cargo is in a harbour. * * @param goods The goods which are going to leave the ship where it is * located. */ public void unloadCargo(Goods goods) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); goods.adjustAmount(); Element unloadCargoElement = Message.createNewRootElement("unloadCargo"); unloadCargoElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), unloadCargoElement .getOwnerDocument())); goods.unload(); client.sendAndWait(unloadCargoElement); } /** * Buys goods in Europe. The amount of goods is adjusted if there is lack of * space in the <code>carrier</code>. * * @param type The type of goods to buy. * @param amount The amount of goods to buy. * @param carrier The carrier. */ public void buyGoods(GoodsType type, int amount, Unit carrier) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Player myPlayer = freeColClient.getMyPlayer(); Canvas canvas = freeColClient.getCanvas(); if (carrier == null) { throw new NullPointerException(); } if (carrier.getOwner() != myPlayer || (carrier.getSpaceLeft() <= 0 && (carrier.getGoodsContainer().getGoodsCount(type) % 100 == 0))) { return; } if (carrier.getSpaceLeft() <= 0) { amount = Math.min(amount, 100 - carrier.getGoodsContainer().getGoodsCount(type) % 100); } if (myPlayer.getMarket().getBidPrice(type, amount) > myPlayer.getGold()) { canvas.errorMessage("notEnoughGold"); return; } freeColClient.playSound(SfxLibrary.LOAD_CARGO); Element buyGoodsElement = Message.createNewRootElement("buyGoods"); buyGoodsElement.setAttribute("carrier", carrier.getID()); buyGoodsElement.setAttribute("type", Integer.toString(type.getIndex())); buyGoodsElement.setAttribute("amount", Integer.toString(amount)); carrier.buyGoods(type, amount); freeColClient.getCanvas().updateGoldLabel(); client.sendAndWait(buyGoodsElement); } /** * Sells goods in Europe. * * @param goods The goods to be sold. */ public void sellGoods(Goods goods) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Player player = freeColClient.getMyPlayer(); freeColClient.playSound(SfxLibrary.SELL_CARGO); goods.adjustAmount(); Element sellGoodsElement = Message.createNewRootElement("sellGoods"); sellGoodsElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), sellGoodsElement .getOwnerDocument())); player.getMarket().sell(goods, player); freeColClient.getCanvas().updateGoldLabel(); client.sendAndWait(sellGoodsElement); } /** * Sets the export settings of the custom house. * * @param colony The colony with the custom house. * @param goodsType The goods for which to set the settings. */ public void setGoodsLevels(Colony colony, GoodsType goodsType) { Client client = freeColClient.getClient(); boolean export = colony.getExports(goodsType); int exportLevel = colony.getExportLevel()[goodsType.getIndex()]; int highLevel = colony.getHighLevel()[goodsType.getIndex()]; int lowLevel = colony.getLowLevel()[goodsType.getIndex()]; Element setGoodsLevelsElement = Message.createNewRootElement("setGoodsLevels"); setGoodsLevelsElement.setAttribute("colony", colony.getID()); setGoodsLevelsElement.setAttribute("goods", String.valueOf(goodsType.getIndex())); setGoodsLevelsElement.setAttribute("export", String.valueOf(export)); setGoodsLevelsElement.setAttribute("exportLevel", String.valueOf(exportLevel)); setGoodsLevelsElement.setAttribute("highLevel", String.valueOf(highLevel)); setGoodsLevelsElement.setAttribute("lowLevel", String.valueOf(lowLevel)); client.sendAndWait(setGoodsLevelsElement); } /** * Equips or unequips a <code>Unit</code> with a certain type of * <code>Goods</code>. * * @param unit The <code>Unit</code>. * @param type The type of <code>Goods</code>. * @param amount How many of these goods the unit should have. */ public void equipUnit(Unit unit, GoodsType type, int amount) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Player myPlayer = freeColClient.getMyPlayer(); Unit carrier = null; if (unit.getLocation() instanceof Unit) { carrier = (Unit) unit.getLocation(); leaveShip(unit); } Element equipUnitElement = Message.createNewRootElement("equipunit"); equipUnitElement.setAttribute("unit", unit.getID()); equipUnitElement.setAttribute("type", Integer.toString(type.getIndex())); equipUnitElement.setAttribute("amount", Integer.toString(amount)); if (type == Goods.CROSSES) { unit.setMissionary((amount > 0)); } else if (type == Goods.MUSKETS) { if (unit.isInEurope()) { if (!myPlayer.canTrade(type)) { payArrears(type); if (!myPlayer.canTrade(type)) { return; // The user cancelled the action. } } } unit.setArmed((amount > 0)); // So give them muskets if the // amount we want is greater than // zero. } else if (type == Goods.HORSES) { if (unit.isInEurope()) { if (!myPlayer.canTrade(type)) { payArrears(type); if (!myPlayer.canTrade(type)) { return; // The user cancelled the action. } } } unit.setMounted((amount > 0)); // As above. } else if (type == Goods.TOOLS) { if (unit.isInEurope()) { if (!myPlayer.canTrade(type)) { payArrears(type); if (!myPlayer.canTrade(type)) { return; // The user cancelled the action. } } } int actualAmount = amount; if ((actualAmount % 20) > 0) { logger.warning("Trying to set a number of tools that is not a multiple of 20."); actualAmount -= (actualAmount % 20); } unit.setNumberOfTools(actualAmount); } else { logger.warning("Invalid type of goods to equip."); return; } freeColClient.getCanvas().updateGoldLabel(); client.sendAndWait(equipUnitElement); if (unit.getLocation() instanceof Colony || unit.getLocation() instanceof Building || unit.getLocation() instanceof ColonyTile) { putOutsideColony(unit); } else if (carrier != null) { boardShip(unit, carrier); } } /** * Moves a <code>Unit</code> to a <code>WorkLocation</code>. * * @param unit The <code>Unit</code>. * @param workLocation The <code>WorkLocation</code>. */ public void work(Unit unit, WorkLocation workLocation) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element workElement = Message.createNewRootElement("work"); workElement.setAttribute("unit", unit.getID()); workElement.setAttribute("workLocation", workLocation.getID()); unit.work(workLocation); client.sendAndWait(workElement); } /** * Puts the specified unit outside the colony. * * @param unit The <code>Unit</code> * @return <i>true</i> if the unit was successfully put outside the colony. */ public boolean putOutsideColony(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); throw new IllegalStateException("Not your turn."); } Element putOutsideColonyElement = Message.createNewRootElement("putOutsideColony"); putOutsideColonyElement.setAttribute("unit", unit.getID()); unit.putOutsideColony(); Client client = freeColClient.getClient(); client.sendAndWait(putOutsideColonyElement); return true; } /** * Changes the work type of this <code>Unit</code>. * * @param unit The <code>Unit</code> * @param workType The new <code>GoodsType</code> to produce. */ public void changeWorkType(Unit unit, GoodsType workType) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Element changeWorkTypeElement = Message.createNewRootElement("changeWorkType"); changeWorkTypeElement.setAttribute("unit", unit.getID()); changeWorkTypeElement.setAttribute("workType", Integer.toString(workType.getIndex())); unit.setWorkType(workType); client.sendAndWait(changeWorkTypeElement); } /** * Assigns a unit to a teacher <code>Unit</code>. * * @param student an <code>Unit</code> value * @param teacher an <code>Unit</code> value */ public void assignTeacher(Unit student, Unit teacher) { Player player = freeColClient.getMyPlayer(); if (freeColClient.getGame().getCurrentPlayer() != player) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (!student.canBeStudent(teacher)) { throw new IllegalStateException("Unit can not be student!"); } if (!teacher.getColony().canTrain(teacher)) { throw new IllegalStateException("Unit can not be teacher!"); } if (student.getOwner() != player) { throw new IllegalStateException("Student is not your unit!"); } if (teacher.getOwner() != player) { throw new IllegalStateException("Teacher is not your unit!"); } if (student.getColony() != teacher.getColony()) { throw new IllegalStateException("Student and teacher are not in the same colony!"); } if (!(student.getLocation() instanceof WorkLocation)) { throw new IllegalStateException("Student is not in a WorkLocation!"); } Element assignTeacherElement = Message.createNewRootElement("assignTeacher"); assignTeacherElement.setAttribute("student", student.getID()); assignTeacherElement.setAttribute("teacher", teacher.getID()); if (student.getTeacher() != null) { student.getTeacher().setStudent(null); } student.setTeacher(teacher); if (teacher.getStudent() != null) { teacher.getStudent().setTeacher(null); } teacher.setStudent(student); freeColClient.getClient().sendAndWait(assignTeacherElement); } /** * Changes the current construction project of a <code>Colony</code>. * * @param colony The <code>Colony</code> * @param type The new type of building to build. */ public void setCurrentlyBuilding(Colony colony, int type) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); colony.setCurrentlyBuilding(type); Element setCurrentlyBuildingElement = Message.createNewRootElement("setCurrentlyBuilding"); setCurrentlyBuildingElement.setAttribute("colony", colony.getID()); setCurrentlyBuildingElement.setAttribute("type", Integer.toString(type)); client.sendAndWait(setCurrentlyBuildingElement); } /** * Changes the state of this <code>Unit</code>. * * @param unit The <code>Unit</code> * @param state The state of the unit. */ public void changeState(Unit unit, int state) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); Canvas canvas = freeColClient.getCanvas(); if (!(unit.checkSetState(state))) { return; // Don't bother (and don't log, this is not exceptional) } if (state == Unit.IMPROVING) { int price = unit.getOwner().getLandPrice(unit.getTile()); if (price > 0) { Player nation = unit.getTile().getOwner(); ChoiceItem[] choices = { new ChoiceItem(Messages.message("indianLand.pay" ,"%amount%", Integer.toString(price)), 1), new ChoiceItem(Messages.message("indianLand.take"), 2) }; ChoiceItem ci = (ChoiceItem) canvas.showChoiceDialog(Messages.message("indianLand.text", "%player%", nation.getName()), Messages.message("indianLand.cancel"), choices); if (ci == null) { return; } else if (ci.getChoice() == 1) { if (price > freeColClient.getMyPlayer().getGold()) { canvas.errorMessage("notEnoughGold"); return; } buyLand(unit.getTile()); } } } else if (state == Unit.FORTIFYING && unit.isOffensiveUnit() && !unit.hasAbility("model.ability.piracy")) { // check if it's going to occupy a work tile Tile tile = unit.getTile(); if (tile != null && tile.getOwningSettlement() != null) { // check stance with settlement's owner Player myPlayer = unit.getOwner(); Player enemy = tile.getOwningSettlement().getOwner(); if (myPlayer != enemy && myPlayer.getStance(enemy) != Player.ALLIANCE && !confirmHostileAction(unit, tile.getOwningSettlement().getTile())) { // player has aborted return; } } } unit.setState(state); // NOTE! The call to nextActiveUnit below can lead to the dreaded // "not your turn" error, so let's finish networking first. Element changeStateElement = Message.createNewRootElement("changeState"); changeStateElement.setAttribute("unit", unit.getID()); changeStateElement.setAttribute("state", Integer.toString(state)); client.sendAndWait(changeStateElement); if (!freeColClient.getCanvas().isShowingSubPanel() && (unit.getMovesLeft() == 0 || unit.getState() == Unit.SENTRY)) { nextActiveUnit(); } else { freeColClient.getCanvas().refresh(); } } /** * Clears the orders of the given <code>Unit</code> The orders are cleared * by making the unit {@link Unit#ACTIVE} and setting a null destination * * @param unit The <code>Unit</code>. */ public void clearOrders(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (unit == null) { return; } /* * report to server, in order not to restore destination if it's * received in a update message */ clearGotoOrders(unit); assignTradeRoute(unit, TradeRoute.NO_TRADE_ROUTE); changeState(unit, Unit.ACTIVE); } /** * Clears the orders of the given <code>Unit</code>. The orders are * cleared by making the unit {@link Unit#ACTIVE}. * * @param unit The <code>Unit</code>. */ public void clearGotoOrders(Unit unit) { if (unit == null) { return; } /* * report to server, in order not to restore destination if it's * received in a update message */ if (unit.getDestination() != null) setDestination(unit, null); } /** * Moves the specified unit in the "high seas" in a specified direction. * This may result in an ordinary move, no move or a move to europe. * * @param unit The unit to be moved. * @param direction The direction in which to move the Unit. */ private void moveHighSeas(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); // getTile() == null : Unit in europe if (!unit.isAlreadyOnHighSea() && (unit.getTile() == null || canvas.showConfirmDialog("highseas.text", "highseas.yes", "highseas.no"))) { moveToEurope(unit); nextActiveUnit(); } else if (map.getNeighbourOrNull(direction, unit.getTile()) != null) { reallyMove(unit, direction); } } /** * Moves the specified free colonist into an Indian settlement to learn a * skill. Of course, the colonist won't physically get into the village, it * will just stay where it is and gain the skill. * * @param unit The unit to learn the skill. * @param direction The direction in which the Indian settlement lies. */ private void learnSkillAtIndianSettlement(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile()) .getSettlement(); if (settlement.getLearnableSkill() != null || !settlement.hasBeenVisited()) { unit.setMovesLeft(0); String skillName; Element askSkill = Message.createNewRootElement("askSkill"); askSkill.setAttribute("unit", unit.getID()); askSkill.setAttribute("direction", Integer.toString(direction)); Element reply = client.ask(askSkill); UnitType skill = null; if (reply.getTagName().equals("provideSkill")) { String skillStr = reply.getAttribute("skill"); if (skillStr == null) { skillName = null; } else { skill = FreeCol.getSpecification().getUnitType(Integer.parseInt(skillStr)); skillName = skill.getName(); } } else { logger.warning("Server gave an invalid reply to an askSkill message"); return; } settlement.setLearnableSkill(skill); settlement.setVisited(); if (skillName == null) { canvas.errorMessage("indianSettlement.noMoreSkill"); } else if (!unit.getUnitType().canLearnFromNatives(skill)) { canvas.showInformationMessage("indianSettlement.cantLearnSkill", new String[][] { {"%unit%", unit.getName()}, {"%skill%", skillName} }); } else { Element learnSkill = Message.createNewRootElement("learnSkillAtSettlement"); learnSkill.setAttribute("unit", unit.getID()); learnSkill.setAttribute("direction", Integer.toString(direction)); if (!canvas.showConfirmDialog("learnSkill.text", "learnSkill.yes", "learnSkill.no", new String[][] { { "%replace%", skillName } })) { // the player declined to learn the skill learnSkill.setAttribute("action", "cancel"); } Element reply2 = freeColClient.getClient().ask(learnSkill); String result = reply2.getAttribute("result"); if (result.equals("die")) { unit.dispose(); canvas.showInformationMessage("learnSkill.die"); } else if (result.equals("leave")) { canvas.showInformationMessage("learnSkill.leave"); } else if (result.equals("success")) { unit.setType(skill); if (!settlement.isCapital()) settlement.setLearnableSkill(null); } else if (result.equals("cancelled")) { // do nothing } else { logger.warning("Server gave an invalid reply to an learnSkillAtSettlement message"); } } } else if (unit.getDestination() != null) { setDestination(unit, null); } nextActiveUnit(unit.getTile()); } /** * Ask for spy the foreign colony, negotiate with the foreign power * or attack the colony * * @param unit The unit that will spy, negotiate or attack. * @param direction The direction in which the foreign colony lies. */ private void scoutForeignColony(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); Tile tile = map.getNeighbourOrNull(direction, unit.getTile()); Colony colony = tile.getColony(); int userAction = canvas.showScoutForeignColonyDialog(colony, unit); switch (userAction) { case FreeColDialog.SCOUT_FOREIGN_COLONY_CANCEL: break; case FreeColDialog.SCOUT_FOREIGN_COLONY_ATTACK: attack(unit, direction); break; case FreeColDialog.SCOUT_FOREIGN_COLONY_NEGOTIATE: negotiate(unit, direction); break; case FreeColDialog.SCOUT_FOREIGN_COLONY_SPY: spy(unit, direction); break; default: logger.warning("Incorrect response returned from Canvas.showScoutForeignColonyDialog()"); return; } } /** * Moves the specified scout into an Indian settlement to speak with the * chief or demand a tribute etc. Of course, the scout won't physically get * into the village, it will just stay where it is. * * @param unit The unit that will speak, attack or ask tribute. * @param direction The direction in which the Indian settlement lies. */ private void scoutIndianSettlement(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); Tile tile = map.getNeighbourOrNull(direction, unit.getTile()); IndianSettlement settlement = (IndianSettlement) tile.getSettlement(); // The scout loses his moves because the skill data and tradeable goods // data is fetched // from the server and the moves are the price we have to pay to obtain // that data. unit.setMovesLeft(0); Element scoutMessage = Message.createNewRootElement("scoutIndianSettlement"); scoutMessage.setAttribute("unit", unit.getID()); scoutMessage.setAttribute("direction", Integer.toString(direction)); scoutMessage.setAttribute("action", "basic"); Element reply = client.ask(scoutMessage); if (reply.getTagName().equals("scoutIndianSettlementResult")) { Specification spec = FreeCol.getSpecification(); UnitType skill = null; String skillStr = reply.getAttribute("skill"); if (skillStr != null) { skill = spec.getUnitType(Integer.parseInt(skillStr)); } settlement.setLearnableSkill(skill); settlement.setWantedGoods(0, Integer.parseInt(reply.getAttribute("highlyWantedGoods"))); settlement.setWantedGoods(1, Integer.parseInt(reply.getAttribute("wantedGoods1"))); settlement.setWantedGoods(2, Integer.parseInt(reply.getAttribute("wantedGoods2"))); settlement.setVisited(); } else { logger.warning("Server gave an invalid reply to an askSkill message"); return; } int userAction = canvas.showScoutIndianSettlementDialog(settlement); switch (userAction) { case FreeColDialog.SCOUT_INDIAN_SETTLEMENT_ATTACK: scoutMessage.setAttribute("action", "attack"); // The movesLeft has been set to 0 when the scout initiated its // action.If it wants to attack then it can and it will need some // moves to do it. unit.setMovesLeft(1); client.sendAndWait(scoutMessage); // TODO: Check if this dialog is needed, one has just been displayed if (confirmPreCombat(unit, tile)) { reallyAttack(unit, direction); } return; case FreeColDialog.SCOUT_INDIAN_SETTLEMENT_CANCEL: scoutMessage.setAttribute("action", "cancel"); client.sendAndWait(scoutMessage); return; case FreeColDialog.SCOUT_INDIAN_SETTLEMENT_SPEAK: scoutMessage.setAttribute("action", "speak"); reply = client.ask(scoutMessage); break; case FreeColDialog.SCOUT_INDIAN_SETTLEMENT_TRIBUTE: scoutMessage.setAttribute("action", "tribute"); reply = client.ask(scoutMessage); break; default: logger.warning("Incorrect response returned from Canvas.showScoutIndianSettlementDialog()"); return; } if (reply.getTagName().equals("scoutIndianSettlementResult")) { String result = reply.getAttribute("result"), action = scoutMessage.getAttribute("action"); if (result.equals("die")) { unit.dispose(); canvas.showInformationMessage("scoutSettlement.speakDie"); } else if (action.equals("speak") && result.equals("tales")) { // Parse the tiles. Element updateElement = getChildElement(reply, "update"); if (updateElement != null) { freeColClient.getInGameInputHandler().handle(client.getConnection(), updateElement); } canvas.showInformationMessage("scoutSettlement.speakTales"); } else if (action.equals("speak") && result.equals("beads")) { String amount = reply.getAttribute("amount"); unit.getOwner().modifyGold(Integer.parseInt(amount)); freeColClient.getCanvas().updateGoldLabel(); canvas.showInformationMessage("scoutSettlement.speakBeads", new String[][] { { "%replace%", amount } }); } else if (action.equals("speak") && result.equals("nothing")) { canvas.showInformationMessage("scoutSettlement.speakNothing"); } else if (action.equals("tribute") && result.equals("agree")) { String amount = reply.getAttribute("amount"); unit.getOwner().modifyGold(Integer.parseInt(amount)); freeColClient.getCanvas().updateGoldLabel(); canvas.showInformationMessage("scoutSettlement.tributeAgree", new String[][] { { "%replace%", amount } }); } else if (action.equals("tribute") && result.equals("disagree")) { canvas.showInformationMessage("scoutSettlement.tributeDisagree"); } } else { logger.warning("Server gave an invalid reply to an scoutIndianSettlement message"); return; } nextActiveUnit(unit.getTile()); } /** * Moves a missionary into an indian settlement. * * @param unit The unit that will enter the settlement. * @param direction The direction in which the Indian settlement lies. */ private void useMissionary(Unit unit, int direction) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Map map = freeColClient.getGame().getMap(); IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile()) .getSettlement(); List<Object> response = canvas.showUseMissionaryDialog(settlement); int action = ((Integer) response.get(0)).intValue(); Element missionaryMessage = Message.createNewRootElement("missionaryAtSettlement"); missionaryMessage.setAttribute("unit", unit.getID()); missionaryMessage.setAttribute("direction", Integer.toString(direction)); Element reply = null; unit.setMovesLeft(0); switch (action) { case FreeColDialog.MISSIONARY_CANCEL: missionaryMessage.setAttribute("action", "cancel"); client.sendAndWait(missionaryMessage); break; case FreeColDialog.MISSIONARY_ESTABLISH: missionaryMessage.setAttribute("action", "establish"); settlement.setMissionary(unit); client.sendAndWait(missionaryMessage); nextActiveUnit(); // At this point: unit.getTile() == null return; case FreeColDialog.MISSIONARY_DENOUNCE_AS_HERESY: missionaryMessage.setAttribute("action", "heresy"); reply = client.ask(missionaryMessage); if (!reply.getTagName().equals("missionaryReply")) { logger.warning("Server gave an invalid reply to a missionaryAtSettlement message"); return; } String success = reply.getAttribute("success"); if (success.equals("true")) { settlement.setMissionary(unit); nextActiveUnit(); // At this point: unit.getTile() == null } else { unit.dispose(); nextActiveUnit(); // At this point: unit == null } return; case FreeColDialog.MISSIONARY_INCITE_INDIANS: missionaryMessage.setAttribute("action", "incite"); missionaryMessage.setAttribute("incite", ((Player) response.get(1)).getID()); reply = client.ask(missionaryMessage); if (reply.getTagName().equals("missionaryReply")) { int amount = Integer.parseInt(reply.getAttribute("amount")); boolean confirmed = canvas.showInciteDialog((Player) response.get(1), amount); if (confirmed && unit.getOwner().getGold() < amount) { canvas.showInformationMessage("notEnoughGold"); confirmed = false; } Element inciteMessage = Message.createNewRootElement("inciteAtSettlement"); inciteMessage.setAttribute("unit", unit.getID()); inciteMessage.setAttribute("direction", Integer.toString(direction)); inciteMessage.setAttribute("confirmed", confirmed ? "true" : "false"); inciteMessage.setAttribute("enemy", ((Player) response.get(1)).getID()); if (confirmed) { unit.getOwner().modifyGold(-amount); // Maybe at this point we can keep track of the fact that // the indian is now at // war with the chosen european player, but is this really // necessary at the client // side? settlement.getOwner().setStance((Player) response.get(1), Player.WAR); ((Player) response.get(1)).setStance(settlement.getOwner(), Player.WAR); } client.sendAndWait(inciteMessage); } else { logger.warning("Server gave an invalid reply to a missionaryAtSettlement message"); return; } } nextActiveUnit(unit.getTile()); } /** * Moves the specified unit to Europe. * * @param unit The unit to be moved to Europe. */ public void moveToEurope(Unit unit) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); unit.moveToEurope(); Element moveToEuropeElement = Message.createNewRootElement("moveToEurope"); moveToEuropeElement.setAttribute("unit", unit.getID()); client.sendAndWait(moveToEuropeElement); } /** * Moves the specified unit to America. * * @param unit The unit to be moved to America. */ public void moveToAmerica(Unit unit) { final Canvas canvas = freeColClient.getCanvas(); final Player player = freeColClient.getMyPlayer(); if (freeColClient.getGame().getCurrentPlayer() != player) { canvas.showInformationMessage("notYourTurn"); return; } final Client client = freeColClient.getClient(); final ClientOptions co = canvas.getClient().getClientOptions(); // Ask for autoload emigrants if (unit.getLocation() instanceof Europe) { final boolean autoload = co.getBoolean(ClientOptions.AUTOLOAD_EMIGRANTS); if (autoload) { int spaceLeft = unit.getSpaceLeft(); List<Unit> unitsInEurope = unit.getLocation().getUnitList(); for (Unit possiblePassenger : unitsInEurope) { if (possiblePassenger.isNaval()) { continue; } if (possiblePassenger.getTakeSpace() <= spaceLeft) { boardShip(possiblePassenger, unit); spaceLeft -= possiblePassenger.getTakeSpace(); } else { break; } } } } unit.moveToAmerica(); Element moveToAmericaElement = Message.createNewRootElement("moveToAmerica"); moveToAmericaElement.setAttribute("unit", unit.getID()); client.sendAndWait(moveToAmericaElement); } /** * Trains a unit of a specified type in Europe. * * @param unitType The type of unit to be trained. */ public void trainUnitInEurope(UnitType unitType) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Game game = freeColClient.getGame(); Player myPlayer = freeColClient.getMyPlayer(); Europe europe = myPlayer.getEurope(); if (myPlayer.getGold() < europe.getUnitPrice(unitType)) { // System.out.println("Price: " + Unit.getPrice(unitType) + ", Gold: // " + myPlayer.getGold()); canvas.errorMessage("notEnoughGold"); return; } Element trainUnitInEuropeElement = Message.createNewRootElement("trainUnitInEurope"); trainUnitInEuropeElement.setAttribute("unitType", Integer.toString(unitType.getIndex())); Element reply = client.ask(trainUnitInEuropeElement); if (reply.getTagName().equals("trainUnitInEuropeConfirmed")) { Element unitElement = (Element) reply.getChildNodes().item(0); Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(game, unitElement); } else { unit.readFromXMLElement(unitElement); } europe.train(unit); } else { logger.warning("Could not train unit in europe."); return; } freeColClient.getCanvas().updateGoldLabel(); } /** * Buys the remaining hammers and tools for the {@link Building} currently * being built in the given <code>Colony</code>. * * @param colony The {@link Colony} where the building should be bought. */ public void payForBuilding(Colony colony) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } if (!freeColClient.getCanvas() .showConfirmDialog("payForBuilding.text", "payForBuilding.yes", "payForBuilding.no", new String[][] { { "%replace%", Integer.toString(colony.getPriceForBuilding()) } })) { return; } if (colony.getPriceForBuilding() > freeColClient.getMyPlayer().getGold()) { freeColClient.getCanvas().errorMessage("notEnoughGold"); return; } Element payForBuildingElement = Message.createNewRootElement("payForBuilding"); payForBuildingElement.setAttribute("colony", colony.getID()); colony.payForBuilding(); freeColClient.getClient().sendAndWait(payForBuildingElement); } /** * Recruit a unit from a specified "slot" in Europe. * * @param slot The slot to recruit the unit from. Either 1, 2 or 3. */ public void recruitUnitInEurope(int slot) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); Game game = freeColClient.getGame(); Player myPlayer = freeColClient.getMyPlayer(); Europe europe = myPlayer.getEurope(); if (myPlayer.getGold() < myPlayer.getRecruitPrice()) { canvas.errorMessage("notEnoughGold"); return; } Element recruitUnitInEuropeElement = Message.createNewRootElement("recruitUnitInEurope"); recruitUnitInEuropeElement.setAttribute("slot", Integer.toString(slot)); Element reply = client.ask(recruitUnitInEuropeElement); if (reply.getTagName().equals("recruitUnitInEuropeConfirmed")) { Element unitElement = (Element) reply.getChildNodes().item(0); Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(game, unitElement); } else { unit.readFromXMLElement(unitElement); } int unitIndex = Integer.parseInt(reply.getAttribute("newRecruitable")); UnitType unitType = FreeCol.getSpecification().getUnitType(unitIndex); europe.recruit(slot, unit, unitType); } else { logger.warning("Could not recruit the specified unit in europe."); return; } freeColClient.getCanvas().updateGoldLabel(); } /** * Cause a unit to emigrate from a specified "slot" in Europe. If the player * doesn't have William Brewster in the congress then the value of the slot * parameter is not important (it won't be used). * * @param slot The slot from which the unit emigrates. Either 1, 2 or 3 if * William Brewster is in the congress. */ private void emigrateUnitInEurope(int slot) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); Player myPlayer = freeColClient.getMyPlayer(); Europe europe = myPlayer.getEurope(); Element emigrateUnitInEuropeElement = Message.createNewRootElement("emigrateUnitInEurope"); if (myPlayer.hasFather(FreeCol.getSpecification().getFoundingFather("model.foundingFather.williamBrewster"))) { emigrateUnitInEuropeElement.setAttribute("slot", Integer.toString(slot)); } Element reply = client.ask(emigrateUnitInEuropeElement); if (reply == null || !reply.getTagName().equals("emigrateUnitInEuropeConfirmed")) { logger.warning("Could not recruit unit: " + myPlayer.getCrosses() + "/" + myPlayer.getCrossesRequired()); throw new IllegalStateException(); } // System.out.println("Sent slot " + slot); if (!myPlayer.hasFather(FreeCol.getSpecification().getFoundingFather("model.foundingFather.williamBrewster"))) { slot = Integer.parseInt(reply.getAttribute("slot")); // System.out.println("Received slot " + slot); } Element unitElement = (Element) reply.getChildNodes().item(0); Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(game, unitElement); } else { unit.readFromXMLElement(unitElement); } int unitIndex = Integer.parseInt(reply.getAttribute("newRecruitable")); UnitType newRecruitable = FreeCol.getSpecification().getUnitType(unitIndex); europe.emigrate(slot, unit, newRecruitable); freeColClient.getCanvas().updateGoldLabel(); } /** * Updates a trade route. * * @param route The trade route to update. */ public void updateTradeRoute(TradeRoute route) { logger.finest("Entering method updateTradeRoute"); /* * if (freeColClient.getGame().getCurrentPlayer() != * freeColClient.getMyPlayer()) { * freeColClient.getCanvas().showInformationMessage("notYourTurn"); * return; } */ Element tradeRouteElement = Message.createNewRootElement("updateTradeRoute"); tradeRouteElement.appendChild(route.toXMLElement(null, tradeRouteElement.getOwnerDocument())); freeColClient.getClient().sendAndWait(tradeRouteElement); } /** * Sets the trade routes for this player * * @param routes The trade routes to set. */ public void setTradeRoutes(List<TradeRoute> routes) { Player myPlayer = freeColClient.getMyPlayer(); myPlayer.setTradeRoutes(routes); /* * if (freeColClient.getGame().getCurrentPlayer() != * freeColClient.getMyPlayer()) { * freeColClient.getCanvas().showInformationMessage("notYourTurn"); * return; } */ Element tradeRoutesElement = Message.createNewRootElement("setTradeRoutes"); for(TradeRoute route : routes) { Element routeElement = tradeRoutesElement.getOwnerDocument().createElement(TradeRoute.getXMLElementTagName()); routeElement.setAttribute("id", route.getID()); tradeRoutesElement.appendChild(routeElement); } freeColClient.getClient().sendAndWait(tradeRoutesElement); } /** * Assigns a trade route to a unit. * * @param unit The unit to assign a trade route to. */ public void assignTradeRoute(Unit unit) { assignTradeRoute(unit, freeColClient.getCanvas().showTradeRouteDialog(unit.getTradeRoute())); } public void assignTradeRoute(Unit unit, TradeRoute tradeRoute) { if (tradeRoute != null) { Element assignTradeRouteElement = Message.createNewRootElement("assignTradeRoute"); assignTradeRouteElement.setAttribute("unit", unit.getID()); if (tradeRoute == TradeRoute.NO_TRADE_ROUTE) { unit.setTradeRoute(null); freeColClient.getClient().sendAndWait(assignTradeRouteElement); setDestination(unit, null); } else { unit.setTradeRoute(tradeRoute); assignTradeRouteElement.setAttribute("tradeRoute", tradeRoute.getID()); freeColClient.getClient().sendAndWait(assignTradeRouteElement); Location location = unit.getLocation(); if (location instanceof Tile) location = ((Tile) location).getColony(); if (tradeRoute.getStops().get(0).getLocation() == location) { followTradeRoute(unit); } else if (freeColClient.getGame().getCurrentPlayer() == freeColClient.getMyPlayer()) { moveToDestination(unit); } } } } /** * Pays the tax arrears on this type of goods. * * @param goods The goods for which to pay arrears. */ public void payArrears(Goods goods) { payArrears(goods.getType()); } /** * Pays the tax arrears on this type of goods. * * @param type The type of goods for which to pay arrears. */ public void payArrears(GoodsType type) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Player player = freeColClient.getMyPlayer(); int arrears = player.getArrears(type.getIndex()); if (player.getGold() >= arrears) { if (freeColClient.getCanvas().showConfirmDialog("model.europe.payArrears", "ok", "cancel", new String[][] { { "%replace%", String.valueOf(arrears) } })) { player.modifyGold(-arrears); freeColClient.getCanvas().updateGoldLabel(); player.resetArrears(type.getIndex()); // send to server Element payArrearsElement = Message.createNewRootElement("payArrears"); payArrearsElement.setAttribute("goodsType", String.valueOf(type.getIndex())); client.sendAndWait(payArrearsElement); } } else { freeColClient.getCanvas().showInformationMessage("model.europe.cantPayArrears", new String[][] { { "%amount%", String.valueOf(arrears) } }); } } // TODO: make this unnecessary public void payArrears(int typeIndex) { payArrears(FreeCol.getSpecification().getGoodsType(typeIndex)); } /** * Purchases a unit of a specified type in Europe. * * @param unitType The type of unit to be purchased. */ public void purchaseUnitFromEurope(UnitType unitType) { trainUnitInEurope(unitType); } /** * Skips the active unit by setting it's <code>movesLeft</code> to 0. */ public void skipActiveUnit() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } GUI gui = freeColClient.getGUI(); Unit unit = gui.getActiveUnit(); if (unit != null) { Element skipUnit = Message.createNewRootElement("skipUnit"); skipUnit.setAttribute("unit", unit.getID()); unit.skip(); freeColClient.getClient().sendAndWait(skipUnit); } nextActiveUnit(); } /** * Gathers information about opponents. */ public Element getForeignAffairsReport() { return freeColClient.getClient().ask(Message.createNewRootElement("foreignAffairs")); } /** * Gathers information about the REF. */ public Element getREFUnits() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return null; } Element reply = freeColClient.getClient().ask(Message.createNewRootElement("getREFUnits")); return reply; } /** * Disbands the active unit. */ public void disbandActiveUnit() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } GUI gui = freeColClient.getGUI(); Unit unit = gui.getActiveUnit(); Client client = freeColClient.getClient(); if (unit == null) { return; } if (!freeColClient.getCanvas().showConfirmDialog("disbandUnit.text", "disbandUnit.yes", "disbandUnit.no")) { return; } Element disbandUnit = Message.createNewRootElement("disbandUnit"); disbandUnit.setAttribute("unit", unit.getID()); unit.dispose(); client.sendAndWait(disbandUnit); nextActiveUnit(); } /** * Centers the map on the selected tile. */ public void centerActiveUnit() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } GUI gui = freeColClient.getGUI(); if (gui.getActiveUnit() != null && gui.getActiveUnit().getTile() != null) { gui.setFocus(gui.getActiveUnit().getTile().getPosition()); } } /** * Executes the units' goto orders. */ public void executeGotoOrders() { executeGoto = true; nextActiveUnit(null); } /** * Makes a new unit active. */ public void nextActiveUnit() { nextActiveUnit(null); } /** * Makes a new unit active. Displays any new <code>ModelMessage</code>s * (uses {@link #nextModelMessage}). * * @param tile The tile to select if no new unit can be made active. */ public void nextActiveUnit(Tile tile) { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } nextModelMessage(); Canvas canvas = freeColClient.getCanvas(); Player myPlayer = freeColClient.getMyPlayer(); if (endingTurn || executeGoto) { while (!freeColClient.getCanvas().isShowingSubPanel() && myPlayer.hasNextGoingToUnit()) { Unit unit = myPlayer.getNextGoingToUnit(); moveToDestination(unit); nextModelMessage(); if (unit.getMovesLeft() > 0) { if (endingTurn) { unit.setMovesLeft(0); } else { return; } } } if (!myPlayer.hasNextGoingToUnit() && !freeColClient.getCanvas().isShowingSubPanel()) { if (endingTurn) { canvas.getGUI().setActiveUnit(null); endingTurn = false; Element endTurnElement = Message.createNewRootElement("endTurn"); freeColClient.getClient().send(endTurnElement); return; } else { executeGoto = false; } } } GUI gui = freeColClient.getGUI(); Unit nextActiveUnit = myPlayer.getNextActiveUnit(); if (nextActiveUnit != null) { gui.setActiveUnit(nextActiveUnit); } else { // no more active units, so we can move the others nextActiveUnit = myPlayer.getNextGoingToUnit(); if (nextActiveUnit != null) { moveToDestination(nextActiveUnit); } else if (tile != null) { Position p = tile.getPosition(); if (p != null) { // this really shouldn't happen gui.setSelectedTile(p); } gui.setActiveUnit(null); } else { gui.setActiveUnit(null); } } } /** * Ignore this ModelMessage from now on until it is not generated in a turn. * * @param message a <code>ModelMessage</code> value * @param flag whether to ignore the ModelMessage or not */ public synchronized void ignoreMessage(ModelMessage message, boolean flag) { String key = message.getSource().getID(); for (String[] replacement : message.getData()) { if (replacement[0].equals("%goods%")) { key += replacement[1]; break; } } if (flag) { startIgnoringMessage(key, freeColClient.getGame().getTurn().getNumber()); } else { stopIgnoringMessage(key); } } /** * Displays the next <code>ModelMessage</code>. * * @see net.sf.freecol.common.model.ModelMessage ModelMessage */ public void nextModelMessage() { displayModelMessages(false); } public void displayModelMessages(final boolean allMessages) { int thisTurn = freeColClient.getGame().getTurn().getNumber(); final ArrayList<ModelMessage> messageList = new ArrayList<ModelMessage>(); List<ModelMessage> inputList; if (allMessages) { inputList = freeColClient.getMyPlayer().getModelMessages(); } else { inputList = freeColClient.getMyPlayer().getNewModelMessages(); } for (ModelMessage message : inputList) { if (shouldAllowMessage(message)) { if (message.getType() == ModelMessage.WAREHOUSE_CAPACITY) { String key = message.getSource().getID(); for (String[] replacement : message.getData()) { if (replacement[0].equals("%goods%")) { key += replacement[1]; break; } } Integer turn = getTurnForMessageIgnored(key); if (turn != null && turn.intValue() == thisTurn - 1) { startIgnoringMessage(key, thisTurn); message.setBeenDisplayed(true); continue; } } messageList.add(message); } // flag all messages delivered as "beenDisplayed". message.setBeenDisplayed(true); } purgeOldMessagesFromMessagesToIgnore(thisTurn); Runnable uiTask = new Runnable() { public void run() { if (messageList.size() > 0) { if (allMessages || messageList.size() > 5) { freeColClient.getCanvas().showTurnReport(messageList); } else { freeColClient.getCanvas().showModelMessages( messageList.toArray(new ModelMessage[0])); } } freeColClient.getActionManager().update(); } }; if (SwingUtilities.isEventDispatchThread()) { uiTask.run(); } else { try { SwingUtilities.invokeAndWait(uiTask); } catch (InterruptedException e) { // Ignore } catch (InvocationTargetException e) { // Ignore } } } private synchronized Integer getTurnForMessageIgnored(String key) { return messagesToIgnore.get(key); } private synchronized void startIgnoringMessage(String key, int turn) { logger.finer("Ignoring model message with key " + key); messagesToIgnore.put(key, new Integer(turn)); } private synchronized void stopIgnoringMessage(String key) { logger.finer("Removing model message with key " + key + " from ignored messages."); messagesToIgnore.remove(key); } private synchronized void purgeOldMessagesFromMessagesToIgnore(int thisTurn) { List<String> keysToRemove = new ArrayList<String>(); for (Entry<String, Integer> entry : messagesToIgnore.entrySet()) { if (entry.getValue().intValue() < thisTurn - 1) { if (logger.isLoggable(Level.FINER)) { logger.finer("Removing old model message with key " + entry.getKey() + " from ignored messages."); } keysToRemove.add(entry.getKey()); } } for (String key : keysToRemove) { stopIgnoringMessage(key); } } /** * Provides an opportunity to filter the messages delivered to the canvas. * * @param message the message that is candidate for delivery to the canvas * @return true if the message should be delivered */ private boolean shouldAllowMessage(ModelMessage message) { switch (message.getType()) { case ModelMessage.DEFAULT: return true; case ModelMessage.WARNING: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_WARNING); case ModelMessage.SONS_OF_LIBERTY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_SONS_OF_LIBERTY); case ModelMessage.GOVERNMENT_EFFICIENCY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_GOVERNMENT_EFFICIENCY); case ModelMessage.WAREHOUSE_CAPACITY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_WAREHOUSE_CAPACITY); case ModelMessage.UNIT_IMPROVED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_IMPROVED); case ModelMessage.UNIT_DEMOTED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_DEMOTED); case ModelMessage.UNIT_LOST: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_LOST); case ModelMessage.UNIT_ADDED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_ADDED); case ModelMessage.BUILDING_COMPLETED: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_BUILDING_COMPLETED); case ModelMessage.FOREIGN_DIPLOMACY: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_FOREIGN_DIPLOMACY); case ModelMessage.MARKET_PRICES: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_MARKET_PRICES); case ModelMessage.MISSING_GOODS: return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_MISSING_GOODS); default: return true; } } /** * End the turn. */ public void endTurn() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } endingTurn = true; nextActiveUnit(null); } /** * Convenience method: returns the first child element with the specified * tagname. * * @param element The <code>Element</code> to search for the child * element. * @param tagName The tag name of the child element to be found. * @return The child of the given <code>Element</code> with the given * <code>tagName</code> or <code>null</code> if no such child * exists. */ protected Element getChildElement(Element element, String tagName) { NodeList n = element.getChildNodes(); for (int i = 0; i < n.getLength(); i++) { if (((Element) n.item(i)).getTagName().equals(tagName)) { return (Element) n.item(i); } } return null; } /** * Abandon a colony with no units * * @param colony The colony to be abandoned */ public void abandonColony(Colony colony) { if (colony == null) { return; } Client client = freeColClient.getClient(); Element abandonColony = Message.createNewRootElement("abandonColony"); abandonColony.setAttribute("colony", colony.getID()); colony.dispose(); client.sendAndWait(abandonColony); } }
true
true
public void buildColony() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); GUI gui = freeColClient.getGUI(); Unit unit = freeColClient.getGUI().getActiveUnit(); if (unit == null || !unit.canBuildColony()) { return; } Tile tile = unit.getTile(); if (tile == null) { return; } if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_COLONY_WARNINGS)) { boolean landLocked = true; int lumber = 0; int food = tile.potential(Goods.FOOD); int ore = 0; boolean ownedByEuropeans = false; boolean ownedBySelf = false; boolean ownedByIndians = false; if (tile.secondaryGoods() == Goods.ORE) { ore = 3; } Map map = game.getMap(); Iterator<Position> tileIterator = map.getAdjacentIterator(tile.getPosition()); while (tileIterator.hasNext()) { Tile newTile = map.getTile(tileIterator.next()); if (newTile.isLand()) { lumber += newTile.potential(Goods.LUMBER); food += newTile.potential(Goods.FOOD); ore += newTile.potential(Goods.ORE); Player tileOwner = newTile.getOwner(); if (tileOwner == unit.getOwner()) { if (newTile.getOwningSettlement() != null) { // we are using newTile ownedBySelf = true; } else { Iterator<Position> ownTileIt = map.getAdjacentIterator(newTile.getPosition()); while (ownTileIt.hasNext()) { Colony colony = map.getTile(ownTileIt.next()).getColony(); if (colony != null && colony.getOwner() == unit.getOwner()) { // newTile can be used from an own colony ownedBySelf = true; break; } } } } else if (tileOwner.isEuropean()) { ownedByEuropeans = true; } else if (tileOwner != null) { ownedByIndians = true; } } else { landLocked = false; } } ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>(); if (landLocked) { messages.add(new ModelMessage(unit, "buildColony.landLocked", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.fish"))); } if (food < 8) { messages.add(new ModelMessage(unit, "buildColony.noFood", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.food"))); } if (lumber < 4) { messages.add(new ModelMessage(unit, "buildColony.noLumber", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.lumber"))); } if (ore < 2) { messages.add(new ModelMessage(unit, "buildColony.noOre", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.ore"))); } if (ownedBySelf) { messages.add(new ModelMessage(unit, "buildColony.ownLand", null, ModelMessage.WARNING)); } if (ownedByEuropeans) { messages.add(new ModelMessage(unit, "buildColony.EuropeanLand", null, ModelMessage.WARNING)); } if (ownedByIndians) { messages.add(new ModelMessage(unit, "buildColony.IndianLand", null, ModelMessage.WARNING)); } if (messages.size() > 0) { ModelMessage[] modelMessages = messages.toArray(new ModelMessage[0]); if (!freeColClient.getCanvas().showConfirmDialog(modelMessages, "buildColony.yes", "buildColony.no")) { return; } } } String name = freeColClient.getCanvas().showInputDialog("nameColony.text", freeColClient.getMyPlayer().getDefaultColonyName(), "nameColony.yes", "nameColony.no"); if (name == null) { // The user cancelled the action. return; } else if (freeColClient.getMyPlayer().getColony(name) != null) { // colony name must be unique (per Player) freeColClient.getCanvas().showInformationMessage("nameColony.notUnique", new String[][] { { "%name%", name } }); return; } Element buildColonyElement = Message.createNewRootElement("buildColony"); buildColonyElement.setAttribute("name", name); buildColonyElement.setAttribute("unit", unit.getID()); Element reply = client.ask(buildColonyElement); if (reply.getTagName().equals("buildColonyConfirmed")) { if (reply.getElementsByTagName("update").getLength() > 0) { Element updateElement = (Element) reply.getElementsByTagName("update").item(0); freeColClient.getInGameInputHandler().update(updateElement); } Colony colony = (Colony) game.getFreeColGameObject(((Element) reply.getChildNodes().item(0)) .getAttribute("ID")); if (colony == null) { colony = new Colony(game, (Element) reply.getChildNodes().item(0)); } else { colony.readFromXMLElement((Element) reply.getChildNodes().item(0)); } changeWorkType(unit, Goods.FOOD); unit.buildColony(colony); for(Unit unitInTile : tile.getUnitList()) { if (unitInTile.canCarryTreasure()) { checkCashInTreasureTrain(unitInTile); } } gui.setActiveUnit(null); gui.setSelectedTile(colony.getTile().getPosition()); } else { // Handle errormessage. } }
public void buildColony() { if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) { freeColClient.getCanvas().showInformationMessage("notYourTurn"); return; } Client client = freeColClient.getClient(); Game game = freeColClient.getGame(); GUI gui = freeColClient.getGUI(); Unit unit = freeColClient.getGUI().getActiveUnit(); if (unit == null || !unit.canBuildColony()) { return; } Tile tile = unit.getTile(); if (tile == null) { return; } if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_COLONY_WARNINGS)) { boolean landLocked = true; int lumber = 0; int food = tile.potential(Goods.FOOD); int ore = 0; boolean ownedByEuropeans = false; boolean ownedBySelf = false; boolean ownedByIndians = false; if (tile.secondaryGoods() == Goods.ORE) { ore = 3; } Map map = game.getMap(); Iterator<Position> tileIterator = map.getAdjacentIterator(tile.getPosition()); while (tileIterator.hasNext()) { Tile newTile = map.getTile(tileIterator.next()); if (newTile.isLand()) { lumber += newTile.potential(Goods.LUMBER); food += newTile.potential(Goods.FOOD); ore += newTile.potential(Goods.ORE); Player tileOwner = newTile.getOwner(); if (tileOwner == unit.getOwner()) { if (newTile.getOwningSettlement() != null) { // we are using newTile ownedBySelf = true; } else { Iterator<Position> ownTileIt = map.getAdjacentIterator(newTile.getPosition()); while (ownTileIt.hasNext()) { Colony colony = map.getTile(ownTileIt.next()).getColony(); if (colony != null && colony.getOwner() == unit.getOwner()) { // newTile can be used from an own colony ownedBySelf = true; break; } } } } else if (tileOwner != null && tileOwner.isEuropean()) { ownedByEuropeans = true; } else if (tileOwner != null) { ownedByIndians = true; } } else { landLocked = false; } } ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>(); if (landLocked) { messages.add(new ModelMessage(unit, "buildColony.landLocked", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.fish"))); } if (food < 8) { messages.add(new ModelMessage(unit, "buildColony.noFood", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.food"))); } if (lumber < 4) { messages.add(new ModelMessage(unit, "buildColony.noLumber", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.lumber"))); } if (ore < 2) { messages.add(new ModelMessage(unit, "buildColony.noOre", null, ModelMessage.MISSING_GOODS, FreeCol.getSpecification().getGoodsType("model.goods.ore"))); } if (ownedBySelf) { messages.add(new ModelMessage(unit, "buildColony.ownLand", null, ModelMessage.WARNING)); } if (ownedByEuropeans) { messages.add(new ModelMessage(unit, "buildColony.EuropeanLand", null, ModelMessage.WARNING)); } if (ownedByIndians) { messages.add(new ModelMessage(unit, "buildColony.IndianLand", null, ModelMessage.WARNING)); } if (messages.size() > 0) { ModelMessage[] modelMessages = messages.toArray(new ModelMessage[0]); if (!freeColClient.getCanvas().showConfirmDialog(modelMessages, "buildColony.yes", "buildColony.no")) { return; } } } String name = freeColClient.getCanvas().showInputDialog("nameColony.text", freeColClient.getMyPlayer().getDefaultColonyName(), "nameColony.yes", "nameColony.no"); if (name == null) { // The user cancelled the action. return; } else if (freeColClient.getMyPlayer().getColony(name) != null) { // colony name must be unique (per Player) freeColClient.getCanvas().showInformationMessage("nameColony.notUnique", new String[][] { { "%name%", name } }); return; } Element buildColonyElement = Message.createNewRootElement("buildColony"); buildColonyElement.setAttribute("name", name); buildColonyElement.setAttribute("unit", unit.getID()); Element reply = client.ask(buildColonyElement); if (reply.getTagName().equals("buildColonyConfirmed")) { if (reply.getElementsByTagName("update").getLength() > 0) { Element updateElement = (Element) reply.getElementsByTagName("update").item(0); freeColClient.getInGameInputHandler().update(updateElement); } Colony colony = (Colony) game.getFreeColGameObject(((Element) reply.getChildNodes().item(0)) .getAttribute("ID")); if (colony == null) { colony = new Colony(game, (Element) reply.getChildNodes().item(0)); } else { colony.readFromXMLElement((Element) reply.getChildNodes().item(0)); } changeWorkType(unit, Goods.FOOD); unit.buildColony(colony); for(Unit unitInTile : tile.getUnitList()) { if (unitInTile.canCarryTreasure()) { checkCashInTreasureTrain(unitInTile); } } gui.setActiveUnit(null); gui.setSelectedTile(colony.getTile().getPosition()); } else { // Handle errormessage. } }
diff --git a/src/main/java/de/lessvoid/nifty/effects/impl/Move.java b/src/main/java/de/lessvoid/nifty/effects/impl/Move.java index d37af916..c089efdc 100644 --- a/src/main/java/de/lessvoid/nifty/effects/impl/Move.java +++ b/src/main/java/de/lessvoid/nifty/effects/impl/Move.java @@ -1,130 +1,130 @@ package de.lessvoid.nifty.effects.impl; import java.util.logging.Logger; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.effects.EffectImpl; import de.lessvoid.nifty.effects.EffectProperties; import de.lessvoid.nifty.effects.Falloff; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.render.NiftyRenderEngine; import de.lessvoid.nifty.tools.TargetElementResolver; /** * Move - move stuff around. * @author void */ public class Move implements EffectImpl { private Logger log = Logger.getLogger(Move.class.getName()); private static final String LEFT = "left"; private static final String RIGHT = "right"; private static final String TOP = "top"; private static final String BOTTOM = "bottom"; private String direction; private long offset = 0; private long startOffset = 0; private int offsetDir = 0; private float offsetY; private float startOffsetY; private int startOffsetX; private float offsetX; private boolean withTarget = false; private boolean fromOffset = false; private boolean toOffset = false; public void activate(final Nifty nifty, final Element element, final EffectProperties parameter) { String mode = parameter.getProperty("mode"); direction = parameter.getProperty("direction"); if (LEFT.equals(direction)) { offset = element.getX() + element.getWidth(); } else if (RIGHT.equals(direction)) { offset = nifty.getRenderEngine().getWidth() - element.getX(); } else if (TOP.equals(direction)) { offset = element.getY() + element.getHeight(); } else if (BOTTOM.equals(direction)) { offset = nifty.getRenderEngine().getHeight() - element.getY(); } else { offset = 0; } if ("out".equals(mode)) { startOffset = 0; offsetDir = -1; withTarget = false; } else if ("in".equals(mode)) { startOffset = offset; offsetDir = 1; withTarget = false; } else if ("fromPosition".equals(mode)) { withTarget = true; } else if ("toPosition".equals(mode)) { withTarget = true; } else if ("fromOffset".equals(mode)) { fromOffset = true; startOffsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); startOffsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); - offsetX = Math.abs(startOffsetX); - offsetY = Math.abs(startOffsetY); + offsetX = startOffsetX * -1; + offsetY = startOffsetY * -1; } else if ("toOffset".equals(mode)) { toOffset = true; startOffsetX = 0; startOffsetY = 0; offsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); offsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); } String target = parameter.getProperty("targetElement"); if (target != null) { TargetElementResolver resolver = new TargetElementResolver(nifty.getCurrentScreen(), element); Element targetElement = resolver.resolve(target); if (targetElement == null) { log.warning("move effect for element [" + element.getId() + "] was unable to find target element [" + target + "] at screen [" + nifty.getCurrentScreen().getScreenId() + "]"); return; } if ("fromPosition".equals(mode)) { startOffsetX = targetElement.getX() - element.getX(); startOffsetY = targetElement.getY() - element.getY(); offsetX = -(targetElement.getX() - element.getX()); offsetY = -(targetElement.getY() - element.getY()); } else if ("toPosition".equals(mode)) { startOffsetX = 0; startOffsetY = 0; offsetX = (targetElement.getX() - element.getX()); offsetY = (targetElement.getY() - element.getY()); } } } public void execute( final Element element, final float normalizedTime, final Falloff falloff, final NiftyRenderEngine r) { if (fromOffset || toOffset) { float moveToX = startOffsetX + normalizedTime * offsetX; float moveToY = startOffsetY + normalizedTime * offsetY; r.moveTo(moveToX, moveToY); } else if (withTarget) { float moveToX = startOffsetX + normalizedTime * offsetX; float moveToY = startOffsetY + normalizedTime * offsetY; r.moveTo(moveToX, moveToY); } else { if (LEFT.equals(direction)) { r.moveTo(-startOffset + offsetDir * normalizedTime * offset, 0); } else if (RIGHT.equals(direction)) { r.moveTo(startOffset - offsetDir * normalizedTime * offset, 0); } else if (TOP.equals(direction)) { r.moveTo(0, -startOffset + offsetDir * normalizedTime * offset); } else if (BOTTOM.equals(direction)) { r.moveTo(0, startOffset - offsetDir * normalizedTime * offset); } } } public void deactivate() { } }
true
true
public void activate(final Nifty nifty, final Element element, final EffectProperties parameter) { String mode = parameter.getProperty("mode"); direction = parameter.getProperty("direction"); if (LEFT.equals(direction)) { offset = element.getX() + element.getWidth(); } else if (RIGHT.equals(direction)) { offset = nifty.getRenderEngine().getWidth() - element.getX(); } else if (TOP.equals(direction)) { offset = element.getY() + element.getHeight(); } else if (BOTTOM.equals(direction)) { offset = nifty.getRenderEngine().getHeight() - element.getY(); } else { offset = 0; } if ("out".equals(mode)) { startOffset = 0; offsetDir = -1; withTarget = false; } else if ("in".equals(mode)) { startOffset = offset; offsetDir = 1; withTarget = false; } else if ("fromPosition".equals(mode)) { withTarget = true; } else if ("toPosition".equals(mode)) { withTarget = true; } else if ("fromOffset".equals(mode)) { fromOffset = true; startOffsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); startOffsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); offsetX = Math.abs(startOffsetX); offsetY = Math.abs(startOffsetY); } else if ("toOffset".equals(mode)) { toOffset = true; startOffsetX = 0; startOffsetY = 0; offsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); offsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); } String target = parameter.getProperty("targetElement"); if (target != null) { TargetElementResolver resolver = new TargetElementResolver(nifty.getCurrentScreen(), element); Element targetElement = resolver.resolve(target); if (targetElement == null) { log.warning("move effect for element [" + element.getId() + "] was unable to find target element [" + target + "] at screen [" + nifty.getCurrentScreen().getScreenId() + "]"); return; } if ("fromPosition".equals(mode)) { startOffsetX = targetElement.getX() - element.getX(); startOffsetY = targetElement.getY() - element.getY(); offsetX = -(targetElement.getX() - element.getX()); offsetY = -(targetElement.getY() - element.getY()); } else if ("toPosition".equals(mode)) { startOffsetX = 0; startOffsetY = 0; offsetX = (targetElement.getX() - element.getX()); offsetY = (targetElement.getY() - element.getY()); } } }
public void activate(final Nifty nifty, final Element element, final EffectProperties parameter) { String mode = parameter.getProperty("mode"); direction = parameter.getProperty("direction"); if (LEFT.equals(direction)) { offset = element.getX() + element.getWidth(); } else if (RIGHT.equals(direction)) { offset = nifty.getRenderEngine().getWidth() - element.getX(); } else if (TOP.equals(direction)) { offset = element.getY() + element.getHeight(); } else if (BOTTOM.equals(direction)) { offset = nifty.getRenderEngine().getHeight() - element.getY(); } else { offset = 0; } if ("out".equals(mode)) { startOffset = 0; offsetDir = -1; withTarget = false; } else if ("in".equals(mode)) { startOffset = offset; offsetDir = 1; withTarget = false; } else if ("fromPosition".equals(mode)) { withTarget = true; } else if ("toPosition".equals(mode)) { withTarget = true; } else if ("fromOffset".equals(mode)) { fromOffset = true; startOffsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); startOffsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); offsetX = startOffsetX * -1; offsetY = startOffsetY * -1; } else if ("toOffset".equals(mode)) { toOffset = true; startOffsetX = 0; startOffsetY = 0; offsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); offsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); } String target = parameter.getProperty("targetElement"); if (target != null) { TargetElementResolver resolver = new TargetElementResolver(nifty.getCurrentScreen(), element); Element targetElement = resolver.resolve(target); if (targetElement == null) { log.warning("move effect for element [" + element.getId() + "] was unable to find target element [" + target + "] at screen [" + nifty.getCurrentScreen().getScreenId() + "]"); return; } if ("fromPosition".equals(mode)) { startOffsetX = targetElement.getX() - element.getX(); startOffsetY = targetElement.getY() - element.getY(); offsetX = -(targetElement.getX() - element.getX()); offsetY = -(targetElement.getY() - element.getY()); } else if ("toPosition".equals(mode)) { startOffsetX = 0; startOffsetY = 0; offsetX = (targetElement.getX() - element.getX()); offsetY = (targetElement.getY() - element.getY()); } } }
diff --git a/webit-script/src/main/java/webit/script/resolvers/impl/IterGetResolver.java b/webit-script/src/main/java/webit/script/resolvers/impl/IterGetResolver.java index 4f48f1b1..2d1264c4 100644 --- a/webit-script/src/main/java/webit/script/resolvers/impl/IterGetResolver.java +++ b/webit-script/src/main/java/webit/script/resolvers/impl/IterGetResolver.java @@ -1,61 +1,61 @@ // Copyright (c) 2013, Webit Team. All Rights Reserved. package webit.script.resolvers.impl; import webit.script.exceptions.ScriptRuntimeException; import webit.script.resolvers.GetResolver; import webit.script.resolvers.MatchMode; import webit.script.util.collection.Iter; /** * * @author Zqq */ public class IterGetResolver implements GetResolver { public MatchMode getMatchMode() { return MatchMode.INSTANCEOF; } public Class<?> getMatchClass() { return Iter.class; } public Object get(Object object, Object property) { Iter iter = (Iter) object; switch (property.hashCode()) { case 696759469: if ("hasNext".equals(property)) { return iter.hasNext(); } break; case 100346066: if ("index".equals(property)) { return iter.index(); } break; case 2058846118: if ("isFirst".equals(property)) { return iter.isFirst(); } break; case 3377907: if ("next".equals(property)) { return iter.next(); } break; case -1180529308: if ("isEven".equals(property)) { - return iter.index() % 2 == 0; + return iter.index() % 2 == 1; //Note: when index start by 0 } break; case 100474789: if ("isOdd".equals(property)) { - return iter.index() % 2 == 1; + return iter.index() % 2 == 0; //Note: when index start by 0 } break; } throw new ScriptRuntimeException("Invalid property or can't read: webit.tl.util.collection.Iter#" + property); } }
false
true
public Object get(Object object, Object property) { Iter iter = (Iter) object; switch (property.hashCode()) { case 696759469: if ("hasNext".equals(property)) { return iter.hasNext(); } break; case 100346066: if ("index".equals(property)) { return iter.index(); } break; case 2058846118: if ("isFirst".equals(property)) { return iter.isFirst(); } break; case 3377907: if ("next".equals(property)) { return iter.next(); } break; case -1180529308: if ("isEven".equals(property)) { return iter.index() % 2 == 0; } break; case 100474789: if ("isOdd".equals(property)) { return iter.index() % 2 == 1; } break; } throw new ScriptRuntimeException("Invalid property or can't read: webit.tl.util.collection.Iter#" + property); }
public Object get(Object object, Object property) { Iter iter = (Iter) object; switch (property.hashCode()) { case 696759469: if ("hasNext".equals(property)) { return iter.hasNext(); } break; case 100346066: if ("index".equals(property)) { return iter.index(); } break; case 2058846118: if ("isFirst".equals(property)) { return iter.isFirst(); } break; case 3377907: if ("next".equals(property)) { return iter.next(); } break; case -1180529308: if ("isEven".equals(property)) { return iter.index() % 2 == 1; //Note: when index start by 0 } break; case 100474789: if ("isOdd".equals(property)) { return iter.index() % 2 == 0; //Note: when index start by 0 } break; } throw new ScriptRuntimeException("Invalid property or can't read: webit.tl.util.collection.Iter#" + property); }
diff --git a/java/marytts/features/FeatureDefinition.java b/java/marytts/features/FeatureDefinition.java index e80e901c6..952aac3df 100644 --- a/java/marytts/features/FeatureDefinition.java +++ b/java/marytts/features/FeatureDefinition.java @@ -1,1723 +1,1722 @@ /** * Copyright 2006 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * This file is part of MARY TTS. * * MARY TTS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package marytts.features; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import marytts.util.io.StreamUtils; import marytts.util.string.ByteStringTranslator; import marytts.util.string.IntStringTranslator; import marytts.util.string.ShortStringTranslator; /** * A feature definition object represents the "meaning" of feature vectors. * It consists of a list of byte-valued, short-valued and continuous features * by name and index position in the feature vector; * the respective possible feature values (and corresponding byte and short * codes); * and, optionally, the weights and, for continuous features, weighting functions * for each feature. * @author Marc Schr&ouml;der * */ public class FeatureDefinition { public static final String BYTEFEATURES = "ByteValuedFeatureProcessors"; public static final String SHORTFEATURES = "ShortValuedFeatureProcessors"; public static final String CONTINUOUSFEATURES = "ContinuousFeatureProcessors"; public static final String FEATURESIMILARITY = "FeatureSimilarity"; public static final char WEIGHT_SEPARATOR = '|'; public static final String EDGEFEATURE = "edge"; public static final String EDGEFEATURE_START = "start"; public static final String EDGEFEATURE_END = "end"; public static final String NULLVALUE = "0"; private int numByteFeatures; private int numShortFeatures; private int numContinuousFeatures; private float[] featureWeights; private IntStringTranslator featureNames; // feature values: for byte and short features only private ByteStringTranslator[] byteFeatureValues; private ShortStringTranslator[] shortFeatureValues; private String[] floatWeightFuncts; // for continuous features only private float[][][] similarityMatrices = null; /** * Create a feature definition object, reading textual data * from the given BufferedReader. * @param input a BufferedReader from which a textual feature definition * can be read. * @param readWeights a boolean indicating whether or not to read * weights from input. If weights are read, they will be normalized * so that they sum to one. * @throws IOException if a reading problem occurs * */ public FeatureDefinition(BufferedReader input, boolean readWeights) throws IOException { // Section BYTEFEATURES String line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); while ( line.matches("^\\s*#.*") || line.matches("\\s*") ) { line = input.readLine(); } if (!line.trim().equals(BYTEFEATURES)) { throw new IOException("Unexpected input: expected '"+BYTEFEATURES+"', read '"+line+"'"); } List<String> byteFeatureLines = new ArrayList<String>(); while (true) { line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); line = line.trim(); if (line.equals(SHORTFEATURES)) break; // Found end of section byteFeatureLines.add(line); } // Section SHORTFEATURES List<String> shortFeatureLines = new ArrayList<String>(); while (true) { line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); line = line.trim(); if (line.equals(CONTINUOUSFEATURES)) break; // Found end of section shortFeatureLines.add(line); } // Section CONTINUOUSFEATURES List<String> continuousFeatureLines = new ArrayList<String>(); boolean readFeatureSimilarity = false; while ((line = input.readLine()) != null) { // it's OK if we hit the end of the file now line = line.trim(); //if (line.equals(FEATURESIMILARITY) || line.equals("")) break; // Found end of section if ( line.equals(FEATURESIMILARITY) ) { //readFeatureSimilarityMatrices(input); readFeatureSimilarity = true; break; } else if (line.equals("")) { // empty line: end of section break; } continuousFeatureLines.add(line); } numByteFeatures = byteFeatureLines.size(); numShortFeatures = shortFeatureLines.size(); numContinuousFeatures = continuousFeatureLines.size(); int total = numByteFeatures+numShortFeatures+numContinuousFeatures; featureNames = new IntStringTranslator(total); byteFeatureValues = new ByteStringTranslator[numByteFeatures]; shortFeatureValues = new ShortStringTranslator[numShortFeatures]; float sumOfWeights = 0; // for normalisation of weights if (readWeights) { featureWeights = new float[total]; floatWeightFuncts = new String[numContinuousFeatures]; } for (int i=0; i<numByteFeatures; i++) { line = byteFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is simply the float number: featureWeights[i] = Float.parseFloat(weightDef); sumOfWeights += featureWeights[i]; if (featureWeights[i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); } else { featureDef = line; } // Now featureDef is a String in which the feature name and all feature values // are separated by white space. String[] nameAndValues = featureDef.split("\\s+", 2); featureNames.set(i, nameAndValues[0]); // the feature name byteFeatureValues[i] = new ByteStringTranslator(nameAndValues[1].split("\\s+")); // the feature values } for (int i=0; i<numShortFeatures; i++) { line = shortFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is simply the float number: featureWeights[numByteFeatures+i] = Float.parseFloat(weightDef); sumOfWeights += featureWeights[numByteFeatures+i]; if (featureWeights[numByteFeatures+i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); } else { featureDef = line; } // Now featureDef is a String in which the feature name and all feature values // are separated by white space. String[] nameAndValues = featureDef.split("\\s+", 2); featureNames.set(numByteFeatures+i, nameAndValues[0]); // the feature name shortFeatureValues[i] = new ShortStringTranslator(nameAndValues[1].split("\\s+")); // the feature values } for (int i=0; i<numContinuousFeatures; i++) { line = continuousFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is the float number plus a definition of a weight function: String[] weightAndFunction = weightDef.split("\\s+", 2); featureWeights[numByteFeatures+numShortFeatures+i] = Float.parseFloat(weightAndFunction[0]); sumOfWeights += featureWeights[numByteFeatures+numShortFeatures+i]; if (featureWeights[numByteFeatures+numShortFeatures+i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); try { floatWeightFuncts[i] = weightAndFunction[1]; } catch ( ArrayIndexOutOfBoundsException e ) { // System.out.println( "weightDef string was: '" + weightDef + "'." ); // System.out.println( "Splitting part 1: '" + weightAndFunction[0] + "'." ); // System.out.println( "Splitting part 2: '" + weightAndFunction[1] + "'." ); throw new RuntimeException( "The string [" + weightDef + "] appears to be a badly formed" + " weight plus weighting function definition." ); } } else { featureDef = line; } // Now featureDef is the feature name // or the feature name followed by the word "float" if (featureDef.endsWith("float")){ String[] featureDefSplit = featureDef.split("\\s+", 2); featureNames.set(numByteFeatures+numShortFeatures+i, featureDefSplit[0]); } else { featureNames.set(numByteFeatures+numShortFeatures+i, featureDef); } } // Normalize weights to sum to one: if (readWeights) { for (int i=0; i<total; i++) { featureWeights[i] /= sumOfWeights; } } // read feature similarities here, if any if ( readFeatureSimilarity ) { readFeatureSimilarityMatrices(input); } - input.close(); } /** * read similarity matrices from feature definition file * @param input * @throws IOException */ private void readFeatureSimilarityMatrices(BufferedReader input) throws IOException { String line = null; similarityMatrices = new float[this.getNumberOfByteFeatures()][][]; for ( int i=0; i < this.getNumberOfByteFeatures(); i++ ) { similarityMatrices[i] = null; } while ( (line = input.readLine()) != null) { if ( "".equals(line) ) { return; } String[] featureUniqueValues = line.trim().split("\\s+"); String featureName = featureUniqueValues[0]; if ( !isByteFeature(featureName) ) { throw new RuntimeException("Similarity matrix support is for bytefeatures only, but not for other feature types..."); } int featureIndex = this.getFeatureIndex(featureName); int noUniqValues = featureUniqueValues.length - 1; similarityMatrices[featureIndex] = new float[noUniqValues][noUniqValues]; for ( int i=1; i <= noUniqValues; i++ ) { Arrays.fill(similarityMatrices[featureIndex][i-1], 0); String featureValue = featureUniqueValues[i]; String matLine = input.readLine(); if ( matLine == null ) { throw new RuntimeException("Feature definition file is having unexpected format..."); } String[] lines = matLine.trim().split("\\s+"); if( !featureValue.equals(lines[0]) ){ throw new RuntimeException("Feature definition file is having unexpected format..."); } if( lines.length != i){ throw new RuntimeException("Feature definition file is having unexpected format..."); } for ( int j=1; j < i; j++ ) { float similarity = (new Float(lines[j])).floatValue(); similarityMatrices[featureIndex][i-1][j-1] = similarity; similarityMatrices[featureIndex][j-1][i-1] = similarity; } } } } /** * Create a feature definition object, reading binary data * from the given DataInput. * @param input a DataInputStream or a RandomAccessFile from which * a binary feature definition can be read. * @throws IOException if a reading problem occurs */ public FeatureDefinition(DataInput input) throws IOException { // Section BYTEFEATURES numByteFeatures = input.readInt(); byteFeatureValues = new ByteStringTranslator[numByteFeatures]; // Initialise global arrays to byte feature length first; // we have no means of knowing how many short or continuous // features there will be, so we need to resize later. // This will happen automatically for featureNames, but needs // to be done by hand for featureWeights. featureNames = new IntStringTranslator(numByteFeatures); featureWeights = new float[numByteFeatures]; // There is no need to normalise weights here, because // they have already been normalized before the binary // file was written. for (int i=0; i<numByteFeatures; i++) { featureWeights[i] = input.readFloat(); String featureName = input.readUTF(); featureNames.set(i, featureName); byte numberOfValuesEncoded = input.readByte(); // attention: this is an unsigned byte int numberOfValues = numberOfValuesEncoded & 0xFF; byteFeatureValues[i] = new ByteStringTranslator(numberOfValues); for (int b=0; b<numberOfValues; b++) { String value = input.readUTF(); byteFeatureValues[i].set((byte)b, value); } } // Section SHORTFEATURES numShortFeatures = input.readInt(); if (numShortFeatures > 0) { shortFeatureValues = new ShortStringTranslator[numShortFeatures]; // resize weight array: float[] newWeights = new float[numByteFeatures+numShortFeatures]; System.arraycopy(featureWeights, 0, newWeights, 0, numByteFeatures); featureWeights = newWeights; for (int i=0; i<numShortFeatures; i++) { featureWeights[numByteFeatures+i] = input.readFloat(); String featureName = input.readUTF(); featureNames.set(numByteFeatures+i, featureName); short numberOfValues = input.readShort(); shortFeatureValues[i] = new ShortStringTranslator(numberOfValues); for (short s=0; s<numberOfValues; s++) { String value = input.readUTF(); shortFeatureValues[i].set(s, value); } } } // Section CONTINUOUSFEATURES numContinuousFeatures = input.readInt(); floatWeightFuncts = new String[numContinuousFeatures]; if (numContinuousFeatures > 0) { // resize weight array: float[] newWeights = new float[numByteFeatures+numShortFeatures+numContinuousFeatures]; System.arraycopy(featureWeights, 0, newWeights, 0, numByteFeatures+numShortFeatures); featureWeights = newWeights; } for (int i=0; i<numContinuousFeatures; i++) { featureWeights[numByteFeatures+numShortFeatures+i] = input.readFloat(); floatWeightFuncts[i] = input.readUTF(); String featureName = input.readUTF(); featureNames.set(numByteFeatures+numShortFeatures+i, featureName); } } /** * Create a feature definition object, reading binary data * from the given byte buffer. * @param input a byte buffer from which * a binary feature definition can be read. * @throws IOException if a reading problem occurs */ public FeatureDefinition(ByteBuffer bb) throws IOException { // Section BYTEFEATURES numByteFeatures = bb.getInt(); byteFeatureValues = new ByteStringTranslator[numByteFeatures]; // Initialise global arrays to byte feature length first; // we have no means of knowing how many short or continuous // features there will be, so we need to resize later. // This will happen automatically for featureNames, but needs // to be done by hand for featureWeights. featureNames = new IntStringTranslator(numByteFeatures); featureWeights = new float[numByteFeatures]; // There is no need to normalise weights here, because // they have already been normalized before the binary // file was written. for (int i=0; i<numByteFeatures; i++) { featureWeights[i] = bb.getFloat(); String featureName = StreamUtils.readUTF(bb); featureNames.set(i, featureName); byte numberOfValuesEncoded = bb.get(); // attention: this is an unsigned byte int numberOfValues = numberOfValuesEncoded & 0xFF; byteFeatureValues[i] = new ByteStringTranslator(numberOfValues); for (int b=0; b<numberOfValues; b++) { String value = StreamUtils.readUTF(bb); byteFeatureValues[i].set((byte)b, value); } } // Section SHORTFEATURES numShortFeatures = bb.getInt(); if (numShortFeatures > 0) { shortFeatureValues = new ShortStringTranslator[numShortFeatures]; // resize weight array: float[] newWeights = new float[numByteFeatures+numShortFeatures]; System.arraycopy(featureWeights, 0, newWeights, 0, numByteFeatures); featureWeights = newWeights; for (int i=0; i<numShortFeatures; i++) { featureWeights[numByteFeatures+i] = bb.getFloat(); String featureName = StreamUtils.readUTF(bb); featureNames.set(numByteFeatures+i, featureName); short numberOfValues = bb.getShort(); shortFeatureValues[i] = new ShortStringTranslator(numberOfValues); for (short s=0; s<numberOfValues; s++) { String value = StreamUtils.readUTF(bb); shortFeatureValues[i].set(s, value); } } } // Section CONTINUOUSFEATURES numContinuousFeatures = bb.getInt(); floatWeightFuncts = new String[numContinuousFeatures]; if (numContinuousFeatures > 0) { // resize weight array: float[] newWeights = new float[numByteFeatures+numShortFeatures+numContinuousFeatures]; System.arraycopy(featureWeights, 0, newWeights, 0, numByteFeatures+numShortFeatures); featureWeights = newWeights; } for (int i=0; i<numContinuousFeatures; i++) { featureWeights[numByteFeatures+numShortFeatures+i] = bb.getFloat(); floatWeightFuncts[i] = StreamUtils.readUTF(bb); String featureName = StreamUtils.readUTF(bb); featureNames.set(numByteFeatures+numShortFeatures+i, featureName); } } /** * Write this feature definition in binary format to the given * output. * @param out a DataOutputStream or RandomAccessFile to which the * FeatureDefinition should be written. * @throws IOException if a problem occurs while writing. */ public void writeBinaryTo(DataOutput out) throws IOException { // TODO to avoid duplicate code, replace this with writeBinaryTo(out, List<Integer>()) or some such // Section BYTEFEATURES out.writeInt(numByteFeatures); for (int i=0; i<numByteFeatures; i++) { if (featureWeights != null) { out.writeFloat(featureWeights[i]); } else { out.writeFloat(0); } out.writeUTF(getFeatureName(i)); int numValues = getNumberOfValues(i); byte numValuesEncoded = (byte) numValues; // an unsigned byte out.writeByte(numValuesEncoded); for (int b=0; b<numValues; b++) { String value = getFeatureValueAsString(i, b); out.writeUTF(value); } } // Section SHORTFEATURES out.writeInt(numShortFeatures); for (int i=numByteFeatures; i<numByteFeatures+numShortFeatures; i++) { if (featureWeights != null) { out.writeFloat(featureWeights[i]); } else { out.writeFloat(0); } out.writeUTF(getFeatureName(i)); short numValues = (short) getNumberOfValues(i); out.writeShort(numValues); for (short b=0; b<numValues; b++) { String value = getFeatureValueAsString(i, b); out.writeUTF(value); } } // Section CONTINUOUSFEATURES out.writeInt(numContinuousFeatures); for (int i=numByteFeatures+numShortFeatures; i<numByteFeatures+numShortFeatures+numContinuousFeatures; i++) { if (featureWeights != null) { out.writeFloat(featureWeights[i]); out.writeUTF(floatWeightFuncts[i-numByteFeatures-numShortFeatures]); } else { out.writeFloat(0); out.writeUTF(""); } out.writeUTF(getFeatureName(i)); } } /** * Write this feature definition in binary format to the given * output, dropping featuresToDrop * @param out a DataOutputStream or RandomAccessFile to which the * FeatureDefinition should be written. * @param featuresToDrop List of Integers containing the indices of features to drop from DataOutputStream * @throws IOException if a problem occurs while writing. */ private void writeBinaryTo(DataOutput out, List<Integer> featuresToDrop) throws IOException { // how many features of each type are to be dropped int droppedByteFeatures = 0; int droppedShortFeatures = 0; int droppedContinuousFeatures = 0; for (int f : featuresToDrop) { if (f < numByteFeatures) { droppedByteFeatures++; } else if (f < numByteFeatures + numShortFeatures) { droppedShortFeatures++; } else if (f < numByteFeatures + numShortFeatures + numContinuousFeatures) { droppedContinuousFeatures++; } } // Section BYTEFEATURES out.writeInt(numByteFeatures - droppedByteFeatures); for (int i=0; i<numByteFeatures; i++) { if (featuresToDrop.contains(i)) { continue; } if (featureWeights != null) { out.writeFloat(featureWeights[i]); } else { out.writeFloat(0); } out.writeUTF(getFeatureName(i)); int numValues = getNumberOfValues(i); byte numValuesEncoded = (byte) numValues; // an unsigned byte out.writeByte(numValuesEncoded); for (int b=0; b<numValues; b++) { String value = getFeatureValueAsString(i, b); out.writeUTF(value); } } // Section SHORTFEATURES out.writeInt(numShortFeatures - droppedShortFeatures); for (int i=numByteFeatures; i<numByteFeatures+numShortFeatures; i++) { if (featuresToDrop.contains(i)) { continue; } if (featureWeights != null) { out.writeFloat(featureWeights[i]); } else { out.writeFloat(0); } out.writeUTF(getFeatureName(i)); short numValues = (short) getNumberOfValues(i); out.writeShort(numValues); for (short b=0; b<numValues; b++) { String value = getFeatureValueAsString(i, b); out.writeUTF(value); } } // Section CONTINUOUSFEATURES out.writeInt(numContinuousFeatures - droppedContinuousFeatures); for (int i=numByteFeatures+numShortFeatures; i<numByteFeatures+numShortFeatures+numContinuousFeatures; i++) { if (featuresToDrop.contains(i)) { continue; } if (featureWeights != null) { out.writeFloat(featureWeights[i]); out.writeUTF(floatWeightFuncts[i-numByteFeatures-numShortFeatures]); } else { out.writeFloat(0); out.writeUTF(""); } out.writeUTF(getFeatureName(i)); } } /** * Get the total number of features. * @return the number of features */ public int getNumberOfFeatures() { return numByteFeatures+numShortFeatures+numContinuousFeatures; } /** * Get the number of byte features. * @return the number of features */ public int getNumberOfByteFeatures() { return numByteFeatures; } /** * Get the number of short features. * @return the number of features */ public int getNumberOfShortFeatures() { return numShortFeatures; } /** * Get the number of continuous features. * @return the number of features */ public int getNumberOfContinuousFeatures() { return numContinuousFeatures; } /** * For the feature with the given index, return the weight. * @param featureIndex * @return a non-negative weight. */ public float getWeight(int featureIndex) { return featureWeights[featureIndex]; } public float[] getFeatureWeights() { return featureWeights; } /** * Get the name of any weighting function associated with the * given feature index. For byte-valued and short-valued features, * this method will always return null; for continuous features, * the method will return the name of a weighting function, or null. * @param featureIndex * @return the name of a weighting function, or null */ public String getWeightFunctionName(int featureIndex) { return floatWeightFuncts[featureIndex-numByteFeatures-numShortFeatures]; } ////////////////////// META-INFORMATION METHODS /////////////////////// /** * Translate between a feature index and a feature name. * @param index a feature index, as could be used to access * a feature value in a FeatureVector. * @return the name of the feature corresponding to the index * @throws IndexOutOfBoundsException if index<0 or index>getNumberOfFeatures() */ public String getFeatureName(int index) { return featureNames.get(index); } /** * Translate between an array of feature indexes and an array of feature names. * @param index an array of feature indexes, as could be used to access * a feature value in a FeatureVector. * @return an array with the name of the features corresponding to the index * @throws IndexOutOfBoundsException if any of the indexes is <0 or >getNumberOfFeatures() */ public String[] getFeatureNameArray(int[] index) { String[] ret = new String[index.length]; for ( int i = 0; i < index.length; i++ ) { ret[i] = getFeatureName( index[i] ); } return( ret ); } /** * Get names of all features * @return an array of all feature name strings */ public String[] getFeatureNameArray() { String[] names = new String[getNumberOfFeatures()]; for ( int i = 0; i < names.length; i++ ) { names[i] = getFeatureName(i); } return(names); } /** * Get names of byte features * @return an array of byte feature name strings */ public String[] getByteFeatureNameArray() { String[] byteFeatureNames = new String[numByteFeatures]; for (int i = 0; i < numByteFeatures; i++) { assert isByteFeature(i); byteFeatureNames[i] = getFeatureName(i); } return byteFeatureNames; } /** * Get names of short features * @return an array of short feature name strings */ public String[] getShortFeatureNameArray() { String[] shortFeatureNames = new String[numShortFeatures]; for (int i = 0; i < numShortFeatures; i++) { int shortFeatureIndex = numByteFeatures + i; assert isShortFeature(shortFeatureIndex); shortFeatureNames[i] = getFeatureName(shortFeatureIndex); } return shortFeatureNames; } /** * Get names of continuous features * @return an array of continuous feature name strings */ public String[] getContinuousFeatureNameArray() { String[] continuousFeatureNames = new String[numContinuousFeatures]; for (int i = 0; i < numContinuousFeatures; i++) { int continuousFeatureIndex = numByteFeatures + numShortFeatures + i; assert isContinuousFeature(continuousFeatureIndex); continuousFeatureNames[i] = getFeatureName(continuousFeatureIndex); } return continuousFeatureNames; } /** * List all feature names, separated by white space, * in their order of definition. * @return */ public String getFeatureNames() { StringBuilder buf = new StringBuilder(); for (int i=0, n=getNumberOfFeatures(); i<n; i++) { if (buf.length() > 0) buf.append(" "); buf.append(featureNames.get(i)); } return buf.toString(); } /** * Indicate whether the feature definition contains the feature with the given name * @param name the feature name in question, e.g. "next_next_phone" * @return */ public boolean hasFeature(String name) { return featureNames.contains(name); } /** * Query a feature as identified by the given featureName as to whether the given featureValue * is a known value of that feature. In other words, this will return true exactly if * the given feature is a byte feature and getFeatureValueAsByte(featureName, featureValue) will not throw an exception * or if the given feature is a short feature and getFeatureValueAsShort(featureName, featureValue) will not throw an exception. * * @param featureName * @param featureValue * @return */ public boolean hasFeatureValue(String featureName, String featureValue) { return hasFeatureValue(getFeatureIndex(featureName), featureValue); } /** * Query a feature as identified by the given featureIndex as to whether the given featureValue * is a known value of that feature. In other words, this will return true exactly if * the given feature is a byte feature and getFeatureValueAsByte(featureIndex, featureValue) will not throw an exception * or if the given feature is a short feature and getFeatureValueAsShort(featureIndex, featureValue) will not throw an exception. * * @param featureIndex * @param featureValue * @return */ public boolean hasFeatureValue(int featureIndex, String featureValue) { if (featureIndex < 0) { return false; } if (featureIndex < numByteFeatures) { return byteFeatureValues[featureIndex].contains(featureValue); } if (featureIndex < numByteFeatures+numShortFeatures) { return shortFeatureValues[featureIndex-numByteFeatures].contains(featureValue); } return false; } /** * Determine whether the feature with the given name is a byte feature. * @param featureName * @return true if the feature is a byte feature, false if the feature * is not known or is not a byte feature */ public boolean isByteFeature(String featureName) { try { int index = getFeatureIndex(featureName); return isByteFeature(index); } catch (Exception e) { return false; } } /** * Determine whether the feature with the given index number is a byte feature. * @param featureIndex * @return true if the feature is a byte feature, false if the feature * is not a byte feature or is invalid */ public boolean isByteFeature(int index) { return 0<=index && index < numByteFeatures; } /** * Determine whether the feature with the given name is a short feature. * @param featureName * @return true if the feature is a short feature, false if the feature * is not known or is not a short feature */ public boolean isShortFeature(String featureName) { try { int index = getFeatureIndex(featureName); return isShortFeature(index); } catch (Exception e) { return false; } } /** * Determine whether the feature with the given index number is a short feature. * @param featureIndex * @return true if the feature is a short feature, false if the feature * is not a short feature or is invalid */ public boolean isShortFeature(int index) { index -= numByteFeatures; return 0<=index && index < numShortFeatures; } /** * Determine whether the feature with the given name is a continuous feature. * @param featureName * @return true if the feature is a continuous feature, false if the feature * is not known or is not a continuous feature */ public boolean isContinuousFeature(String featureName) { try { int index = getFeatureIndex(featureName); return isContinuousFeature(index); } catch (Exception e) { return false; } } /** * Determine whether the feature with the given index number is a continuous feature. * @param featureIndex * @return true if the feature is a continuous feature, false if the feature * is not a continuous feature or is invalid */ public boolean isContinuousFeature(int index) { index -= numByteFeatures; index -= numShortFeatures; return 0<=index && index < numContinuousFeatures; } /** * true, if given feature index contains similarity matrix * @param featureIndex * @return */ public boolean hasSimilarityMatrix(int featureIndex) { if ( featureIndex >= this.getNumberOfByteFeatures() ) { return false; } if ( this.similarityMatrices != null && this.similarityMatrices[featureIndex] != null ) { return true; } return false; } /** * true, if given feature name contains similarity matrix * @param featureName * @return */ public boolean hasSimilarityMatrix(String featureName) { return hasSimilarityMatrix(this.getFeatureIndex(featureName)); } /** * To get a similarity between two feature values * @param featureIndex * @param i * @param j * @return */ public float getSimilarity(int featureIndex, byte i, byte j) { if ( !hasSimilarityMatrix(featureIndex) ) { throw new RuntimeException("the given feature index "); } return this.similarityMatrices[featureIndex][i][j]; } /** * Translate between a feature name and a feature index. * @param featureName a valid feature name * @return a feature index, as could be used to access * a feature value in a FeatureVector. * @throws IllegalArgumentException if the feature name is unknown. */ public int getFeatureIndex(String featureName) { return featureNames.get(featureName); } /** * Translate between an array of feature names and an array of feature indexes. * @param featureName an array of valid feature names * @return an array of feature indexes, as could be used to access * a feature value in a FeatureVector. * @throws IllegalArgumentException if one of the feature names is unknown. */ public int[] getFeatureIndexArray(String[] featureName) { int[] ret = new int[featureName.length]; for ( int i = 0; i < featureName.length; i++ ) { ret[i] = getFeatureIndex( featureName[i] ); } return( ret ); } /** * Get the number of possible values for the feature with the given index number. * This method must only be called for byte-valued or short-valued features. * @param featureIndex the index number of the feature. * @return for byte-valued and short-valued features, return the number of values. * @throws IndexOutOfBoundsException if featureIndex < 0 or * featureIndex >= getNumberOfByteFeatures() + getNumberOfShortFeatures(). */ public int getNumberOfValues(int featureIndex) { if (featureIndex < numByteFeatures) return byteFeatureValues[featureIndex].getNumberOfValues(); featureIndex -= numByteFeatures; if (featureIndex < numShortFeatures) return shortFeatureValues[featureIndex].getNumberOfValues(); throw new IndexOutOfBoundsException("Feature no. "+featureIndex+" is not a byte-valued or short-valued feature"); } /** * Get the list of possible String values for the feature with the given index number. * This method must only be called for byte-valued or short-valued features. * The position in the String array corresponds to the byte or short value of the * feature obtained from a FeatureVector. * @param featureIndex the index number of the feature. * @return for byte-valued and short-valued features, return the array of String values. * @throws IndexOutOfBoundsException if featureIndex < 0 or * featureIndex >= getNumberOfByteFeatures() + getNumberOfShortFeatures(). */ public String[] getPossibleValues(int featureIndex) { if (featureIndex < numByteFeatures) return byteFeatureValues[featureIndex].getStringValues(); featureIndex -= numByteFeatures; if (featureIndex < numShortFeatures) return shortFeatureValues[featureIndex].getStringValues(); throw new IndexOutOfBoundsException("Feature no. "+featureIndex+" is not a byte-valued or short-valued feature"); } /** * For the feature with the given index number, translate its byte or short value * to its String value. * This method must only be called for byte-valued or short-valued features. * @param featureIndex the index number of the feature. * @param value the feature value. This must be in the range of acceptable values for * the given feature. * @return for byte-valued and short-valued features, return the String representation * of the feature value. * @throws IndexOutOfBoundsException if featureIndex < 0 or * featureIndex >= getNumberOfByteFeatures() + getNumberOfShortFeatures() * @throws IndexOutOfBoundsException if value is not a legal value for this feature * * */ public String getFeatureValueAsString(int featureIndex, int value) { if (featureIndex < numByteFeatures) return byteFeatureValues[featureIndex].get((byte)value); featureIndex -= numByteFeatures; if (featureIndex < numShortFeatures) return shortFeatureValues[featureIndex].get((short)value); throw new IndexOutOfBoundsException("Feature no. "+featureIndex+" is not a byte-valued or short-valued feature"); } /** * Simple access to string-based features. * @param featureName * @param fv * @return */ public String getFeatureValueAsString(String featureName, FeatureVector fv) { int i = getFeatureIndex(featureName); return getFeatureValueAsString(i, fv.getFeatureAsInt(i)); } /** * For the feature with the given name, translate its String value * to its byte value. * This method must only be called for byte-valued features. * @param featureName the name of the feature. * @param value the feature value. This must be among the acceptable values for * the given feature. * @return for byte-valued features, return the byte representation * of the feature value. * @throws IllegalArgumentException if featureName is not a valid feature name, * or if featureName is not a byte-valued feature. * @throws IllegalArgumentException if value is not a legal value for this feature */ public byte getFeatureValueAsByte(String featureName, String value) { int featureIndex = getFeatureIndex(featureName); return getFeatureValueAsByte(featureIndex, value); } /** * For the feature with the given index number, translate its String value * to its byte value. * This method must only be called for byte-valued features. * @param featureName the name of the feature. * @param value the feature value. This must be among the acceptable values for * the given feature. * @return for byte-valued features, return the byte representation * of the feature value. * @throws IllegalArgumentException if featureName is not a valid feature name, * or if featureName is not a byte-valued feature. * @throws IllegalArgumentException if value is not a legal value for this feature */ public byte getFeatureValueAsByte(int featureIndex, String value) { if (featureIndex >= numByteFeatures) throw new IndexOutOfBoundsException("Feature no. "+featureIndex+" is not a byte-valued feature"); try { return byteFeatureValues[featureIndex].get(value); } catch (IllegalArgumentException iae) { StringBuilder message = new StringBuilder("Illegal value '"+value+"' for feature "+getFeatureName(featureIndex)+"; Legal values are:\n"); for (String v : getPossibleValues(featureIndex)) { message.append(" "+v); } throw new IllegalArgumentException(message.toString()); } } /** * For the feature with the given name, translate its String value * to its short value. * This method must only be called for short-valued features. * @param featureName the name of the feature. * @param value the feature value. This must be among the acceptable values for * the given feature. * @return for short-valued features, return the short representation * of the feature value. * @throws IllegalArgumentException if featureName is not a valid feature name, * or if featureName is not a short-valued feature. * @throws IllegalArgumentException if value is not a legal value for this feature */ public short getFeatureValueAsShort(String featureName, String value) { int featureIndex = getFeatureIndex(featureName); featureIndex -= numByteFeatures; if (featureIndex < numShortFeatures) return shortFeatureValues[featureIndex].get(value); throw new IndexOutOfBoundsException("Feature '"+featureName+"' is not a short-valued feature"); } /** * For the feature with the given name, translate its String value * to its short value. * This method must only be called for short-valued features. * @param featureName the name of the feature. * @param value the feature value. This must be among the acceptable values for * the given feature. * @return for short-valued features, return the short representation * of the feature value. * @throws IllegalArgumentException if featureName is not a valid feature name, * or if featureName is not a short-valued feature. * @throws IllegalArgumentException if value is not a legal value for this feature */ public short getFeatureValueAsShort(int featureIndex, String value) { featureIndex -= numByteFeatures; if (featureIndex < numShortFeatures) return shortFeatureValues[featureIndex].get(value); throw new IndexOutOfBoundsException("Feature no. "+featureIndex+" is not a short-valued feature"); } /** * Determine whether two feature definitions are equal, with respect * to number, names, and possible values of the three kinds of features * (byte-valued, short-valued, continuous). This method does not compare * any weights. * @param other the feature definition to compare to * @return true if all features and values are identical, false otherwise */ public boolean featureEquals(FeatureDefinition other) { if (numByteFeatures != other.numByteFeatures || numShortFeatures != other.numShortFeatures || numContinuousFeatures != other.numContinuousFeatures) return false; // Compare the feature names and values for byte and short features: for (int i=0; i<numByteFeatures+numShortFeatures+numContinuousFeatures; i++) { if (!getFeatureName(i).equals(other.getFeatureName(i))) return false; } // Compare the values for byte and short features: for (int i=0; i<numByteFeatures+numShortFeatures; i++) { if (getNumberOfValues(i) != other.getNumberOfValues(i)) return false; for (int v=0, n=getNumberOfValues(i); v<n; v++) { if (!getFeatureValueAsString(i, v).equals(other.getFeatureValueAsString(i, v))) return false; } } return true; } /** * An extension of the previous method. */ public String featureEqualsAnalyse(FeatureDefinition other) { if (numByteFeatures != other.numByteFeatures) { return( "The number of BYTE features differs: " + numByteFeatures + " versus " + other.numByteFeatures ); } if (numShortFeatures != other.numShortFeatures) { return( "The number of SHORT features differs: " + numShortFeatures + " versus " + other.numShortFeatures ); } if (numContinuousFeatures != other.numContinuousFeatures) { return( "The number of CONTINUOUS features differs: " + numContinuousFeatures + " versus " + other.numContinuousFeatures ); } // Compare the feature names and values for byte and short features: for (int i=0; i<numByteFeatures+numShortFeatures+numContinuousFeatures; i++) { if (!getFeatureName(i).equals(other.getFeatureName(i))) { return( "The feature name differs at position [" + i + "]: " + getFeatureName(i) + " versus " + other.getFeatureName(i) ); } } // Compare the values for byte and short features: for (int i=0; i<numByteFeatures+numShortFeatures; i++) { if (getNumberOfValues(i) != other.getNumberOfValues(i)) { return( "The number of values differs at position [" + i + "]: " + getNumberOfValues(i) + " versus " + other.getNumberOfValues(i) ); } for (int v=0, n=getNumberOfValues(i); v<n; v++) { if (!getFeatureValueAsString(i, v).equals(other.getFeatureValueAsString(i, v))) { return( "The feature value differs at position [" + i + "] for feature value [" + v + "]: " + getFeatureValueAsString(i, v) + " versus " + other.getFeatureValueAsString(i, v) ); } } } return ""; } /** * Determine whether two feature definitions are equal, regarding both * the actual feature definitions and the weights. * The comparison of weights will succeed if both have no weights or * if both have exactly the same weights * @param other the feature definition to compare to * @return true if all features, values and weights are identical, false otherwise * @see #featureEquals(FeatureDefinition) */ public boolean equals(FeatureDefinition other) { if (featureWeights == null) { if (other.featureWeights != null) return false; // Both are null } else { // featureWeights != null if (other.featureWeights == null) return false; // Both != null if (featureWeights.length != other.featureWeights.length) return false; for (int i=0; i<featureWeights.length; i++) { if (featureWeights[i] != other.featureWeights[i]) return false; } assert floatWeightFuncts != null; assert other.floatWeightFuncts != null; if (floatWeightFuncts.length != other.floatWeightFuncts.length) return false; for (int i=0; i<floatWeightFuncts.length; i++) { if (floatWeightFuncts[i] == null) { if (other.floatWeightFuncts[i] != null) return false; // Both are null } else { // != null if (other.floatWeightFuncts[i] == null) return false; // Both != null if (!floatWeightFuncts[i].equals(other.floatWeightFuncts[i])) return false; } } } // OK, weights are equal return featureEquals(other); } /** * Determine whether this FeatureDefinition is a superset of, or equal to, another FeatureDefinition. * <p> * Specifically, * <ol> * <li>every byte-valued feature in <b>other</b> must be in <b>this</b>, likewise for short-valued and continuous-valued * features;</li> * <li>for byte-valued and short-valued features, the possible feature values must be the same in <b>this</b> and * <b>other</b>.</li> * </ol> * @param other FeatureDefinition * @return <i>true</i> if * <ol> * <li>all features in <b>other</b> are also in <b>this</b>, and every feature in <b>other</b> is of the same type in * <b>this</b>; and</li> * <li>every feature in <b>other</b> has the same possible values as the feature in <b>this</b></li> * </ol> * <i>false</i> otherwise * @author steiner */ public boolean contains(FeatureDefinition other) { List<String> thisByteFeatures = Arrays.asList(this.getByteFeatureNameArray()); List<String> otherByteFeatures = Arrays.asList(other.getByteFeatureNameArray()); if (!thisByteFeatures.containsAll(otherByteFeatures)){ return false; } for (String commonByteFeature : otherByteFeatures){ String[] thisByteFeaturePossibleValues = this.getPossibleValues(this.getFeatureIndex(commonByteFeature)); String[] otherByteFeaturePossibleValues = other.getPossibleValues(other.getFeatureIndex(commonByteFeature)); if(!Arrays.equals(thisByteFeaturePossibleValues, otherByteFeaturePossibleValues)){ return false; } } List<String> thisShortFeatures = Arrays.asList(this.getShortFeatureNameArray()); List<String> otherShortFeatures = Arrays.asList(other.getShortFeatureNameArray()); if (!thisShortFeatures.containsAll(otherShortFeatures)){ return false; } for (String commonShortFeature : otherShortFeatures){ String[] thisShortFeaturePossibleValues = this.getPossibleValues(this.getFeatureIndex(commonShortFeature)); String[] otherShortFeaturePossibleValues = other.getPossibleValues(other.getFeatureIndex(commonShortFeature)); if(!Arrays.equals(thisShortFeaturePossibleValues, otherShortFeaturePossibleValues)){ return false; } } List<String> thisContinuousFeatures = Arrays.asList(this.getContinuousFeatureNameArray()); List<String> otherContinuousFeatures = Arrays.asList(other.getContinuousFeatureNameArray()); if (!thisContinuousFeatures.containsAll(otherContinuousFeatures)){ return false; } return true; } /** * Create a new FeatureDefinition that contains a subset of the features in this. * @param featureNamesToDrop array of Strings containing the names of the features to drop from the new FeatureDefinition * @return new FeatureDefinition * @author steiner */ public FeatureDefinition subset(String[] featureNamesToDrop){ // construct a list of indices for the features to be dropped: List<Integer> featureIndicesToDrop = new ArrayList<Integer>(); for (String featureName : featureNamesToDrop) { int featureIndex; try { featureIndex = getFeatureIndex(featureName); featureIndicesToDrop.add(featureIndex); } catch (IllegalArgumentException e) { System.err.println("WARNING: feature " + featureName + " not found in FeatureDefinition; ignoring."); } } // create a new FeatureDefinition by way of a byte array: FeatureDefinition subDefinition = null; try { ByteArrayOutputStream toMemory = new ByteArrayOutputStream(); DataOutput output = new DataOutputStream(toMemory); writeBinaryTo(output, featureIndicesToDrop); byte[] memory = toMemory.toByteArray(); ByteArrayInputStream fromMemory = new ByteArrayInputStream(memory); DataInput input = new DataInputStream(fromMemory); subDefinition = new FeatureDefinition(input); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // make sure that subDefinition really is a subset of this assert this.contains(subDefinition); return subDefinition; } /** * Create a feature vector consistent with this feature definition * by reading the data from a String representation. In that String, * the String values for each feature must be separated by white space. * For example, this format is created by toFeatureString(FeatureVector). * @param unitIndex an index number to assign to the feature vector * @param featureString the string representation of a feature vector. * @return the feature vector created from the String. * @throws IllegalArgumentException if the feature values listed are not * consistent with the feature definition. * @see #toFeatureString(FeatureVector) */ public FeatureVector toFeatureVector(int unitIndex, String featureString) { String[] featureValues = featureString.split("\\s+"); if (featureValues.length != numByteFeatures+numShortFeatures+numContinuousFeatures) throw new IllegalArgumentException("Expected "+(numByteFeatures+numShortFeatures+numContinuousFeatures)+" features, got "+featureValues.length); byte[] bytes = new byte[numByteFeatures]; short[] shorts = new short[numShortFeatures]; float[] floats = new float[numContinuousFeatures]; for (int i=0; i<numByteFeatures; i++) { bytes[i] = Byte.parseByte( featureValues[i] ); } for (int i=0; i<numShortFeatures; i++) { shorts[i] = Short.parseShort( featureValues[numByteFeatures+i] ); } for (int i=0; i<numContinuousFeatures; i++) { floats[i] = Float.parseFloat(featureValues[numByteFeatures+numShortFeatures+i]); } return new FeatureVector(bytes, shorts, floats, unitIndex); } public FeatureVector toFeatureVector(int unitIndex, byte[] bytes, short[] shorts, float[] floats) { if (!((numByteFeatures == 0 && bytes == null || numByteFeatures == bytes.length) && (numShortFeatures == 0 && shorts == null || numShortFeatures == shorts.length) && (numContinuousFeatures == 0 && floats == null || numContinuousFeatures == floats.length))) { throw new IllegalArgumentException("Expected "+numByteFeatures+" bytes (got "+(bytes == null ? "0" : bytes.length) + "), "+numShortFeatures+" shorts (got "+(shorts==null ? "0" : shorts.length) + "), "+numContinuousFeatures+" floats (got "+(floats==null ? "0" : floats.length)+")"); } return new FeatureVector(bytes, shorts, floats, unitIndex); } /** * Create a feature vector consistent with this feature definition * by reading the data from the given input. * @param input a DataInputStream or RandomAccessFile to read the feature values from. * @return a FeatureVector. */ public FeatureVector readFeatureVector(int currentUnitIndex, DataInput input) throws IOException { byte[] bytes = new byte[numByteFeatures]; input.readFully(bytes); short[] shorts = new short[numShortFeatures]; for (int i=0; i<shorts.length; i++) { shorts[i] = input.readShort(); } float[] floats = new float[numContinuousFeatures]; for (int i=0; i<floats.length; i++) { floats[i] = input.readFloat(); } return new FeatureVector(bytes, shorts, floats, currentUnitIndex); } /** * Create a feature vector consistent with this feature definition * by reading the data from the byte buffer. * @param bb a byte buffer to read the feature values from. * @return a FeatureVector. */ public FeatureVector readFeatureVector(int currentUnitIndex, ByteBuffer bb) throws IOException { byte[] bytes = new byte[numByteFeatures]; bb.get(bytes); short[] shorts = new short[numShortFeatures]; for (int i=0; i<shorts.length; i++) { shorts[i] = bb.getShort(); } float[] floats = new float[numContinuousFeatures]; for (int i=0; i<floats.length; i++) { floats[i] = bb.getFloat(); } return new FeatureVector(bytes, shorts, floats, currentUnitIndex); } /** * Create a feature vector that marks a start or end of a unit. * All feature values are set to the neutral value "0", except for * the EDGEFEATURE, which is set to start if start == true, to end otherwise. * @param unitIndex index of the unit * @param start true creates a start vector, false creates an end vector. * @return a feature vector representing an edge. */ public FeatureVector createEdgeFeatureVector(int unitIndex, boolean start) { int edgeFeature = getFeatureIndex(EDGEFEATURE); assert edgeFeature < numByteFeatures; // we can assume this is byte-valued byte edge; if (start) edge = getFeatureValueAsByte(edgeFeature, EDGEFEATURE_START); else edge = getFeatureValueAsByte(edgeFeature, EDGEFEATURE_END); byte[] bytes = new byte[numByteFeatures]; short[] shorts = new short[numShortFeatures]; float[] floats = new float[numContinuousFeatures]; for (int i=0; i<numByteFeatures; i++) { bytes[i] = getFeatureValueAsByte(i, NULLVALUE); } for (int i=0; i<numShortFeatures; i++) { shorts[i] = getFeatureValueAsShort(numByteFeatures+i, NULLVALUE); } for (int i=0; i<numContinuousFeatures; i++) { floats[i] = 0; } bytes[edgeFeature] = edge; return new FeatureVector(bytes, shorts, floats, unitIndex); } /** * Convert a feature vector into a String representation. * @param fv a feature vector which must be consistent with this feature definition. * @return a String containing the String values of all features, separated by white space. * @throws IllegalArgumentException if the feature vector is not consistent with this * feature definition * @throws IndexOutOfBoundsException if any value of the feature vector is not consistent with this * feature definition */ public String toFeatureString(FeatureVector fv) { if (numByteFeatures != fv.getNumberOfByteFeatures() || numShortFeatures != fv.getNumberOfShortFeatures() || numContinuousFeatures != fv.getNumberOfContinuousFeatures()) throw new IllegalArgumentException("Feature vector '"+fv+"' is inconsistent with feature definition"); StringBuilder buf = new StringBuilder(); for (int i=0; i<numByteFeatures; i++) { if (buf.length()>0) buf.append(" "); buf.append(getFeatureValueAsString(i, fv.getByteFeature(i))); } for (int i=numByteFeatures; i<numByteFeatures+numShortFeatures; i++) { if (buf.length()>0) buf.append(" "); buf.append(getFeatureValueAsString(i, fv.getShortFeature(i))); } for (int i=numByteFeatures+numShortFeatures; i<numByteFeatures+numShortFeatures+numContinuousFeatures; i++) { if (buf.length()>0) buf.append(" "); buf.append(fv.getContinuousFeature(i)); } return buf.toString(); } /** * Export this feature definition in the text format which can also be read by this class. * @param out the destination of the data * @param writeWeights whether to write weights before every line */ public void writeTo(PrintWriter out, boolean writeWeights) { out.println("ByteValuedFeatureProcessors"); for (int i=0; i<numByteFeatures; i++) { if (writeWeights) { out.print(featureWeights[i]+" | "); } out.print(getFeatureName(i)); for (int v=0, vmax=getNumberOfValues(i); v<vmax; v++) { out.print(" "); String val = getFeatureValueAsString(i, v); out.print(val); } out.println(); } out.println("ShortValuedFeatureProcessors"); for (int i=0; i<numShortFeatures; i++) { if (writeWeights) { out.print(featureWeights[numByteFeatures+i]+" | "); } out.print(getFeatureName(numByteFeatures+i)); for (int v=0, vmax=getNumberOfValues(numByteFeatures+i); v<vmax; v++) { out.print(" "); String val = getFeatureValueAsString(numByteFeatures+i, v); out.print(val); } out.println(); } out.println("ContinuousFeatureProcessors"); for (int i=0; i<numContinuousFeatures; i++) { if (writeWeights) { out.print(featureWeights[numByteFeatures+numShortFeatures+i]); out.print(" "); out.print(floatWeightFuncts[i]); out.print(" | "); } out.print(getFeatureName(numByteFeatures+numShortFeatures+i)); out.println(); } } /** * Export this feature definition in the "all.desc" format which can be * read by wagon. * @param out the destination of the data */ public void generateAllDotDescForWagon(PrintWriter out) { generateAllDotDescForWagon(out, null); } /** * Export this feature definition in the "all.desc" format which can be * read by wagon. * @param out the destination of the data * @param featuresToIgnore a set of Strings containing the names of features that * wagon should ignore. Can be null. */ public void generateAllDotDescForWagon(PrintWriter out, Set<String> featuresToIgnore) { out.println("("); out.println("(occurid cluster)"); for (int i=0, n=getNumberOfFeatures(); i<n; i++) { out.print("( "); String featureName = getFeatureName(i); out.print(featureName); if (featuresToIgnore != null && featuresToIgnore.contains(featureName)) { out.print(" ignore"); } if (i<numByteFeatures+numShortFeatures) { // list values for (int v=0, vmax=getNumberOfValues(i); v<vmax; v++) { out.print(" "); // Print values surrounded by double quotes, and make sure any // double quotes in the value are preceded by a backslash -- // otherwise, we get problems e.g. for sentence_punc String val = getFeatureValueAsString(i, v); if (val.indexOf('"') != -1) { StringBuilder buf = new StringBuilder(); for (int c=0; c<val.length(); c++) { char ch = val.charAt(c); if (ch == '"') buf.append("\\\""); else buf.append(ch); } val = buf.toString(); } out.print("\""+val+"\""); } out.println(" )"); } else { // float feature out.println(" float )"); } } out.println(")"); } /** * Print this feature definition plus weights to a .txt file * @param out the destination of the data */ public void generateFeatureWeightsFile(PrintWriter out) { out.println("# This file lists the features and their weights to be used for\n" +"# creating the MARY features file.\n" +"# The same file can also be used to override weights in a run-time system.\n" +"# Three sections are distinguished: Byte-valued, Short-valued, and\n" +"# Continuous features.\n" +"#\n" +"# Lines starting with '#' are ignored; they can be used for comments\n" +"# anywhere in the file. Empty lines are also ignored.\n" +"# Entries must have the following form:\n" +"# \n" +"# <weight definition> | <feature definition>\n" +"# \n" +"# For byte and short features, <weight definition> is simply the \n" +"# (float) number representing the weight.\n" +"# For continuous features, <weight definition> is the\n" +"# (float) number representing the weight, followed by an optional\n" +"# weighting function including arguments.\n" +"#\n" +"# The <feature definition> is the feature name, which in the case of\n" +"# byte and short features is followed by the full list of feature values.\n" +"#\n" +"# Note that the feature definitions must be identical between this file\n" +"# and all unit feature files for individual database utterances.\n" +"# THIS FILE WAS GENERATED AUTOMATICALLY"); out.println(); out.println("ByteValuedFeatureProcessors"); List<String> getValuesOf10 = new ArrayList<String>(); getValuesOf10.add("phone"); getValuesOf10.add("ph_vc"); getValuesOf10.add("prev_phone"); getValuesOf10.add("next_phone"); getValuesOf10.add("stressed"); getValuesOf10.add("syl_break"); getValuesOf10.add("prev_syl_break"); getValuesOf10.add("next_is_pause"); getValuesOf10.add("prev_is_pause"); List<String> getValuesOf5 = new ArrayList<String>(); getValuesOf5.add("cplace"); getValuesOf5.add("ctype"); getValuesOf5.add("cvox"); getValuesOf5.add("vfront"); getValuesOf5.add("vheight"); getValuesOf5.add("vlng"); getValuesOf5.add("vrnd"); getValuesOf5.add("vc"); for (int i=0; i<numByteFeatures; i++) { String featureName = getFeatureName(i); if (getValuesOf10.contains(featureName)){ out.print("10 | "+featureName); } else { boolean found = false; for (String match : getValuesOf5){ if (featureName.matches(".*"+match)){ out.print("5 | "+featureName); found=true; break; } } if (!found){ out.print("0 | "+featureName); } } for (int v=0, vmax=getNumberOfValues(i); v<vmax; v++) { String val = getFeatureValueAsString(i, v); out.print(" "+val); } out.print("\n"); } out.println("ShortValuedFeatureProcessors"); for (int i=numByteFeatures; i<numShortFeatures; i++) { String featureName = getFeatureName(i); out.print("0 | "+featureName); for (int v=0, vmax=getNumberOfValues(i); v<vmax; v++) { String val = getFeatureValueAsString(i, v); out.print(" "+val); } out.print("\n"); } out.println("ContinuousFeatureProcessors"); for (int i=numByteFeatures; i<numByteFeatures+numContinuousFeatures; i++) { String featureName = getFeatureName(i); out.println("0 linear | "+featureName); } out.flush(); out.close(); } /** * Compares two feature vectors in terms of how many discrete features they have in common. * WARNING: this assumes that the feature vectors are issued from the same * FeatureDefinition; only the number of features is checked for compatibility. * * @param v1 A feature vector. * @param v2 Another feature vector to compare v1 with. * @return The number of common features. */ public static int diff( FeatureVector v1, FeatureVector v2 ) { int ret = 0; /* Byte valued features */ if ( v1.byteValuedDiscreteFeatures.length < v2.byteValuedDiscreteFeatures.length ) { throw new RuntimeException( "v1 and v2 don't have the same number of byte-valued features: [" + v1.byteValuedDiscreteFeatures.length + "] versus [" + v2.byteValuedDiscreteFeatures.length + "]." ); } for ( int i = 0; i < v1.byteValuedDiscreteFeatures.length; i++ ) { if ( v1.byteValuedDiscreteFeatures[i] == v2.byteValuedDiscreteFeatures[i] ) ret++; } /* Short valued features */ if ( v1.shortValuedDiscreteFeatures.length < v2.shortValuedDiscreteFeatures.length ) { throw new RuntimeException( "v1 and v2 don't have the same number of short-valued features: [" + v1.shortValuedDiscreteFeatures.length + "] versus [" + v2.shortValuedDiscreteFeatures.length + "]." ); } for ( int i = 0; i < v1.shortValuedDiscreteFeatures.length; i++ ) { if ( v1.shortValuedDiscreteFeatures[i] == v2.shortValuedDiscreteFeatures[i] ) ret++; } /* TODO: would checking float-valued features make sense ? (Code below.) */ /* float valued features */ /* if ( v1.continuousFeatures.length < v2.continuousFeatures.length ) { throw new RuntimeException( "v1 and v2 don't have the same number of continuous features: [" + v1.continuousFeatures.length + "] versus [" + v2.continuousFeatures.length + "]." ); } float epsilon = 1.0e-6f; float d = 0.0f; for ( int i = 0; i < v1.continuousFeatures.length; i++ ) { d = ( v1.continuousFeatures[i] > v2.continuousFeatures[i] ? (v1.continuousFeatures[i] - v2.continuousFeatures[i]) : (v2.continuousFeatures[i] - v1.continuousFeatures[i]) ); // => this avoids Math.abs() if ( d < epsilon ) ret++; } */ return( ret ); } }
true
true
public FeatureDefinition(BufferedReader input, boolean readWeights) throws IOException { // Section BYTEFEATURES String line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); while ( line.matches("^\\s*#.*") || line.matches("\\s*") ) { line = input.readLine(); } if (!line.trim().equals(BYTEFEATURES)) { throw new IOException("Unexpected input: expected '"+BYTEFEATURES+"', read '"+line+"'"); } List<String> byteFeatureLines = new ArrayList<String>(); while (true) { line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); line = line.trim(); if (line.equals(SHORTFEATURES)) break; // Found end of section byteFeatureLines.add(line); } // Section SHORTFEATURES List<String> shortFeatureLines = new ArrayList<String>(); while (true) { line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); line = line.trim(); if (line.equals(CONTINUOUSFEATURES)) break; // Found end of section shortFeatureLines.add(line); } // Section CONTINUOUSFEATURES List<String> continuousFeatureLines = new ArrayList<String>(); boolean readFeatureSimilarity = false; while ((line = input.readLine()) != null) { // it's OK if we hit the end of the file now line = line.trim(); //if (line.equals(FEATURESIMILARITY) || line.equals("")) break; // Found end of section if ( line.equals(FEATURESIMILARITY) ) { //readFeatureSimilarityMatrices(input); readFeatureSimilarity = true; break; } else if (line.equals("")) { // empty line: end of section break; } continuousFeatureLines.add(line); } numByteFeatures = byteFeatureLines.size(); numShortFeatures = shortFeatureLines.size(); numContinuousFeatures = continuousFeatureLines.size(); int total = numByteFeatures+numShortFeatures+numContinuousFeatures; featureNames = new IntStringTranslator(total); byteFeatureValues = new ByteStringTranslator[numByteFeatures]; shortFeatureValues = new ShortStringTranslator[numShortFeatures]; float sumOfWeights = 0; // for normalisation of weights if (readWeights) { featureWeights = new float[total]; floatWeightFuncts = new String[numContinuousFeatures]; } for (int i=0; i<numByteFeatures; i++) { line = byteFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is simply the float number: featureWeights[i] = Float.parseFloat(weightDef); sumOfWeights += featureWeights[i]; if (featureWeights[i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); } else { featureDef = line; } // Now featureDef is a String in which the feature name and all feature values // are separated by white space. String[] nameAndValues = featureDef.split("\\s+", 2); featureNames.set(i, nameAndValues[0]); // the feature name byteFeatureValues[i] = new ByteStringTranslator(nameAndValues[1].split("\\s+")); // the feature values } for (int i=0; i<numShortFeatures; i++) { line = shortFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is simply the float number: featureWeights[numByteFeatures+i] = Float.parseFloat(weightDef); sumOfWeights += featureWeights[numByteFeatures+i]; if (featureWeights[numByteFeatures+i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); } else { featureDef = line; } // Now featureDef is a String in which the feature name and all feature values // are separated by white space. String[] nameAndValues = featureDef.split("\\s+", 2); featureNames.set(numByteFeatures+i, nameAndValues[0]); // the feature name shortFeatureValues[i] = new ShortStringTranslator(nameAndValues[1].split("\\s+")); // the feature values } for (int i=0; i<numContinuousFeatures; i++) { line = continuousFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is the float number plus a definition of a weight function: String[] weightAndFunction = weightDef.split("\\s+", 2); featureWeights[numByteFeatures+numShortFeatures+i] = Float.parseFloat(weightAndFunction[0]); sumOfWeights += featureWeights[numByteFeatures+numShortFeatures+i]; if (featureWeights[numByteFeatures+numShortFeatures+i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); try { floatWeightFuncts[i] = weightAndFunction[1]; } catch ( ArrayIndexOutOfBoundsException e ) { // System.out.println( "weightDef string was: '" + weightDef + "'." ); // System.out.println( "Splitting part 1: '" + weightAndFunction[0] + "'." ); // System.out.println( "Splitting part 2: '" + weightAndFunction[1] + "'." ); throw new RuntimeException( "The string [" + weightDef + "] appears to be a badly formed" + " weight plus weighting function definition." ); } } else { featureDef = line; } // Now featureDef is the feature name // or the feature name followed by the word "float" if (featureDef.endsWith("float")){ String[] featureDefSplit = featureDef.split("\\s+", 2); featureNames.set(numByteFeatures+numShortFeatures+i, featureDefSplit[0]); } else { featureNames.set(numByteFeatures+numShortFeatures+i, featureDef); } } // Normalize weights to sum to one: if (readWeights) { for (int i=0; i<total; i++) { featureWeights[i] /= sumOfWeights; } } // read feature similarities here, if any if ( readFeatureSimilarity ) { readFeatureSimilarityMatrices(input); } input.close(); }
public FeatureDefinition(BufferedReader input, boolean readWeights) throws IOException { // Section BYTEFEATURES String line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); while ( line.matches("^\\s*#.*") || line.matches("\\s*") ) { line = input.readLine(); } if (!line.trim().equals(BYTEFEATURES)) { throw new IOException("Unexpected input: expected '"+BYTEFEATURES+"', read '"+line+"'"); } List<String> byteFeatureLines = new ArrayList<String>(); while (true) { line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); line = line.trim(); if (line.equals(SHORTFEATURES)) break; // Found end of section byteFeatureLines.add(line); } // Section SHORTFEATURES List<String> shortFeatureLines = new ArrayList<String>(); while (true) { line = input.readLine(); if (line == null) throw new IOException("Could not read from input"); line = line.trim(); if (line.equals(CONTINUOUSFEATURES)) break; // Found end of section shortFeatureLines.add(line); } // Section CONTINUOUSFEATURES List<String> continuousFeatureLines = new ArrayList<String>(); boolean readFeatureSimilarity = false; while ((line = input.readLine()) != null) { // it's OK if we hit the end of the file now line = line.trim(); //if (line.equals(FEATURESIMILARITY) || line.equals("")) break; // Found end of section if ( line.equals(FEATURESIMILARITY) ) { //readFeatureSimilarityMatrices(input); readFeatureSimilarity = true; break; } else if (line.equals("")) { // empty line: end of section break; } continuousFeatureLines.add(line); } numByteFeatures = byteFeatureLines.size(); numShortFeatures = shortFeatureLines.size(); numContinuousFeatures = continuousFeatureLines.size(); int total = numByteFeatures+numShortFeatures+numContinuousFeatures; featureNames = new IntStringTranslator(total); byteFeatureValues = new ByteStringTranslator[numByteFeatures]; shortFeatureValues = new ShortStringTranslator[numShortFeatures]; float sumOfWeights = 0; // for normalisation of weights if (readWeights) { featureWeights = new float[total]; floatWeightFuncts = new String[numContinuousFeatures]; } for (int i=0; i<numByteFeatures; i++) { line = byteFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is simply the float number: featureWeights[i] = Float.parseFloat(weightDef); sumOfWeights += featureWeights[i]; if (featureWeights[i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); } else { featureDef = line; } // Now featureDef is a String in which the feature name and all feature values // are separated by white space. String[] nameAndValues = featureDef.split("\\s+", 2); featureNames.set(i, nameAndValues[0]); // the feature name byteFeatureValues[i] = new ByteStringTranslator(nameAndValues[1].split("\\s+")); // the feature values } for (int i=0; i<numShortFeatures; i++) { line = shortFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is simply the float number: featureWeights[numByteFeatures+i] = Float.parseFloat(weightDef); sumOfWeights += featureWeights[numByteFeatures+i]; if (featureWeights[numByteFeatures+i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); } else { featureDef = line; } // Now featureDef is a String in which the feature name and all feature values // are separated by white space. String[] nameAndValues = featureDef.split("\\s+", 2); featureNames.set(numByteFeatures+i, nameAndValues[0]); // the feature name shortFeatureValues[i] = new ShortStringTranslator(nameAndValues[1].split("\\s+")); // the feature values } for (int i=0; i<numContinuousFeatures; i++) { line = continuousFeatureLines.get(i); String featureDef; if (readWeights) { int seppos = line.indexOf(WEIGHT_SEPARATOR); if (seppos == -1) throw new IOException("Weight separator '"+WEIGHT_SEPARATOR+"' not found in line '"+line+"'"); String weightDef = line.substring(0, seppos).trim(); featureDef = line.substring(seppos+1).trim(); // The weight definition is the float number plus a definition of a weight function: String[] weightAndFunction = weightDef.split("\\s+", 2); featureWeights[numByteFeatures+numShortFeatures+i] = Float.parseFloat(weightAndFunction[0]); sumOfWeights += featureWeights[numByteFeatures+numShortFeatures+i]; if (featureWeights[numByteFeatures+numShortFeatures+i] < 0) throw new IOException("Negative weight found in line '"+line+"'"); try { floatWeightFuncts[i] = weightAndFunction[1]; } catch ( ArrayIndexOutOfBoundsException e ) { // System.out.println( "weightDef string was: '" + weightDef + "'." ); // System.out.println( "Splitting part 1: '" + weightAndFunction[0] + "'." ); // System.out.println( "Splitting part 2: '" + weightAndFunction[1] + "'." ); throw new RuntimeException( "The string [" + weightDef + "] appears to be a badly formed" + " weight plus weighting function definition." ); } } else { featureDef = line; } // Now featureDef is the feature name // or the feature name followed by the word "float" if (featureDef.endsWith("float")){ String[] featureDefSplit = featureDef.split("\\s+", 2); featureNames.set(numByteFeatures+numShortFeatures+i, featureDefSplit[0]); } else { featureNames.set(numByteFeatures+numShortFeatures+i, featureDef); } } // Normalize weights to sum to one: if (readWeights) { for (int i=0; i<total; i++) { featureWeights[i] /= sumOfWeights; } } // read feature similarities here, if any if ( readFeatureSimilarity ) { readFeatureSimilarityMatrices(input); } }
diff --git a/src/org/python/parser/TreeBuilder.java b/src/org/python/parser/TreeBuilder.java index b64eb3ae..831d7ae3 100644 --- a/src/org/python/parser/TreeBuilder.java +++ b/src/org/python/parser/TreeBuilder.java @@ -1,694 +1,698 @@ package org.python.parser; import org.python.parser.ast.*; import org.python.core.PyObject; public class TreeBuilder implements PythonGrammarTreeConstants { private JJTPythonGrammarState stack; CtxVisitor ctx; public TreeBuilder(JJTPythonGrammarState stack) { this.stack = stack; ctx = new CtxVisitor(); } private stmtType[] makeStmts(int l) { stmtType[] stmts = new stmtType[l]; for (int i = l-1; i >= 0; i--) { stmts[i] = (stmtType) stack.popNode(); } return stmts; } private stmtType[] popSuite() { return ((Suite) popNode()).body; } private exprType[] makeExprs() { if (stack.nodeArity() > 0 && peekNode().getId() == JJTCOMMA) popNode(); return makeExprs(stack.nodeArity()); } private exprType[] makeExprs(int l) { exprType[] exprs = new exprType[l]; for (int i = l-1; i >= 0; i--) { exprs[i] = makeExpr(); } return exprs; } private exprType makeExpr(SimpleNode node) { return (exprType) node; } private exprType makeExpr() { return makeExpr((SimpleNode) stack.popNode()); } private String makeIdentifier() { return ((Name) stack.popNode()).id; } private String[] makeIdentifiers() { int l = stack.nodeArity(); String[] ids = new String[l]; for (int i = l - 1; i >= 0; i--) { ids[i] = makeIdentifier(); } return ids; } private aliasType[] makeAliases() { return makeAliases(stack.nodeArity()); } private aliasType[] makeAliases(int l) { aliasType[] aliases = new aliasType[l]; for (int i = l-1; i >= 0; i--) { aliases[i] = (aliasType) stack.popNode(); } return aliases; } private static SimpleNode[] nodes = new SimpleNode[PythonGrammarTreeConstants.jjtNodeName.length]; public SimpleNode openNode(int id) { if (nodes[id] == null) nodes[id] = new IdentityNode(id); return nodes[id]; } public SimpleNode closeNode(SimpleNode n, int arity) throws Exception { exprType value; exprType[] exprs; switch (n.getId()) { case -1: System.out.println("Illegal node"); case JJTSINGLE_INPUT: return new Interactive(makeStmts(arity)); case JJTFILE_INPUT: return new Module(makeStmts(arity)); case JJTEVAL_INPUT: return new Expression(makeExpr()); case JJTNAME: return new Name(n.getImage().toString(), Name.Load); case JJTNUM: return new Num((PyObject) n.getImage()); case JJTSTRING: return new Str(n.getImage().toString()); case JJTUNICODE: return new Unicode(n.getImage().toString()); case JJTSUITE: stmtType[] stmts = new stmtType[arity]; for (int i = arity-1; i >= 0; i--) { stmts[i] = (stmtType) popNode(); } return new Suite(stmts); case JJTEXPR_STMT: value = makeExpr(); if (arity > 1) { exprs = makeExprs(arity-1); ctx.setStore(exprs); return new Assign(exprs, value); } else { return new Expr(value); } case JJTINDEX_OP: sliceType slice = (sliceType) stack.popNode(); value = makeExpr(); return new Subscript(value, slice, Subscript.Load); case JJTDOT_OP: String attr = makeIdentifier(); value = makeExpr(); return new Attribute(value, attr, Attribute.Load); case JJTDEL_STMT: exprs = makeExprs(arity); ctx.setDelete(exprs); return new Delete(exprs); case JJTPRINT_STMT: boolean nl = true; if (stack.nodeArity() == 0) return new Print(null, null, true); if (peekNode().getId() == JJTCOMMA) { popNode(); nl = false; } return new Print(null, makeExprs(), nl); case JJTPRINTEXT_STMT: nl = true; if (peekNode().getId() == JJTCOMMA) { popNode(); nl = false; } exprs = makeExprs(stack.nodeArity()-1); return new Print(makeExpr(), exprs, nl); case JJTFOR_STMT: stmtType[] orelse = null; if (stack.nodeArity() == 4) orelse = popSuite(); stmtType[] body = popSuite(); exprType iter = makeExpr(); exprType target = makeExpr(); ctx.setStore(target); return new For(target, iter, body, orelse); case JJTWHILE_STMT: orelse = null; if (stack.nodeArity() == 3) orelse = popSuite(); body = popSuite(); exprType test = makeExpr(); return new While(test, body, orelse); case JJTIF_STMT: orelse = null; if (arity % 2 == 1) orelse = popSuite(); body = popSuite(); test = makeExpr(); If last = new If(test, body, orelse); for (int i = 0; i < (arity / 2)-1; i++) { body = popSuite(); test = makeExpr(); last = new If(test, body, new stmtType[] { last }); } return last; case JJTPASS_STMT: return new Pass(); case JJTBREAK_STMT: return new Break(); case JJTCONTINUE_STMT: return new Continue(); case JJTFUNCDEF: body = popSuite(); argumentsType arguments = makeArguments(arity - 2); String name = makeIdentifier(); return new FunctionDef(name, arguments, body); case JJTDEFAULTARG: value = (arity == 1) ? null : makeExpr(); return new DefaultArg(makeExpr(), value); case JJTEXTRAARGLIST: return new ExtraArg(makeIdentifier(), JJTEXTRAARGLIST); case JJTEXTRAKEYWORDLIST: return new ExtraArg(makeIdentifier(), JJTEXTRAKEYWORDLIST); /* case JJTFPLIST: fpdefType[] list = new fpdefType[arity]; for (int i = arity-1; i >= 0; i--) { list[i] = popFpdef(); } return new FpList(list); */ case JJTCLASSDEF: body = popSuite(); exprType[] bases = makeExprs(stack.nodeArity() - 1); name = makeIdentifier(); return new ClassDef(name, bases, body); case JJTRETURN_STMT: value = arity == 1 ? makeExpr() : null; return new Return(value); case JJTYIELD_STMT: return new Yield(makeExpr()); case JJTRAISE_STMT: exprType tback = arity >= 3 ? makeExpr() : null; exprType inst = arity >= 2 ? makeExpr() : null; exprType type = arity >= 1 ? makeExpr() : null; return new Raise(type, inst, tback); case JJTGLOBAL_STMT: return new Global(makeIdentifiers()); case JJTEXEC_STMT: exprType globals = arity >= 3 ? makeExpr() : null; exprType locals = arity >= 2 ? makeExpr() : null; value = makeExpr(); return new Exec(value, locals, globals); case JJTASSERT_STMT: exprType msg = arity == 2 ? makeExpr() : null; test = makeExpr(); return new Assert(test, msg); case JJTTRYFINALLY_STMT: orelse = popSuite(); return new TryFinally(popSuite(), orelse); case JJTTRY_STMT: orelse = null; if (peekNode() instanceof Suite) { arity--; orelse = popSuite(); } int l = arity - 1; excepthandlerType[] handlers = new excepthandlerType[l]; for (int i = l - 1; i >= 0; i--) { handlers[i] = (excepthandlerType) popNode(); } return new TryExcept(popSuite(), handlers, orelse); case JJTEXCEPT_CLAUSE: body = popSuite(); exprType excname = arity == 3 ? makeExpr() : null; if (excname != null) ctx.setStore(excname); type = arity >= 2 ? makeExpr() : null; return new excepthandlerType(type, excname, body); case JJTOR_BOOLEAN: return new BoolOp(BoolOp.Or, makeExprs()); case JJTAND_BOOLEAN: return new BoolOp(BoolOp.And, makeExprs()); case JJTCOMPARISION: l = arity / 2; exprType[] comparators = new exprType[l]; int[] ops = new int[l]; for (int i = l-1; i >= 0; i--) { comparators[i] = makeExpr(); SimpleNode op = (SimpleNode) stack.popNode(); switch (op.getId()) { case JJTLESS_CMP: ops[i] = Compare.Lt; break; case JJTGREATER_CMP: ops[i] = Compare.Gt; break; case JJTEQUAL_CMP: ops[i] = Compare.Eq; break; case JJTGREATER_EQUAL_CMP: ops[i] = Compare.GtE; break; case JJTLESS_EQUAL_CMP: ops[i] = Compare.LtE; break; case JJTNOTEQUAL_CMP: ops[i] = Compare.NotEq; break; case JJTIN_CMP: ops[i] = Compare.In; break; case JJTNOT_IN_CMP: ops[i] = Compare.NotIn; break; case JJTIS_NOT_CMP: ops[i] = Compare.IsNot; break; case JJTIS_CMP: ops[i] = Compare.Is; break; default: throw new RuntimeException("Unknown cmp op:" + op.getId()); } } return new Compare(makeExpr(), ops, comparators); case JJTLESS_CMP: case JJTGREATER_CMP: case JJTEQUAL_CMP: case JJTGREATER_EQUAL_CMP: case JJTLESS_EQUAL_CMP: case JJTNOTEQUAL_CMP: case JJTIN_CMP: case JJTNOT_IN_CMP: case JJTIS_NOT_CMP: case JJTIS_CMP: return n; case JJTOR_2OP: return makeBinOp(BinOp.BitOr); case JJTXOR_2OP: return makeBinOp(BinOp.BitXor); case JJTAND_2OP: return makeBinOp(BinOp.BitAnd); case JJTLSHIFT_2OP: return makeBinOp(BinOp.LShift); case JJTRSHIFT_2OP: return makeBinOp(BinOp.RShift); case JJTADD_2OP: return makeBinOp(BinOp.Add); case JJTSUB_2OP: return makeBinOp(BinOp.Sub); case JJTMUL_2OP: return makeBinOp(BinOp.Mult); case JJTDIV_2OP: return makeBinOp(BinOp.Div); case JJTMOD_2OP: return makeBinOp(BinOp.Mod); case JJTPOW_2OP: return makeBinOp(BinOp.Pow); case JJTFLOORDIV_2OP: return makeBinOp(BinOp.FloorDiv); case JJTPOS_1OP: return new UnaryOp(UnaryOp.UAdd, makeExpr()); case JJTNEG_1OP: return new UnaryOp(UnaryOp.USub, makeExpr()); case JJTINVERT_1OP: return new UnaryOp(UnaryOp.Invert, makeExpr()); case JJTNOT_1OP: return new UnaryOp(UnaryOp.Not, makeExpr()); case JJTCALL_OP: //if (arity == 1) // return new Call(makeExpr(), null, null, null, null); exprType starargs = null; exprType kwargs = null; l = arity - 1; if (l > 0 && peekNode().getId() == JJTEXTRAKEYWORDVALUELIST) { kwargs = ((ExtraArgValue) popNode()).value; l--; } if (l > 0 && peekNode().getId() == JJTEXTRAARGVALUELIST) { starargs = ((ExtraArgValue) popNode()).value; l--; } int nargs = l; SimpleNode[] tmparr = new SimpleNode[l]; for (int i = l - 1; i >= 0; i--) { tmparr[i] = popNode(); if (tmparr[i] instanceof keywordType) { nargs = i; } } exprType[] args = new exprType[nargs]; for (int i = 0; i < nargs; i++) { args[i] = makeExpr(tmparr[i]); } keywordType[] keywords = new keywordType[l - nargs]; for (int i = nargs; i < l; i++) { if (!(tmparr[i] instanceof keywordType)) throw new ParseException( "non-keyword argument following keyword", tmparr[i]); keywords[i - nargs] = (keywordType) tmparr[i]; } exprType func = makeExpr(); return new Call(func, args, keywords, starargs, kwargs); case JJTEXTRAKEYWORDVALUELIST: return new ExtraArgValue(makeExpr(), JJTEXTRAKEYWORDVALUELIST); case JJTEXTRAARGVALUELIST: return new ExtraArgValue(makeExpr(), JJTEXTRAARGVALUELIST); case JJTKEYWORD: value = makeExpr(); name = makeIdentifier(); return new keywordType(name, value); case JJTTUPLE: return new Tuple(makeExprs(), Tuple.Load); case JJTLIST: if (stack.nodeArity() > 0 && peekNode() instanceof listcompType) { listcompType[] generators = new listcompType[arity-1]; for (int i = arity-2; i >= 0; i--) { generators[i] = (listcompType) popNode(); } return new ListComp(makeExpr(), generators); } return new List(makeExprs(), List.Load); case JJTDICTIONARY: l = arity / 2; exprType[] keys = new exprType[l]; exprType[] vals = new exprType[l]; for (int i = l - 1; i >= 0; i--) { vals[i] = makeExpr(); keys[i] = makeExpr(); } return new Dict(keys, vals); case JJTSTR_1OP: return new Repr(makeExpr()); case JJTSTRJOIN: String str2 = ((Str) popNode()).s; String str1 = ((Str) popNode()).s; return new Str(str1 + str2); case JJTLAMBDEF: test = makeExpr(); arguments = makeArguments(arity - 1); return new Lambda(arguments, test); case JJTELLIPSES: return new Ellipsis(); case JJTSLICE: SimpleNode[] arr = new SimpleNode[arity]; for (int i = arity-1; i >= 0; i--) { arr[i] = popNode(); } exprType[] values = new exprType[3]; int k = 0; for (int j = 0; j < arity; j++) { if (arr[j].getId() == JJTCOLON) k++; else values[k] = makeExpr(arr[j]); } if (k == 0) { return new Index(values[0]); } else { return new Slice(values[0], values[1], values[2]); } case JJTSUBSCRIPTLIST: + if (arity > 0 && peekNode().getId() == JJTCOMMA){ + arity--; + popNode(); + } sliceType[] dims = new sliceType[arity]; for (int i = arity - 1; i >= 0; i--) { dims[i] = (sliceType) popNode(); } return new ExtSlice(dims); case JJTAUG_PLUS: return makeAugAssign(AugAssign.Add); case JJTAUG_MINUS: return makeAugAssign(AugAssign.Sub); case JJTAUG_MULTIPLY: return makeAugAssign(AugAssign.Mult); case JJTAUG_DIVIDE: return makeAugAssign(AugAssign.Div); case JJTAUG_MODULO: return makeAugAssign(AugAssign.Mod); case JJTAUG_AND: return makeAugAssign(AugAssign.BitAnd); case JJTAUG_OR: return makeAugAssign(AugAssign.BitOr); case JJTAUG_XOR: return makeAugAssign(AugAssign.BitXor); case JJTAUG_LSHIFT: return makeAugAssign(AugAssign.LShift); case JJTAUG_RSHIFT: return makeAugAssign(AugAssign.RShift); case JJTAUG_POWER: return makeAugAssign(AugAssign.Pow); case JJTAUG_FLOORDIVIDE: return makeAugAssign(AugAssign.FloorDiv); case JJTLIST_FOR: exprType[] ifs = new exprType[arity-2]; for (int i = arity-3; i >= 0; i--) { ifs[i] = makeExpr(); } iter = makeExpr(); target = makeExpr(); ctx.setStore(target); return new listcompType(target, iter, ifs); case JJTIMPORTFROM: aliasType[] aliases = makeAliases(arity - 1); String module = makeIdentifier(); return new ImportFrom(module, aliases); case JJTIMPORT: return new Import(makeAliases()); case JJTDOTTED_NAME: StringBuffer sb = new StringBuffer(); for (int i = 0; i < arity; i++) { if (i > 0) sb.insert(0, '.'); sb.insert(0, makeIdentifier()); } return new Name(sb.toString(), Name.Load); case JJTDOTTED_AS_NAME: String asname = null; if (arity > 1) asname = makeIdentifier(); return new aliasType(makeIdentifier(), asname); case JJTIMPORT_AS_NAME: asname = null; if (arity > 1) asname = makeIdentifier(); return new aliasType(makeIdentifier(), asname); case JJTCOMMA: case JJTCOLON: return n; default: return null; } } private stmtType makeAugAssign(int op) throws Exception { exprType value = makeExpr(); exprType target = makeExpr(); ctx.setAugStore(target); return new AugAssign(target, op, value); } private void dumpStack() { int n = stack.nodeArity(); System.out.println("nodeArity:" + n); if (n > 0) { System.out.println("peek:" + stack.peekNode()); } } SimpleNode peekNode() { return (SimpleNode) stack.peekNode(); } SimpleNode popNode() { return (SimpleNode) stack.popNode(); } BinOp makeBinOp(int op) { exprType right = makeExpr(); exprType left = makeExpr(); return new BinOp(left, op, right); } argumentsType makeArguments(int l) throws Exception { String kwarg = null; String stararg = null; if (l > 0 && peekNode().getId() == JJTEXTRAKEYWORDLIST) { kwarg = ((ExtraArg) popNode()).name; l--; } if (l > 0 && peekNode().getId() == JJTEXTRAARGLIST) { stararg = ((ExtraArg) popNode()).name; l--; } int startofdefaults = l; exprType fpargs[] = new exprType[l]; exprType defaults[] = new exprType[l]; for (int i = l-1; i >= 0; i--) { DefaultArg node = (DefaultArg) popNode(); fpargs[i] = node.parameter; ctx.setStore(fpargs[i]); defaults[i] = node.value; if (node.value != null) startofdefaults = i; } //System.out.println("start "+ startofdefaults + " " + l); exprType[] newdefs = new exprType[l-startofdefaults]; System.arraycopy(defaults, startofdefaults, newdefs, 0, newdefs.length); return new argumentsType(fpargs, stararg, kwarg, newdefs); } } class DefaultArg extends SimpleNode { public exprType parameter; public exprType value; DefaultArg(exprType parameter, exprType value) { this.parameter = parameter; this.value = value; } } class ExtraArg extends SimpleNode { public String name; public int id; ExtraArg(String name, int id) { this.name = name; this.id = id; } public int getId() { return id; } } class ExtraArgValue extends SimpleNode { public exprType value; public int id; ExtraArgValue(exprType value, int id) { this.value = value; this.id = id; } public int getId() { return id; } } class IdentityNode extends SimpleNode { public int id; public Object image; IdentityNode(int id) { this.id = id; } public int getId() { return id; } public void setImage(Object image) { this.image = image; } public Object getImage() { return image; } public String toString() { return "IdNode[" + PythonGrammarTreeConstants.jjtNodeName[id] + ", " + image + "]"; } } class CtxVisitor extends Visitor { private int ctx; public CtxVisitor() { } public void setStore(SimpleNode node) throws Exception { this.ctx = expr_contextType.Store; visit(node); } public void setStore(SimpleNode[] nodes) throws Exception { for (int i = 0; i < nodes.length; i++) setStore(nodes[i]); } public void setDelete(SimpleNode node) throws Exception { this.ctx = expr_contextType.Del; visit(node); } public void setDelete(SimpleNode[] nodes) throws Exception { for (int i = 0; i < nodes.length; i++) setDelete(nodes[i]); } public void setAugStore(SimpleNode node) throws Exception { this.ctx = expr_contextType.AugStore; visit(node); } public Object visitName(Name node) throws Exception { node.ctx = ctx; return null; } public Object visitAttribute(Attribute node) throws Exception { node.ctx = ctx; return null; } public Object visitSubscript(Subscript node) throws Exception { node.ctx = ctx; return null; } public Object visitList(List node) throws Exception { if (ctx == expr_contextType.AugStore) { throw new ParseException( "augmented assign to list not possible", node); } node.ctx = ctx; traverse(node); return null; } public Object visitTuple(Tuple node) throws Exception { if (ctx == expr_contextType.AugStore) { throw new ParseException( "augmented assign to tuple not possible", node); } node.ctx = ctx; traverse(node); return null; } public Object visitCall(Call node) throws Exception { throw new ParseException("can't assign to function call", node); } public Object visitListComp(Call node) throws Exception { throw new ParseException("can't assign to list comprehension call", node); } public Object unhandled_node(SimpleNode node) throws Exception { throw new ParseException("can't assign to operator", node); } }
true
true
public SimpleNode closeNode(SimpleNode n, int arity) throws Exception { exprType value; exprType[] exprs; switch (n.getId()) { case -1: System.out.println("Illegal node"); case JJTSINGLE_INPUT: return new Interactive(makeStmts(arity)); case JJTFILE_INPUT: return new Module(makeStmts(arity)); case JJTEVAL_INPUT: return new Expression(makeExpr()); case JJTNAME: return new Name(n.getImage().toString(), Name.Load); case JJTNUM: return new Num((PyObject) n.getImage()); case JJTSTRING: return new Str(n.getImage().toString()); case JJTUNICODE: return new Unicode(n.getImage().toString()); case JJTSUITE: stmtType[] stmts = new stmtType[arity]; for (int i = arity-1; i >= 0; i--) { stmts[i] = (stmtType) popNode(); } return new Suite(stmts); case JJTEXPR_STMT: value = makeExpr(); if (arity > 1) { exprs = makeExprs(arity-1); ctx.setStore(exprs); return new Assign(exprs, value); } else { return new Expr(value); } case JJTINDEX_OP: sliceType slice = (sliceType) stack.popNode(); value = makeExpr(); return new Subscript(value, slice, Subscript.Load); case JJTDOT_OP: String attr = makeIdentifier(); value = makeExpr(); return new Attribute(value, attr, Attribute.Load); case JJTDEL_STMT: exprs = makeExprs(arity); ctx.setDelete(exprs); return new Delete(exprs); case JJTPRINT_STMT: boolean nl = true; if (stack.nodeArity() == 0) return new Print(null, null, true); if (peekNode().getId() == JJTCOMMA) { popNode(); nl = false; } return new Print(null, makeExprs(), nl); case JJTPRINTEXT_STMT: nl = true; if (peekNode().getId() == JJTCOMMA) { popNode(); nl = false; } exprs = makeExprs(stack.nodeArity()-1); return new Print(makeExpr(), exprs, nl); case JJTFOR_STMT: stmtType[] orelse = null; if (stack.nodeArity() == 4) orelse = popSuite(); stmtType[] body = popSuite(); exprType iter = makeExpr(); exprType target = makeExpr(); ctx.setStore(target); return new For(target, iter, body, orelse); case JJTWHILE_STMT: orelse = null; if (stack.nodeArity() == 3) orelse = popSuite(); body = popSuite(); exprType test = makeExpr(); return new While(test, body, orelse); case JJTIF_STMT: orelse = null; if (arity % 2 == 1) orelse = popSuite(); body = popSuite(); test = makeExpr(); If last = new If(test, body, orelse); for (int i = 0; i < (arity / 2)-1; i++) { body = popSuite(); test = makeExpr(); last = new If(test, body, new stmtType[] { last }); } return last; case JJTPASS_STMT: return new Pass(); case JJTBREAK_STMT: return new Break(); case JJTCONTINUE_STMT: return new Continue(); case JJTFUNCDEF: body = popSuite(); argumentsType arguments = makeArguments(arity - 2); String name = makeIdentifier(); return new FunctionDef(name, arguments, body); case JJTDEFAULTARG: value = (arity == 1) ? null : makeExpr(); return new DefaultArg(makeExpr(), value); case JJTEXTRAARGLIST: return new ExtraArg(makeIdentifier(), JJTEXTRAARGLIST); case JJTEXTRAKEYWORDLIST: return new ExtraArg(makeIdentifier(), JJTEXTRAKEYWORDLIST); /* case JJTFPLIST: fpdefType[] list = new fpdefType[arity]; for (int i = arity-1; i >= 0; i--) { list[i] = popFpdef(); } return new FpList(list); */ case JJTCLASSDEF: body = popSuite(); exprType[] bases = makeExprs(stack.nodeArity() - 1); name = makeIdentifier(); return new ClassDef(name, bases, body); case JJTRETURN_STMT: value = arity == 1 ? makeExpr() : null; return new Return(value); case JJTYIELD_STMT: return new Yield(makeExpr()); case JJTRAISE_STMT: exprType tback = arity >= 3 ? makeExpr() : null; exprType inst = arity >= 2 ? makeExpr() : null; exprType type = arity >= 1 ? makeExpr() : null; return new Raise(type, inst, tback); case JJTGLOBAL_STMT: return new Global(makeIdentifiers()); case JJTEXEC_STMT: exprType globals = arity >= 3 ? makeExpr() : null; exprType locals = arity >= 2 ? makeExpr() : null; value = makeExpr(); return new Exec(value, locals, globals); case JJTASSERT_STMT: exprType msg = arity == 2 ? makeExpr() : null; test = makeExpr(); return new Assert(test, msg); case JJTTRYFINALLY_STMT: orelse = popSuite(); return new TryFinally(popSuite(), orelse); case JJTTRY_STMT: orelse = null; if (peekNode() instanceof Suite) { arity--; orelse = popSuite(); } int l = arity - 1; excepthandlerType[] handlers = new excepthandlerType[l]; for (int i = l - 1; i >= 0; i--) { handlers[i] = (excepthandlerType) popNode(); } return new TryExcept(popSuite(), handlers, orelse); case JJTEXCEPT_CLAUSE: body = popSuite(); exprType excname = arity == 3 ? makeExpr() : null; if (excname != null) ctx.setStore(excname); type = arity >= 2 ? makeExpr() : null; return new excepthandlerType(type, excname, body); case JJTOR_BOOLEAN: return new BoolOp(BoolOp.Or, makeExprs()); case JJTAND_BOOLEAN: return new BoolOp(BoolOp.And, makeExprs()); case JJTCOMPARISION: l = arity / 2; exprType[] comparators = new exprType[l]; int[] ops = new int[l]; for (int i = l-1; i >= 0; i--) { comparators[i] = makeExpr(); SimpleNode op = (SimpleNode) stack.popNode(); switch (op.getId()) { case JJTLESS_CMP: ops[i] = Compare.Lt; break; case JJTGREATER_CMP: ops[i] = Compare.Gt; break; case JJTEQUAL_CMP: ops[i] = Compare.Eq; break; case JJTGREATER_EQUAL_CMP: ops[i] = Compare.GtE; break; case JJTLESS_EQUAL_CMP: ops[i] = Compare.LtE; break; case JJTNOTEQUAL_CMP: ops[i] = Compare.NotEq; break; case JJTIN_CMP: ops[i] = Compare.In; break; case JJTNOT_IN_CMP: ops[i] = Compare.NotIn; break; case JJTIS_NOT_CMP: ops[i] = Compare.IsNot; break; case JJTIS_CMP: ops[i] = Compare.Is; break; default: throw new RuntimeException("Unknown cmp op:" + op.getId()); } } return new Compare(makeExpr(), ops, comparators); case JJTLESS_CMP: case JJTGREATER_CMP: case JJTEQUAL_CMP: case JJTGREATER_EQUAL_CMP: case JJTLESS_EQUAL_CMP: case JJTNOTEQUAL_CMP: case JJTIN_CMP: case JJTNOT_IN_CMP: case JJTIS_NOT_CMP: case JJTIS_CMP: return n; case JJTOR_2OP: return makeBinOp(BinOp.BitOr); case JJTXOR_2OP: return makeBinOp(BinOp.BitXor); case JJTAND_2OP: return makeBinOp(BinOp.BitAnd); case JJTLSHIFT_2OP: return makeBinOp(BinOp.LShift); case JJTRSHIFT_2OP: return makeBinOp(BinOp.RShift); case JJTADD_2OP: return makeBinOp(BinOp.Add); case JJTSUB_2OP: return makeBinOp(BinOp.Sub); case JJTMUL_2OP: return makeBinOp(BinOp.Mult); case JJTDIV_2OP: return makeBinOp(BinOp.Div); case JJTMOD_2OP: return makeBinOp(BinOp.Mod); case JJTPOW_2OP: return makeBinOp(BinOp.Pow); case JJTFLOORDIV_2OP: return makeBinOp(BinOp.FloorDiv); case JJTPOS_1OP: return new UnaryOp(UnaryOp.UAdd, makeExpr()); case JJTNEG_1OP: return new UnaryOp(UnaryOp.USub, makeExpr()); case JJTINVERT_1OP: return new UnaryOp(UnaryOp.Invert, makeExpr()); case JJTNOT_1OP: return new UnaryOp(UnaryOp.Not, makeExpr()); case JJTCALL_OP: //if (arity == 1) // return new Call(makeExpr(), null, null, null, null); exprType starargs = null; exprType kwargs = null; l = arity - 1; if (l > 0 && peekNode().getId() == JJTEXTRAKEYWORDVALUELIST) { kwargs = ((ExtraArgValue) popNode()).value; l--; } if (l > 0 && peekNode().getId() == JJTEXTRAARGVALUELIST) { starargs = ((ExtraArgValue) popNode()).value; l--; } int nargs = l; SimpleNode[] tmparr = new SimpleNode[l]; for (int i = l - 1; i >= 0; i--) { tmparr[i] = popNode(); if (tmparr[i] instanceof keywordType) { nargs = i; } } exprType[] args = new exprType[nargs]; for (int i = 0; i < nargs; i++) { args[i] = makeExpr(tmparr[i]); } keywordType[] keywords = new keywordType[l - nargs]; for (int i = nargs; i < l; i++) { if (!(tmparr[i] instanceof keywordType)) throw new ParseException( "non-keyword argument following keyword", tmparr[i]); keywords[i - nargs] = (keywordType) tmparr[i]; } exprType func = makeExpr(); return new Call(func, args, keywords, starargs, kwargs); case JJTEXTRAKEYWORDVALUELIST: return new ExtraArgValue(makeExpr(), JJTEXTRAKEYWORDVALUELIST); case JJTEXTRAARGVALUELIST: return new ExtraArgValue(makeExpr(), JJTEXTRAARGVALUELIST); case JJTKEYWORD: value = makeExpr(); name = makeIdentifier(); return new keywordType(name, value); case JJTTUPLE: return new Tuple(makeExprs(), Tuple.Load); case JJTLIST: if (stack.nodeArity() > 0 && peekNode() instanceof listcompType) { listcompType[] generators = new listcompType[arity-1]; for (int i = arity-2; i >= 0; i--) { generators[i] = (listcompType) popNode(); } return new ListComp(makeExpr(), generators); } return new List(makeExprs(), List.Load); case JJTDICTIONARY: l = arity / 2; exprType[] keys = new exprType[l]; exprType[] vals = new exprType[l]; for (int i = l - 1; i >= 0; i--) { vals[i] = makeExpr(); keys[i] = makeExpr(); } return new Dict(keys, vals); case JJTSTR_1OP: return new Repr(makeExpr()); case JJTSTRJOIN: String str2 = ((Str) popNode()).s; String str1 = ((Str) popNode()).s; return new Str(str1 + str2); case JJTLAMBDEF: test = makeExpr(); arguments = makeArguments(arity - 1); return new Lambda(arguments, test); case JJTELLIPSES: return new Ellipsis(); case JJTSLICE: SimpleNode[] arr = new SimpleNode[arity]; for (int i = arity-1; i >= 0; i--) { arr[i] = popNode(); } exprType[] values = new exprType[3]; int k = 0; for (int j = 0; j < arity; j++) { if (arr[j].getId() == JJTCOLON) k++; else values[k] = makeExpr(arr[j]); } if (k == 0) { return new Index(values[0]); } else { return new Slice(values[0], values[1], values[2]); } case JJTSUBSCRIPTLIST: sliceType[] dims = new sliceType[arity]; for (int i = arity - 1; i >= 0; i--) { dims[i] = (sliceType) popNode(); } return new ExtSlice(dims); case JJTAUG_PLUS: return makeAugAssign(AugAssign.Add); case JJTAUG_MINUS: return makeAugAssign(AugAssign.Sub); case JJTAUG_MULTIPLY: return makeAugAssign(AugAssign.Mult); case JJTAUG_DIVIDE: return makeAugAssign(AugAssign.Div); case JJTAUG_MODULO: return makeAugAssign(AugAssign.Mod); case JJTAUG_AND: return makeAugAssign(AugAssign.BitAnd); case JJTAUG_OR: return makeAugAssign(AugAssign.BitOr); case JJTAUG_XOR: return makeAugAssign(AugAssign.BitXor); case JJTAUG_LSHIFT: return makeAugAssign(AugAssign.LShift); case JJTAUG_RSHIFT: return makeAugAssign(AugAssign.RShift); case JJTAUG_POWER: return makeAugAssign(AugAssign.Pow); case JJTAUG_FLOORDIVIDE: return makeAugAssign(AugAssign.FloorDiv); case JJTLIST_FOR: exprType[] ifs = new exprType[arity-2]; for (int i = arity-3; i >= 0; i--) { ifs[i] = makeExpr(); } iter = makeExpr(); target = makeExpr(); ctx.setStore(target); return new listcompType(target, iter, ifs); case JJTIMPORTFROM: aliasType[] aliases = makeAliases(arity - 1); String module = makeIdentifier(); return new ImportFrom(module, aliases); case JJTIMPORT: return new Import(makeAliases()); case JJTDOTTED_NAME: StringBuffer sb = new StringBuffer(); for (int i = 0; i < arity; i++) { if (i > 0) sb.insert(0, '.'); sb.insert(0, makeIdentifier()); } return new Name(sb.toString(), Name.Load); case JJTDOTTED_AS_NAME: String asname = null; if (arity > 1) asname = makeIdentifier(); return new aliasType(makeIdentifier(), asname); case JJTIMPORT_AS_NAME: asname = null; if (arity > 1) asname = makeIdentifier(); return new aliasType(makeIdentifier(), asname); case JJTCOMMA: case JJTCOLON: return n; default: return null; } }
public SimpleNode closeNode(SimpleNode n, int arity) throws Exception { exprType value; exprType[] exprs; switch (n.getId()) { case -1: System.out.println("Illegal node"); case JJTSINGLE_INPUT: return new Interactive(makeStmts(arity)); case JJTFILE_INPUT: return new Module(makeStmts(arity)); case JJTEVAL_INPUT: return new Expression(makeExpr()); case JJTNAME: return new Name(n.getImage().toString(), Name.Load); case JJTNUM: return new Num((PyObject) n.getImage()); case JJTSTRING: return new Str(n.getImage().toString()); case JJTUNICODE: return new Unicode(n.getImage().toString()); case JJTSUITE: stmtType[] stmts = new stmtType[arity]; for (int i = arity-1; i >= 0; i--) { stmts[i] = (stmtType) popNode(); } return new Suite(stmts); case JJTEXPR_STMT: value = makeExpr(); if (arity > 1) { exprs = makeExprs(arity-1); ctx.setStore(exprs); return new Assign(exprs, value); } else { return new Expr(value); } case JJTINDEX_OP: sliceType slice = (sliceType) stack.popNode(); value = makeExpr(); return new Subscript(value, slice, Subscript.Load); case JJTDOT_OP: String attr = makeIdentifier(); value = makeExpr(); return new Attribute(value, attr, Attribute.Load); case JJTDEL_STMT: exprs = makeExprs(arity); ctx.setDelete(exprs); return new Delete(exprs); case JJTPRINT_STMT: boolean nl = true; if (stack.nodeArity() == 0) return new Print(null, null, true); if (peekNode().getId() == JJTCOMMA) { popNode(); nl = false; } return new Print(null, makeExprs(), nl); case JJTPRINTEXT_STMT: nl = true; if (peekNode().getId() == JJTCOMMA) { popNode(); nl = false; } exprs = makeExprs(stack.nodeArity()-1); return new Print(makeExpr(), exprs, nl); case JJTFOR_STMT: stmtType[] orelse = null; if (stack.nodeArity() == 4) orelse = popSuite(); stmtType[] body = popSuite(); exprType iter = makeExpr(); exprType target = makeExpr(); ctx.setStore(target); return new For(target, iter, body, orelse); case JJTWHILE_STMT: orelse = null; if (stack.nodeArity() == 3) orelse = popSuite(); body = popSuite(); exprType test = makeExpr(); return new While(test, body, orelse); case JJTIF_STMT: orelse = null; if (arity % 2 == 1) orelse = popSuite(); body = popSuite(); test = makeExpr(); If last = new If(test, body, orelse); for (int i = 0; i < (arity / 2)-1; i++) { body = popSuite(); test = makeExpr(); last = new If(test, body, new stmtType[] { last }); } return last; case JJTPASS_STMT: return new Pass(); case JJTBREAK_STMT: return new Break(); case JJTCONTINUE_STMT: return new Continue(); case JJTFUNCDEF: body = popSuite(); argumentsType arguments = makeArguments(arity - 2); String name = makeIdentifier(); return new FunctionDef(name, arguments, body); case JJTDEFAULTARG: value = (arity == 1) ? null : makeExpr(); return new DefaultArg(makeExpr(), value); case JJTEXTRAARGLIST: return new ExtraArg(makeIdentifier(), JJTEXTRAARGLIST); case JJTEXTRAKEYWORDLIST: return new ExtraArg(makeIdentifier(), JJTEXTRAKEYWORDLIST); /* case JJTFPLIST: fpdefType[] list = new fpdefType[arity]; for (int i = arity-1; i >= 0; i--) { list[i] = popFpdef(); } return new FpList(list); */ case JJTCLASSDEF: body = popSuite(); exprType[] bases = makeExprs(stack.nodeArity() - 1); name = makeIdentifier(); return new ClassDef(name, bases, body); case JJTRETURN_STMT: value = arity == 1 ? makeExpr() : null; return new Return(value); case JJTYIELD_STMT: return new Yield(makeExpr()); case JJTRAISE_STMT: exprType tback = arity >= 3 ? makeExpr() : null; exprType inst = arity >= 2 ? makeExpr() : null; exprType type = arity >= 1 ? makeExpr() : null; return new Raise(type, inst, tback); case JJTGLOBAL_STMT: return new Global(makeIdentifiers()); case JJTEXEC_STMT: exprType globals = arity >= 3 ? makeExpr() : null; exprType locals = arity >= 2 ? makeExpr() : null; value = makeExpr(); return new Exec(value, locals, globals); case JJTASSERT_STMT: exprType msg = arity == 2 ? makeExpr() : null; test = makeExpr(); return new Assert(test, msg); case JJTTRYFINALLY_STMT: orelse = popSuite(); return new TryFinally(popSuite(), orelse); case JJTTRY_STMT: orelse = null; if (peekNode() instanceof Suite) { arity--; orelse = popSuite(); } int l = arity - 1; excepthandlerType[] handlers = new excepthandlerType[l]; for (int i = l - 1; i >= 0; i--) { handlers[i] = (excepthandlerType) popNode(); } return new TryExcept(popSuite(), handlers, orelse); case JJTEXCEPT_CLAUSE: body = popSuite(); exprType excname = arity == 3 ? makeExpr() : null; if (excname != null) ctx.setStore(excname); type = arity >= 2 ? makeExpr() : null; return new excepthandlerType(type, excname, body); case JJTOR_BOOLEAN: return new BoolOp(BoolOp.Or, makeExprs()); case JJTAND_BOOLEAN: return new BoolOp(BoolOp.And, makeExprs()); case JJTCOMPARISION: l = arity / 2; exprType[] comparators = new exprType[l]; int[] ops = new int[l]; for (int i = l-1; i >= 0; i--) { comparators[i] = makeExpr(); SimpleNode op = (SimpleNode) stack.popNode(); switch (op.getId()) { case JJTLESS_CMP: ops[i] = Compare.Lt; break; case JJTGREATER_CMP: ops[i] = Compare.Gt; break; case JJTEQUAL_CMP: ops[i] = Compare.Eq; break; case JJTGREATER_EQUAL_CMP: ops[i] = Compare.GtE; break; case JJTLESS_EQUAL_CMP: ops[i] = Compare.LtE; break; case JJTNOTEQUAL_CMP: ops[i] = Compare.NotEq; break; case JJTIN_CMP: ops[i] = Compare.In; break; case JJTNOT_IN_CMP: ops[i] = Compare.NotIn; break; case JJTIS_NOT_CMP: ops[i] = Compare.IsNot; break; case JJTIS_CMP: ops[i] = Compare.Is; break; default: throw new RuntimeException("Unknown cmp op:" + op.getId()); } } return new Compare(makeExpr(), ops, comparators); case JJTLESS_CMP: case JJTGREATER_CMP: case JJTEQUAL_CMP: case JJTGREATER_EQUAL_CMP: case JJTLESS_EQUAL_CMP: case JJTNOTEQUAL_CMP: case JJTIN_CMP: case JJTNOT_IN_CMP: case JJTIS_NOT_CMP: case JJTIS_CMP: return n; case JJTOR_2OP: return makeBinOp(BinOp.BitOr); case JJTXOR_2OP: return makeBinOp(BinOp.BitXor); case JJTAND_2OP: return makeBinOp(BinOp.BitAnd); case JJTLSHIFT_2OP: return makeBinOp(BinOp.LShift); case JJTRSHIFT_2OP: return makeBinOp(BinOp.RShift); case JJTADD_2OP: return makeBinOp(BinOp.Add); case JJTSUB_2OP: return makeBinOp(BinOp.Sub); case JJTMUL_2OP: return makeBinOp(BinOp.Mult); case JJTDIV_2OP: return makeBinOp(BinOp.Div); case JJTMOD_2OP: return makeBinOp(BinOp.Mod); case JJTPOW_2OP: return makeBinOp(BinOp.Pow); case JJTFLOORDIV_2OP: return makeBinOp(BinOp.FloorDiv); case JJTPOS_1OP: return new UnaryOp(UnaryOp.UAdd, makeExpr()); case JJTNEG_1OP: return new UnaryOp(UnaryOp.USub, makeExpr()); case JJTINVERT_1OP: return new UnaryOp(UnaryOp.Invert, makeExpr()); case JJTNOT_1OP: return new UnaryOp(UnaryOp.Not, makeExpr()); case JJTCALL_OP: //if (arity == 1) // return new Call(makeExpr(), null, null, null, null); exprType starargs = null; exprType kwargs = null; l = arity - 1; if (l > 0 && peekNode().getId() == JJTEXTRAKEYWORDVALUELIST) { kwargs = ((ExtraArgValue) popNode()).value; l--; } if (l > 0 && peekNode().getId() == JJTEXTRAARGVALUELIST) { starargs = ((ExtraArgValue) popNode()).value; l--; } int nargs = l; SimpleNode[] tmparr = new SimpleNode[l]; for (int i = l - 1; i >= 0; i--) { tmparr[i] = popNode(); if (tmparr[i] instanceof keywordType) { nargs = i; } } exprType[] args = new exprType[nargs]; for (int i = 0; i < nargs; i++) { args[i] = makeExpr(tmparr[i]); } keywordType[] keywords = new keywordType[l - nargs]; for (int i = nargs; i < l; i++) { if (!(tmparr[i] instanceof keywordType)) throw new ParseException( "non-keyword argument following keyword", tmparr[i]); keywords[i - nargs] = (keywordType) tmparr[i]; } exprType func = makeExpr(); return new Call(func, args, keywords, starargs, kwargs); case JJTEXTRAKEYWORDVALUELIST: return new ExtraArgValue(makeExpr(), JJTEXTRAKEYWORDVALUELIST); case JJTEXTRAARGVALUELIST: return new ExtraArgValue(makeExpr(), JJTEXTRAARGVALUELIST); case JJTKEYWORD: value = makeExpr(); name = makeIdentifier(); return new keywordType(name, value); case JJTTUPLE: return new Tuple(makeExprs(), Tuple.Load); case JJTLIST: if (stack.nodeArity() > 0 && peekNode() instanceof listcompType) { listcompType[] generators = new listcompType[arity-1]; for (int i = arity-2; i >= 0; i--) { generators[i] = (listcompType) popNode(); } return new ListComp(makeExpr(), generators); } return new List(makeExprs(), List.Load); case JJTDICTIONARY: l = arity / 2; exprType[] keys = new exprType[l]; exprType[] vals = new exprType[l]; for (int i = l - 1; i >= 0; i--) { vals[i] = makeExpr(); keys[i] = makeExpr(); } return new Dict(keys, vals); case JJTSTR_1OP: return new Repr(makeExpr()); case JJTSTRJOIN: String str2 = ((Str) popNode()).s; String str1 = ((Str) popNode()).s; return new Str(str1 + str2); case JJTLAMBDEF: test = makeExpr(); arguments = makeArguments(arity - 1); return new Lambda(arguments, test); case JJTELLIPSES: return new Ellipsis(); case JJTSLICE: SimpleNode[] arr = new SimpleNode[arity]; for (int i = arity-1; i >= 0; i--) { arr[i] = popNode(); } exprType[] values = new exprType[3]; int k = 0; for (int j = 0; j < arity; j++) { if (arr[j].getId() == JJTCOLON) k++; else values[k] = makeExpr(arr[j]); } if (k == 0) { return new Index(values[0]); } else { return new Slice(values[0], values[1], values[2]); } case JJTSUBSCRIPTLIST: if (arity > 0 && peekNode().getId() == JJTCOMMA){ arity--; popNode(); } sliceType[] dims = new sliceType[arity]; for (int i = arity - 1; i >= 0; i--) { dims[i] = (sliceType) popNode(); } return new ExtSlice(dims); case JJTAUG_PLUS: return makeAugAssign(AugAssign.Add); case JJTAUG_MINUS: return makeAugAssign(AugAssign.Sub); case JJTAUG_MULTIPLY: return makeAugAssign(AugAssign.Mult); case JJTAUG_DIVIDE: return makeAugAssign(AugAssign.Div); case JJTAUG_MODULO: return makeAugAssign(AugAssign.Mod); case JJTAUG_AND: return makeAugAssign(AugAssign.BitAnd); case JJTAUG_OR: return makeAugAssign(AugAssign.BitOr); case JJTAUG_XOR: return makeAugAssign(AugAssign.BitXor); case JJTAUG_LSHIFT: return makeAugAssign(AugAssign.LShift); case JJTAUG_RSHIFT: return makeAugAssign(AugAssign.RShift); case JJTAUG_POWER: return makeAugAssign(AugAssign.Pow); case JJTAUG_FLOORDIVIDE: return makeAugAssign(AugAssign.FloorDiv); case JJTLIST_FOR: exprType[] ifs = new exprType[arity-2]; for (int i = arity-3; i >= 0; i--) { ifs[i] = makeExpr(); } iter = makeExpr(); target = makeExpr(); ctx.setStore(target); return new listcompType(target, iter, ifs); case JJTIMPORTFROM: aliasType[] aliases = makeAliases(arity - 1); String module = makeIdentifier(); return new ImportFrom(module, aliases); case JJTIMPORT: return new Import(makeAliases()); case JJTDOTTED_NAME: StringBuffer sb = new StringBuffer(); for (int i = 0; i < arity; i++) { if (i > 0) sb.insert(0, '.'); sb.insert(0, makeIdentifier()); } return new Name(sb.toString(), Name.Load); case JJTDOTTED_AS_NAME: String asname = null; if (arity > 1) asname = makeIdentifier(); return new aliasType(makeIdentifier(), asname); case JJTIMPORT_AS_NAME: asname = null; if (arity > 1) asname = makeIdentifier(); return new aliasType(makeIdentifier(), asname); case JJTCOMMA: case JJTCOLON: return n; default: return null; } }
diff --git a/repose-aggregator/services/service-client/impl/src/main/java/com/rackspace/papi/service/serviceclient/akka/AkkaServiceClientImpl.java b/repose-aggregator/services/service-client/impl/src/main/java/com/rackspace/papi/service/serviceclient/akka/AkkaServiceClientImpl.java index 08b7765a1e..4dd262a381 100644 --- a/repose-aggregator/services/service-client/impl/src/main/java/com/rackspace/papi/service/serviceclient/akka/AkkaServiceClientImpl.java +++ b/repose-aggregator/services/service-client/impl/src/main/java/com/rackspace/papi/service/serviceclient/akka/AkkaServiceClientImpl.java @@ -1,98 +1,97 @@ package com.rackspace.papi.service.serviceclient.akka; import akka.actor.*; import akka.routing.RoundRobinRouter; import akka.util.Timeout; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.rackspace.papi.commons.util.http.ServiceClient; import com.rackspace.papi.commons.util.http.ServiceClientResponse; import com.rackspace.papi.service.httpclient.HttpClientService; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import java.util.Map; import java.util.concurrent.TimeUnit; import static akka.pattern.Patterns.ask; public class AkkaServiceClientImpl implements AkkaServiceClient { final private ServiceClient serviceClient; private ActorSystem actorSystem; private ActorRef tokenActorRef; private int numberOfActors; private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(AkkaServiceClientImpl.class); final Timeout t = new Timeout(50, TimeUnit.SECONDS); private final Cache<String, Future> quickFutureCache; private static final long FUTURE_CACHE_TTL = 500; @Autowired public AkkaServiceClientImpl(HttpClientService httpClientService) { this.serviceClient = getServiceClient(httpClientService); numberOfActors = serviceClient.getPoolSize(); - Config customConf = ConfigFactory.parseString( - "akka { actor { default-dispatcher {throughput = 10} } }"); - Config regularConf = ConfigFactory.defaultReference(); - Config combinedConf = customConf.withFallback(regularConf); + Config customConf = ConfigFactory.load(); + Config baseConf = ConfigFactory.defaultReference(); + Config conf = customConf.withFallback(baseConf); - actorSystem = ActorSystem.create("AuthClientActors", ConfigFactory.load(combinedConf)); + actorSystem = ActorSystem.create("AuthClientActors", conf); quickFutureCache = CacheBuilder.newBuilder() .expireAfterWrite(FUTURE_CACHE_TTL, TimeUnit.MILLISECONDS) .build(); tokenActorRef = actorSystem.actorOf(new Props(new UntypedActorFactory() { public UntypedActor create() { return new AuthTokenFutureActor(serviceClient); } }).withRouter(new RoundRobinRouter(numberOfActors)), "authRequestRouter"); } @Override public ServiceClientResponse get(String key, String uri, Map<String, String> headers) { ServiceClientResponse reusableServiceserviceClientResponse = null; AuthGetRequest authGetRequest = new AuthGetRequest(key, uri, headers); Future<ServiceClientResponse> future = getFuture(authGetRequest); try { reusableServiceserviceClientResponse = Await.result(future, Duration.create(50, TimeUnit.SECONDS)); } catch (Exception e) { LOG.error("error with akka future: " + e.getMessage()); } return reusableServiceserviceClientResponse; } @Override public void shutdown(){ actorSystem.shutdown(); } public Future getFuture(AuthGetRequest authGetRequest) { String token = authGetRequest.hashKey(); Future<Object> newFuture; if (!quickFutureCache.asMap().containsKey(token)) { synchronized (quickFutureCache) { if (!quickFutureCache.asMap().containsKey(token)) { newFuture = ask(tokenActorRef, authGetRequest, t); quickFutureCache.asMap().putIfAbsent(token, newFuture); } } } return quickFutureCache.asMap().get(token); } public ServiceClient getServiceClient(HttpClientService httpClientService){ return new ServiceClient(null,httpClientService); } }
false
true
public AkkaServiceClientImpl(HttpClientService httpClientService) { this.serviceClient = getServiceClient(httpClientService); numberOfActors = serviceClient.getPoolSize(); Config customConf = ConfigFactory.parseString( "akka { actor { default-dispatcher {throughput = 10} } }"); Config regularConf = ConfigFactory.defaultReference(); Config combinedConf = customConf.withFallback(regularConf); actorSystem = ActorSystem.create("AuthClientActors", ConfigFactory.load(combinedConf)); quickFutureCache = CacheBuilder.newBuilder() .expireAfterWrite(FUTURE_CACHE_TTL, TimeUnit.MILLISECONDS) .build(); tokenActorRef = actorSystem.actorOf(new Props(new UntypedActorFactory() { public UntypedActor create() { return new AuthTokenFutureActor(serviceClient); } }).withRouter(new RoundRobinRouter(numberOfActors)), "authRequestRouter"); }
public AkkaServiceClientImpl(HttpClientService httpClientService) { this.serviceClient = getServiceClient(httpClientService); numberOfActors = serviceClient.getPoolSize(); Config customConf = ConfigFactory.load(); Config baseConf = ConfigFactory.defaultReference(); Config conf = customConf.withFallback(baseConf); actorSystem = ActorSystem.create("AuthClientActors", conf); quickFutureCache = CacheBuilder.newBuilder() .expireAfterWrite(FUTURE_CACHE_TTL, TimeUnit.MILLISECONDS) .build(); tokenActorRef = actorSystem.actorOf(new Props(new UntypedActorFactory() { public UntypedActor create() { return new AuthTokenFutureActor(serviceClient); } }).withRouter(new RoundRobinRouter(numberOfActors)), "authRequestRouter"); }
diff --git a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckAsynchronous.java b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckAsynchronous.java index 24d65e68a..b41ed4ef5 100644 --- a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckAsynchronous.java +++ b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckAsynchronous.java @@ -1,145 +1,145 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.config.rules; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Future; import javax.ejb.Asynchronous; import org.apache.openejb.OpenEJBException; import org.apache.openejb.config.EjbModule; import org.apache.openejb.jee.ApplicationException; import org.apache.openejb.jee.AsyncMethod; import org.apache.openejb.jee.EnterpriseBean; import org.apache.openejb.jee.MethodParams; import org.apache.openejb.jee.SessionBean; import org.apache.xbean.finder.ClassFinder; /** * @version $Rev$ $Date$ */ public class CheckAsynchronous extends ValidationBase { public void validate(EjbModule module) { Set<String> applicationExceptions = new HashSet<String>(); for (ApplicationException applicationException : module.getEjbJar().getAssemblyDescriptor().getApplicationException()) { applicationExceptions.add(applicationException.getExceptionClass()); } for (EnterpriseBean bean : module.getEjbJar().getEnterpriseBeans()) { Class<?> ejbClass = null; try { ejbClass = loadClass(bean.getEjbClass()); } catch (OpenEJBException e) { continue; } if (bean instanceof SessionBean) { SessionBean session = (SessionBean) bean; for (AsyncMethod asyncMethod : session.getAsyncMethod()) { Method method = getMethod(ejbClass, asyncMethod); if (method == null) { fail(bean, "asynchronous.missing", asyncMethod.getMethodName(), ejbClass.getName(), getParameters(asyncMethod.getMethodParams())); } else { checkAsynchronousMethod(session, ejbClass, method, applicationExceptions); } } for (String className : session.getAsynchronousClasses()) { try { Class<?> cls = loadClass(className); for (Method method : cls.getDeclaredMethods()) { - if (Modifier.isPublic(method.getModifiers())) { + if (Modifier.isPublic(method.getModifiers()) && !method.isSynthetic()) { checkAsynchronousMethod(session, ejbClass, method, applicationExceptions); } else { //warn(session, "asynchronous.methodignored", ejbClass.getName(), method.getName()); } } } catch (OpenEJBException e) { //ignore ? } } } else { ClassFinder classFinder = new ClassFinder(ejbClass); for (Method method : classFinder.findAnnotatedMethods(Asynchronous.class)) { ignoredMethodAnnotation("Asynchronous", bean, bean.getEjbClass(), method.getName(), bean.getClass().getSimpleName()); } if (ejbClass.getAnnotation(Asynchronous.class) != null) { ignoredClassAnnotation("Asynchronous", bean, bean.getEjbClass(), bean.getClass().getSimpleName()); } } } } private void checkAsynchronousMethod(SessionBean bean, Class<?> ejbClass, Method method, Set<String> applicationExceptions) { Class<?> retType = method.getReturnType(); if (retType != void.class && retType != Future.class) { fail(bean, "asynchronous.badReturnType", method.getName(), retType.getName(), ejbClass.getName()); } if (retType == void.class) { String invalidThrowCauses = checkThrowCauses(method.getExceptionTypes(), applicationExceptions); if (invalidThrowCauses != null) { fail(bean, "asynchronous.badExceptionType", method.getName(), ejbClass.getName(), invalidThrowCauses); } } } /** * If the return value of the target method is void, it is not allowed to throw any application exception * @param exceptionTypes * @param applicationExceptions * @return */ private String checkThrowCauses(Class<?>[] exceptionTypes, Set<String> applicationExceptions) { StringBuilder buffer = null; for (Class<?> exceptionType : exceptionTypes) { if (applicationExceptions.contains(exceptionType.getName()) || !Exception.class.isAssignableFrom(exceptionType) || RuntimeException.class.isAssignableFrom(exceptionType)) { continue; } if (buffer == null) { buffer = new StringBuilder(exceptionType.getName()); } else { buffer.append(",").append(exceptionType.getName()); } } return buffer == null ? null : buffer.toString(); } private Method getMethod(Class<?> clazz, AsyncMethod asyncMethod) { try { MethodParams methodParams = asyncMethod.getMethodParams(); Class<?>[] parameterTypes; if (methodParams != null) { parameterTypes = new Class[methodParams.getMethodParam().size()]; int arrayIndex = 0; for (String parameterType : methodParams.getMethodParam()) { parameterTypes[arrayIndex++] = loadClass(parameterType); } } else { parameterTypes = new Class[0]; } return clazz.getMethod(asyncMethod.getMethodName(), parameterTypes); } catch (NoSuchMethodException e) { return null; } catch (OpenEJBException e) { throw new RuntimeException(e); } } }
true
true
public void validate(EjbModule module) { Set<String> applicationExceptions = new HashSet<String>(); for (ApplicationException applicationException : module.getEjbJar().getAssemblyDescriptor().getApplicationException()) { applicationExceptions.add(applicationException.getExceptionClass()); } for (EnterpriseBean bean : module.getEjbJar().getEnterpriseBeans()) { Class<?> ejbClass = null; try { ejbClass = loadClass(bean.getEjbClass()); } catch (OpenEJBException e) { continue; } if (bean instanceof SessionBean) { SessionBean session = (SessionBean) bean; for (AsyncMethod asyncMethod : session.getAsyncMethod()) { Method method = getMethod(ejbClass, asyncMethod); if (method == null) { fail(bean, "asynchronous.missing", asyncMethod.getMethodName(), ejbClass.getName(), getParameters(asyncMethod.getMethodParams())); } else { checkAsynchronousMethod(session, ejbClass, method, applicationExceptions); } } for (String className : session.getAsynchronousClasses()) { try { Class<?> cls = loadClass(className); for (Method method : cls.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers())) { checkAsynchronousMethod(session, ejbClass, method, applicationExceptions); } else { //warn(session, "asynchronous.methodignored", ejbClass.getName(), method.getName()); } } } catch (OpenEJBException e) { //ignore ? } } } else { ClassFinder classFinder = new ClassFinder(ejbClass); for (Method method : classFinder.findAnnotatedMethods(Asynchronous.class)) { ignoredMethodAnnotation("Asynchronous", bean, bean.getEjbClass(), method.getName(), bean.getClass().getSimpleName()); } if (ejbClass.getAnnotation(Asynchronous.class) != null) { ignoredClassAnnotation("Asynchronous", bean, bean.getEjbClass(), bean.getClass().getSimpleName()); } } } }
public void validate(EjbModule module) { Set<String> applicationExceptions = new HashSet<String>(); for (ApplicationException applicationException : module.getEjbJar().getAssemblyDescriptor().getApplicationException()) { applicationExceptions.add(applicationException.getExceptionClass()); } for (EnterpriseBean bean : module.getEjbJar().getEnterpriseBeans()) { Class<?> ejbClass = null; try { ejbClass = loadClass(bean.getEjbClass()); } catch (OpenEJBException e) { continue; } if (bean instanceof SessionBean) { SessionBean session = (SessionBean) bean; for (AsyncMethod asyncMethod : session.getAsyncMethod()) { Method method = getMethod(ejbClass, asyncMethod); if (method == null) { fail(bean, "asynchronous.missing", asyncMethod.getMethodName(), ejbClass.getName(), getParameters(asyncMethod.getMethodParams())); } else { checkAsynchronousMethod(session, ejbClass, method, applicationExceptions); } } for (String className : session.getAsynchronousClasses()) { try { Class<?> cls = loadClass(className); for (Method method : cls.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers()) && !method.isSynthetic()) { checkAsynchronousMethod(session, ejbClass, method, applicationExceptions); } else { //warn(session, "asynchronous.methodignored", ejbClass.getName(), method.getName()); } } } catch (OpenEJBException e) { //ignore ? } } } else { ClassFinder classFinder = new ClassFinder(ejbClass); for (Method method : classFinder.findAnnotatedMethods(Asynchronous.class)) { ignoredMethodAnnotation("Asynchronous", bean, bean.getEjbClass(), method.getName(), bean.getClass().getSimpleName()); } if (ejbClass.getAnnotation(Asynchronous.class) != null) { ignoredClassAnnotation("Asynchronous", bean, bean.getEjbClass(), bean.getClass().getSimpleName()); } } } }
diff --git a/src/test/java/com/wikia/webdriver/Common/Core/CommonFunctions.java b/src/test/java/com/wikia/webdriver/Common/Core/CommonFunctions.java index e898987..6bbf6a7 100644 --- a/src/test/java/com/wikia/webdriver/Common/Core/CommonFunctions.java +++ b/src/test/java/com/wikia/webdriver/Common/Core/CommonFunctions.java @@ -1,841 +1,841 @@ package com.wikia.webdriver.Common.Core; import java.awt.AWTException; import java.awt.GraphicsEnvironment; import java.awt.MouseInfo; import java.awt.Rectangle; import java.awt.Robot; import java.awt.event.InputEvent; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Point; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import com.wikia.webdriver.Common.DriverProvider.DriverProvider; import com.wikia.webdriver.Common.Logging.PageObjectLogging; import com.wikia.webdriver.Common.Properties.Properties; public class CommonFunctions { static By logInAjax = By.className("ajaxLogin"); static By userNameField = By.cssSelector("[name='username']"); static By passwordField = By.cssSelector("[name='password']"); static By remeberMeCheckBox = By.cssSelector("input[type=checkbox]"); static By submitButton = By.cssSelector("input[type='submit']"); private static WebDriver driver; private static WebDriverWait wait; // public CommonFunctions() // { // driver = DriverProvider.getWebDriver(); // wait = new WebDriverWait(driver, 30); // } /** * log in by overlay available from main menu * * @param userName * @param password * @author: Karol Kujawiak */ private static void clickLogInAjax() { driver = DriverProvider.getWebDriver(); WebElement loginButton = driver.findElement(logInAjax); loginButton.click(); PageObjectLogging.log("logIn", "log in ajax button clicked", true, driver); } private static void typeInUserName(String userName) { driver = DriverProvider.getWebDriver(); WebElement userNameInAjax = driver.findElement(userNameField); userNameInAjax.sendKeys(userName); PageObjectLogging.log("logIn", "user name field populated", true, driver); } private static void typeInUserPass(String password) { driver = DriverProvider.getWebDriver(); WebElement passwordInAjax = driver.findElement(passwordField); passwordInAjax.sendKeys(password); PageObjectLogging .log("logIn", "password field populated", true, driver); } private static void clickSubmitLoginButton(String userName) { driver = DriverProvider.getWebDriver(); WebElement submitLoginButton = driver.findElement(submitButton); submitLoginButton.click(); PageObjectLogging.log("logIn", "submit button clicked", true, driver); } private static void verifyUserIsLoggedIn(String userName) { driver.findElement(By.cssSelector("a[href*='/User:" + userName + "']")); PageObjectLogging.log("verifyUserIsLoggedIn", "verified user is logged in", true, driver); } public static void logIn(String userName, String password) { driver = DriverProvider.getWebDriver(); driver.manage().deleteAllCookies(); String temp = driver.getCurrentUrl(); try { driver.get(Global.DOMAIN + "wiki/Special:UserLogin"); } catch (TimeoutException e) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); } WebElement userNameField = driver.findElement(By .cssSelector("#WikiaArticle input[name='username']")); WebElement passwordField = driver.findElement(By .cssSelector("#WikiaArticle input[name='password']")); WebElement submitButton = driver.findElement(By .cssSelector("#WikiaArticle input.login-button.big")); userNameField.sendKeys(userName); passwordField.sendKeys(password); try { submitButton.click(); } catch (TimeoutException e) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); try { driver.navigate().refresh(); } catch (TimeoutException f) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); } } driver.findElement(By.cssSelector(".AccountNavigation a[href*='User:" + userName + "']"));// only for verification try { if (!temp.contains("Special:UserLogout")) { driver.get(temp); } } catch (TimeoutException e) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); } driver.findElement(By.cssSelector(".AccountNavigation a[href*='User:" + userName + "']")); // driver = DriverProvider.getWebDriver(); // wait = new WebDriverWait(driver, 30); // WebElement logInAjaxElem = driver.findElement(logInAjax); // logInAjaxElem.click(); // PageObjectLogging.log("logIn", "log in ajax button clicked", true, // driver); // wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[name='username']"))); // WebElement userNameFieldElem = driver.findElement(userNameField); // userNameFieldElem.sendKeys(userName); // PageObjectLogging.log("logIn", "user name field is populated with " + // userName, true, driver); // try { // Thread.sleep(500); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // WebElement passwordFieldElem = driver.findElement(passwordField); // PageObjectLogging.log("logIn", "password field is populated", true, // driver); // passwordFieldElem.sendKeys(password); // WebElement submitButtonElem = driver.findElement(submitButton); // submitButtonElem.click(); // PageObjectLogging.log("logIn", "submit button clicked", true, // driver); // wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("a[href*='/User:"+userName+"']"))); } public static void logInSpecialUserLogin(String userName, String password, String userNameEnc) { driver = DriverProvider.getWebDriver(); driver.manage().deleteAllCookies(); String temp = driver.getCurrentUrl(); try { driver.get(Global.DOMAIN + "wiki/Special:UserLogin"); } catch (TimeoutException e) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); } WebElement userNameField = driver.findElement(By .cssSelector("#WikiaArticle input[name='username']")); WebElement passwordField = driver.findElement(By .cssSelector("#WikiaArticle input[name='password']")); WebElement submitButton = driver.findElement(By .cssSelector("#WikiaArticle input.login-button.big")); userNameField.sendKeys(userName); passwordField.sendKeys(password); try { submitButton.click(); } catch (TimeoutException e) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); try { driver.navigate().refresh(); } catch (TimeoutException f) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); } } driver.findElement(By.cssSelector(".AccountNavigation a[href*='User:" + userNameEnc + "']"));// only for verification try { if (!temp.contains("Special:UserLogout")) { driver.get(temp); } } catch (TimeoutException e) { PageObjectLogging.log("logIn", "page loads for more than 30 seconds", true, driver); } driver.findElement(By.cssSelector(".AccountNavigation a[href*='User:" + userNameEnc + "']")); } /** * log in by overlay available from main menu * * @param userName * @param password * @author: Karol Kujawiak */ public static void logInDriver(String userName, String password, WebDriver driver) { wait = new WebDriverWait(driver, 30); WebElement logInAjaxElem = driver.findElement(logInAjax); logInAjaxElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("input[name='username']"))); WebElement userNameFieldElem = driver.findElement(userNameField); userNameFieldElem.sendKeys(userName); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } WebElement passwordFieldElem = driver.findElement(passwordField); passwordFieldElem.sendKeys(password); WebElement submitButtonElem = driver.findElement(submitButton); submitButtonElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("a[href*='/User:" + userName + "']"))); } public static void logInDropDown(String userName, String password, String userNameEnc) { driver = DriverProvider.getWebDriver(); wait = new WebDriverWait(driver, 30); WebElement logInAjaxElem = driver.findElement(logInAjax); logInAjaxElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("input[name='username']"))); WebElement userNameFieldElem = driver.findElement(userNameField); userNameFieldElem.sendKeys(userName); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } WebElement passwordFieldElem = driver.findElement(passwordField); passwordFieldElem.sendKeys(password); WebElement submitButtonElem = driver.findElement(submitButton); submitButtonElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("a[href*='/User:" + userNameEnc + "']"))); } /** * log in by overlay available from main menu * * @param userName * @param password * @author: Karol Kujawiak */ public static void logIn(String userName, String password, WebDriver driver) { String temp = driver.getCurrentUrl(); driver.get(Global.DOMAIN + "wiki/Special:UserLogin"); WebElement userNameField = driver.findElement(By .cssSelector("#WikiaArticle input[name='username']")); WebElement passwordField = driver.findElement(By .cssSelector("#WikiaArticle input[name='password']")); String submitButtonSelector = "#WikiaArticle input[class='login-button big']"; WebElement submitButton = driver.findElement(By .cssSelector(submitButtonSelector)); userNameField.sendKeys(userName); passwordField.sendKeys(password); submitButton.click(); driver.findElement(By.cssSelector(".AccountNavigation a[href*='User:" + userName + "']"));// only for verification driver.get(temp); } /** * * @param userName * @author: Karol Kujawiak */ public static void logOut(WebDriver driver) { wait = new WebDriverWait(driver, 30); try { driver.manage().deleteAllCookies(); driver.get(Global.DOMAIN + "wiki/Special:UserLogout?noexternals=1"); } catch (TimeoutException e) { PageObjectLogging.log("logOut", "page loads for more than 30 seconds", true); } wait.until(ExpectedConditions.visibilityOfElementLocated(By .cssSelector("a[data-id='login']"))); PageObjectLogging.log("logOut", "uses is logged out", true, driver); } /** * log in by overlay available from main menu, using generic credentials * * @author: Karol Kujawiak */ public static void logIn() { driver = DriverProvider.getWebDriver(); wait = new WebDriverWait(driver, 30); WebElement logInAjaxElem = driver.findElement(logInAjax); logInAjaxElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("input[name='username']"))); WebElement userNameFieldElem = driver.findElement(userNameField); userNameFieldElem.sendKeys(Properties.userName); WebElement passwordFieldElem = driver.findElement(passwordField); passwordFieldElem.sendKeys(Properties.password); WebElement submitButtonElem = driver.findElement(submitButton); submitButtonElem.click(); wait.until(ExpectedConditions.invisibilityOfElementLocated(By .cssSelector("header#WikiaHeader a.ajaxLogin"))); wait.until(ExpectedConditions.invisibilityOfElementLocated(By .cssSelector("header#WikiaHeader a.ajaxRegister"))); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("a[href*='/User:" + Properties.userName + "']"))); PageObjectLogging.log("logIn ", "Normal user logged in", true, driver); } /** * log in by overlay available from main menu, using generic credentials * with stay logged in check-box checked * * @author: Karol Kujawiak */ public static void logInRememberMe() { driver = DriverProvider.getWebDriver(); wait = new WebDriverWait(driver, 30); WebElement logInAjaxElem = driver.findElement(logInAjax); logInAjaxElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("input[name='username']"))); WebElement userNameFieldElem = driver.findElement(userNameField); userNameFieldElem.sendKeys(Properties.userName); WebElement passwordFieldElem = driver.findElement(passwordField); passwordFieldElem.sendKeys(Properties.password); WebElement rememberMeCheckBox = driver.findElement(remeberMeCheckBox); rememberMeCheckBox.click(); WebElement submitButtonElem = driver.findElement(submitButton); submitButtonElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("a[href*='/User:" + Properties.userName + "']"))); PageObjectLogging.log("logIn ", "Normal user logged in", true, driver); } /** * Obsolete below method - should be fixed * */ public static void logInAsStaff() { driver = DriverProvider.getWebDriver(); wait = new WebDriverWait(driver, 30); WebElement logInAjaxElem = driver.findElement(logInAjax); logInAjaxElem.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("input[name='username']"))); WebElement userNameFieldElem = driver.findElement(userNameField); userNameFieldElem.sendKeys(Properties.userNameStaff); WebElement passwordFieldElem = driver.findElement(passwordField); passwordFieldElem.sendKeys(Properties.passwordStaff); WebElement submitButtonElem = driver.findElement(submitButton); submitButtonElem.click(); wait.until(ExpectedConditions.invisibilityOfElementLocated(By .cssSelector("header#WikiaHeader a.ajaxLogin"))); wait.until(ExpectedConditions.invisibilityOfElementLocated(By .cssSelector("header#WikiaHeader a.ajaxRegister"))); wait.until(ExpectedConditions.presenceOfElementLocated(By .cssSelector("a[href*='/User:" + Properties.userNameStaff + "']"))); PageObjectLogging.log("logInAsStaff ", "Staff user logged in", true, driver); } /** * verifies whether pattern and current string are the same and log to log * file * * @param pattern * @param current * @author: Karol Kujawiak */ public static void assertString(String pattern, String current) { try { Assert.assertEquals(pattern, current); PageObjectLogging.log("assertString", "pattern string: " + pattern + " <br/>current string: " + current + "<br/>are the same", true); } catch (AssertionError e) { PageObjectLogging.log("assertString", "pattern string: " + pattern + " <br/>current string: " + current + "<br/>are different", false); } } /** * Verify actual number is the same as expected number * * @param aNumber * @param secondNumber * @author: Piotr Gabryjeluk */ public static void assertNumber(Number expected, Number actual, String message) { try { Assert.assertEquals(expected, actual); PageObjectLogging.log("assertNumber", message + ", expected: " + expected + ", got: " + actual, true); } catch (AssertionError e) { PageObjectLogging.log("assertNumber", message + ", expected: " + expected + ", got: " + actual, false); } } /** * * @param attributeName * @return * @author: Karol Kujawiak */ public static String currentlyFocusedGetAttributeValue(String attributeName) { String currentlyFocusedName = getCurrentlyFocused().getAttribute( attributeName); return currentlyFocusedName; } /** * * @param element * @param attributeName * @return * @author: Karol Kujawiak */ public static String getAttributeValue(WebElement element, String attributeName) { driver = DriverProvider.getWebDriver(); wait = new WebDriverWait(driver, 30); return element.getAttribute(attributeName); } /** * * @return author: Karol Kujawiak */ public static WebElement getCurrentlyFocused() { driver = DriverProvider.getWebDriver(); wait = new WebDriverWait(driver, 30); return driver.switchTo().activeElement(); } /** * Scroll to the given element * <p> * This mehtod is used mostly because Chrome does not scroll to elements * automaticly (18 july 2012) * <p> * This method uses JavascriptExecutor * * @author Michal Nowierski * @param element * Webelement to be scrolled to */ public static void scrollToElement(WebElement element) { driver = DriverProvider.getWebDriver(); wait = new WebDriverWait(driver, 30); int y = element.getLocation().getY(); // firstly make sure that window scroll is set at the top of browser (if // not method will scroll up) ((JavascriptExecutor) driver) .executeScript("window.scrollBy(0,-3000);"); ((JavascriptExecutor) driver).executeScript("window.scrollBy(0," + y + ");"); } /** * Move cursor to the given X and Y coordinates * * @author Michal Nowierski * @param x * @param y */ public static void MoveCursorTo(int x, int y) { Robot robot = null; try { Thread.sleep(1000); robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } robot.mouseMove(x, y); } /** * Move cursor to Element existing in default DOM, by its Location * * @author Michal Nowierski * @param elem1_location * Location of WebElement (getLocation method) */ public static void MoveCursorToElement(Point elem1_location) { // Toolkit toolkit = Toolkit.getDefaultToolkit (); // Dimension dim = toolkit.getScreenSize(); // double ScreenHeight = dim.getHeight(); // int FireFoxStatusBarHeight = 20; driver = DriverProvider.getWebDriver(); int pixDiff = 0; if (Global.BROWSER.equals("FF")) { pixDiff = 6; } int elem_Y = elem1_location.getY(); int elem_X = elem1_location.getX(); Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); int ScreenHeightWithoutTaskBarHeight = maxBounds.height; JavascriptExecutor js = (JavascriptExecutor) driver; Object visibleDomHeightJS = js .executeScript("return $(window).height()"); int VisibleDomHeight = Integer.parseInt(visibleDomHeightJS.toString()); Object invisibleUpperDomHeightJS = js .executeScript("return document.documentElement.scrollTop"); int invisibleUpperDomHeight = Integer .parseInt(invisibleUpperDomHeightJS.toString()); MoveCursorTo(elem_X + 10, elem_Y + ScreenHeightWithoutTaskBarHeight - VisibleDomHeight - pixDiff + 1 - invisibleUpperDomHeight); } public static void MoveCursorToElement(Point elem1_location, WebDriver driver) { // Toolkit toolkit = Toolkit.getDefaultToolkit (); // Dimension dim = toolkit.getScreenSize(); // double ScreenHeight = dim.getHeight(); // int FireFoxStatusBarHeight = 20; int pixDiff = 0; if (Global.BROWSER.equals("FF")) { pixDiff = 6; } int elem_Y = elem1_location.getY(); int elem_X = elem1_location.getX(); Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); int ScreenHeightWithoutTaskBarHeight = maxBounds.height; JavascriptExecutor js = (JavascriptExecutor) driver; Object visibleDomHeightJS = js .executeScript("return window.innerHeight"); int VisibleDomHeight = Integer.parseInt(visibleDomHeightJS.toString()); Object invisibileUpperDomHeightJS = js .executeScript("return window.pageYOffset"); int invisibileUpperDomHeight = Integer .parseInt(invisibileUpperDomHeightJS.toString()); MoveCursorTo(elem_X + 10, elem_Y + ScreenHeightWithoutTaskBarHeight - VisibleDomHeight - invisibileUpperDomHeight - pixDiff + 1); } /** * Move cursor to Element existing in an IFrame DOM, by its By locator, and * the Iframe Webelement * * @author Michal Nowierski * @param IframeElemBy * By selector of element to be hovered over * @param IFrame * IFrame where the element exists */ public static void MoveCursorToIFrameElement(By IframeElemBy, WebElement IFrame) { driver = DriverProvider.getWebDriver(); Point IFrameLocation = IFrame.getLocation(); driver.switchTo().frame(IFrame); wait.until(ExpectedConditions.visibilityOfElementLocated(IframeElemBy)); Point IFrameElemLocation = driver.findElement(IframeElemBy) .getLocation(); IFrameElemLocation = IFrameElemLocation.moveBy(IFrameLocation.getX(), IFrameLocation.getY()); driver.switchTo().defaultContent(); MoveCursorToElement(IFrameElemLocation); } public static void ClickElement() { Robot robot = null; try { Thread.sleep(300); robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); } /** * Move cursor to from current position by given x and y * * @author Michal Nowierski * @param x * horrizontal move * @param y * vertical move */ public static void DragFromCurrentCursorPositionAndDrop(int x, int y) { Robot robot = null; try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } java.awt.Point CurrentCursorPosition = MouseInfo.getPointerInfo() .getLocation(); int currentX = (int) CurrentCursorPosition.getX(); int currentY = (int) CurrentCursorPosition.getY(); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseMove(currentX + x, currentY + y); robot.mouseRelease(InputEvent.BUTTON1_MASK); } public static void removeChatModeratorRights(String userName, WebDriver driver) { driver.get(Global.DOMAIN + "wiki/Special:UserRights?user=" + userName); PageObjectLogging.log("enterUserRightsPage", "user rights page opened", true); WebElement chatModeratorChkbox = driver.findElement((By .cssSelector("input#wpGroup-chatmoderator"))); WebElement submitButton = driver.findElement((By .cssSelector("input[title='[alt-shift-s]']"))); chatModeratorChkbox.click(); submitButton.click(); } public static String logInCookie(String userName, String password) { try { driver = DriverProvider.getWebDriver(); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Global.DOMAIN + "api.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("action", "login")); nvps.add(new BasicNameValuePair("format", "xml")); nvps.add(new BasicNameValuePair("lgname", userName)); nvps.add(new BasicNameValuePair("lgpassword", password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = null; response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); String xmlResponse = null; xmlResponse = EntityUtils.toString(entity); String[] xmlResponseArr = xmlResponse.split("\""); String token = xmlResponseArr[5]; // System.out.println(token); while (xmlResponseArr.length < 11) {// sometimes first request does // not contain full information, // in such situation // xmlResponseArr.length < 11 List<NameValuePair> nvps2 = new ArrayList<NameValuePair>(); nvps2.add(new BasicNameValuePair("action", "login")); nvps2.add(new BasicNameValuePair("format", "xml")); nvps2.add(new BasicNameValuePair("lgname", userName)); nvps2.add(new BasicNameValuePair("lgpassword", password)); nvps2.add(new BasicNameValuePair("lgtoken", token)); httpPost.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8)); response = httpclient.execute(httpPost); entity = response.getEntity(); xmlResponse = EntityUtils.toString(entity); xmlResponseArr = xmlResponse.split("\""); } JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("$.cookie('" + xmlResponseArr[11] + "_session', '" + xmlResponseArr[13] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserName', '" + xmlResponseArr[7] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserID', '" + xmlResponseArr[5] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "Token', '" + xmlResponseArr[9] + "', {'domain': 'wikia.com'})"); return xmlResponseArr[11]; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static String logInCookie(String userName, String password, WebDriver driver) { try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost( "http://mediawiki119.wikia.com/api.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("action", "login")); nvps.add(new BasicNameValuePair("format", "xml")); nvps.add(new BasicNameValuePair("lgname", userName)); nvps.add(new BasicNameValuePair("lgpassword", password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = null; response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); String xmlResponse = null; xmlResponse = EntityUtils.toString(entity); String[] xmlResponseArr = xmlResponse.split("\""); String token = xmlResponseArr[5]; while (xmlResponseArr.length < 11) {// sometimes first request does // not contain full information, // in such situation // xmlResponseArr.length < 11 List<NameValuePair> nvps2 = new ArrayList<NameValuePair>(); nvps2.add(new BasicNameValuePair("action", "login")); nvps2.add(new BasicNameValuePair("format", "xml")); nvps2.add(new BasicNameValuePair("lgname", userName)); nvps2.add(new BasicNameValuePair("lgpassword", password)); nvps2.add(new BasicNameValuePair("lgtoken", token)); httpPost.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8)); response = httpclient.execute(httpPost); entity = response.getEntity(); xmlResponse = EntityUtils.toString(entity); xmlResponseArr = xmlResponse.split("\""); } JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("$.cookie('" + xmlResponseArr[11] + "_session', '" + xmlResponseArr[13] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserName', '" + xmlResponseArr[7] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserID', '" + xmlResponseArr[5] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "Token', '" + xmlResponseArr[9] + "', {'domain': 'wikia.com'})"); try { - driver.navigate().refresh(); + driver.get(Global.DOMAIN+"Special:Random"); } catch (TimeoutException e) { PageObjectLogging.log("loginCookie", "page timeout after login by cookie", true); } driver.findElement(By .cssSelector(".AccountNavigation a[href*='User:" + userName + "']"));// only for verification PageObjectLogging.log("loginCookie", "user was logged in by cookie", true, driver); return xmlResponseArr[11]; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static void logoutCookie(String wiki) { driver = DriverProvider.getWebDriver(); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("$.cookie('" + wiki + "_session', null)"); js.executeScript("$.cookie('" + wiki + "UserName', null)"); js.executeScript("$.cookie('" + wiki + "UserID', null)"); js.executeScript("$.cookie('" + wiki + "Token', null)"); } }
true
true
public static String logInCookie(String userName, String password, WebDriver driver) { try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost( "http://mediawiki119.wikia.com/api.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("action", "login")); nvps.add(new BasicNameValuePair("format", "xml")); nvps.add(new BasicNameValuePair("lgname", userName)); nvps.add(new BasicNameValuePair("lgpassword", password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = null; response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); String xmlResponse = null; xmlResponse = EntityUtils.toString(entity); String[] xmlResponseArr = xmlResponse.split("\""); String token = xmlResponseArr[5]; while (xmlResponseArr.length < 11) {// sometimes first request does // not contain full information, // in such situation // xmlResponseArr.length < 11 List<NameValuePair> nvps2 = new ArrayList<NameValuePair>(); nvps2.add(new BasicNameValuePair("action", "login")); nvps2.add(new BasicNameValuePair("format", "xml")); nvps2.add(new BasicNameValuePair("lgname", userName)); nvps2.add(new BasicNameValuePair("lgpassword", password)); nvps2.add(new BasicNameValuePair("lgtoken", token)); httpPost.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8)); response = httpclient.execute(httpPost); entity = response.getEntity(); xmlResponse = EntityUtils.toString(entity); xmlResponseArr = xmlResponse.split("\""); } JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("$.cookie('" + xmlResponseArr[11] + "_session', '" + xmlResponseArr[13] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserName', '" + xmlResponseArr[7] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserID', '" + xmlResponseArr[5] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "Token', '" + xmlResponseArr[9] + "', {'domain': 'wikia.com'})"); try { driver.navigate().refresh(); } catch (TimeoutException e) { PageObjectLogging.log("loginCookie", "page timeout after login by cookie", true); } driver.findElement(By .cssSelector(".AccountNavigation a[href*='User:" + userName + "']"));// only for verification PageObjectLogging.log("loginCookie", "user was logged in by cookie", true, driver); return xmlResponseArr[11]; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
public static String logInCookie(String userName, String password, WebDriver driver) { try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost( "http://mediawiki119.wikia.com/api.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("action", "login")); nvps.add(new BasicNameValuePair("format", "xml")); nvps.add(new BasicNameValuePair("lgname", userName)); nvps.add(new BasicNameValuePair("lgpassword", password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = null; response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); String xmlResponse = null; xmlResponse = EntityUtils.toString(entity); String[] xmlResponseArr = xmlResponse.split("\""); String token = xmlResponseArr[5]; while (xmlResponseArr.length < 11) {// sometimes first request does // not contain full information, // in such situation // xmlResponseArr.length < 11 List<NameValuePair> nvps2 = new ArrayList<NameValuePair>(); nvps2.add(new BasicNameValuePair("action", "login")); nvps2.add(new BasicNameValuePair("format", "xml")); nvps2.add(new BasicNameValuePair("lgname", userName)); nvps2.add(new BasicNameValuePair("lgpassword", password)); nvps2.add(new BasicNameValuePair("lgtoken", token)); httpPost.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8)); response = httpclient.execute(httpPost); entity = response.getEntity(); xmlResponse = EntityUtils.toString(entity); xmlResponseArr = xmlResponse.split("\""); } JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("$.cookie('" + xmlResponseArr[11] + "_session', '" + xmlResponseArr[13] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserName', '" + xmlResponseArr[7] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "UserID', '" + xmlResponseArr[5] + "', {'domain': 'wikia.com'})"); js.executeScript("$.cookie('" + xmlResponseArr[11] + "Token', '" + xmlResponseArr[9] + "', {'domain': 'wikia.com'})"); try { driver.get(Global.DOMAIN+"Special:Random"); } catch (TimeoutException e) { PageObjectLogging.log("loginCookie", "page timeout after login by cookie", true); } driver.findElement(By .cssSelector(".AccountNavigation a[href*='User:" + userName + "']"));// only for verification PageObjectLogging.log("loginCookie", "user was logged in by cookie", true, driver); return xmlResponseArr[11]; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
diff --git a/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java b/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java index 037a0aa0..cb389721 100644 --- a/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java +++ b/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java @@ -1,166 +1,171 @@ /* * Copyright (C) 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.gmavenplus.mojo; import com.google.common.io.Closer; import org.codehaus.gmavenplus.model.Version; import org.codehaus.gmavenplus.util.ReflectionUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; /** * Executes Groovy scripts (in the pom or external). * * @author Keegan Witt * * @goal execute * @configurator include-project-test-dependencies * @requiresDependencyResolution test * @threadSafe */ public class ExecuteMojo extends AbstractToolsMojo { /** * The minimum version of Groovy that this mojo supports. */ protected static final Version MIN_GROOVY_VERSION = new Version(1, 5, 0); /** * Groovy scripts to run (in order). Can be an actual Groovy script or a * {@link java.net.URL URL} to a Groovy script (local or remote). * * @parameter * @required */ protected String[] scripts; /** * Whether to continue executing remaining scripts when a script fails. * * @parameter default-value="false" */ protected boolean continueExecuting; /** * The encoding of script files. * * @parameter default-value="${project.build.sourceEncoding}" */ protected String sourceEncoding; /** * Executes this mojo. * * @throws MojoExecutionException If an unexpected problem occurs. Throwing this exception causes a "BUILD ERROR" message to be displayed * @throws MojoFailureException If an expected problem (such as a compilation failure) occurs. Throwing this exception causes a "BUILD FAILURE" message to be displayed */ public void execute() throws MojoExecutionException, MojoFailureException { if (groovyVersionSupportsAction()) { logGroovyVersion("execute"); if (scripts == null || scripts.length == 0) { getLog().info("No scripts specified for execution. Skipping."); return; } try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); // create a GroovyShell to run scripts in Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass)); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "settings", settings); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "project", project); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "session", session); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "pluginArtifacts", pluginArtifacts); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "localRepository", localRepository); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "reactorProjects", reactorProjects); // this is intentionally after the default properties so that the user can override if desired for (String key : properties.stringPropertyNames()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.getProperty(key)); } // TODO: load configurable (compile, test, runtime, or system) dependencies onto classpath before executing so they can be used in scripts? // run the scripts int scriptNum = 1; for (String script : scripts) { Closer closer = Closer.create(); try { try { URL url = new URL(script); // it's a URL to a script getLog().info("Fetching Groovy script from " + url.toString() + "."); - BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); + BufferedReader reader; + if (sourceEncoding != null) { + reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); + } else { + reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream()))); + } StringBuilder scriptSource = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { scriptSource.append(line).append("\n"); } if (!scriptSource.toString().isEmpty()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString()); } } catch (MalformedURLException e) { // it's not a URL to a script, treat as a script body ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script); } catch (Throwable throwable) { throw closer.rethrow(throwable); } finally { closer.close(); } } catch (IOException ioe) { if (continueExecuting) { getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe); } else { throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe); } } scriptNum++; } } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e); } catch (InvocationTargetException e) { throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e); } catch (InstantiationException e) { throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e); } catch (IllegalAccessException e) { throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e); } } else { getLog().error("Your Groovy version (" + getGroovyVersion() + ") script execution. The minimum version of Groovy required is " + MIN_GROOVY_VERSION + ". Skipping script execution."); } } /** * Determines whether this mojo can be run with the version of Groovy supplied. * Must be >= 1.8.2 because not all the classes needed were available and * functioning correctly in previous versions. * * @return <code>true</code> only if the version of Groovy supports this mojo. */ protected boolean groovyVersionSupportsAction() { return getGroovyVersion() != null && getGroovyVersion().compareTo(MIN_GROOVY_VERSION) >= 0; } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { if (groovyVersionSupportsAction()) { logGroovyVersion("execute"); if (scripts == null || scripts.length == 0) { getLog().info("No scripts specified for execution. Skipping."); return; } try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); // create a GroovyShell to run scripts in Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass)); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "settings", settings); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "project", project); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "session", session); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "pluginArtifacts", pluginArtifacts); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "localRepository", localRepository); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "reactorProjects", reactorProjects); // this is intentionally after the default properties so that the user can override if desired for (String key : properties.stringPropertyNames()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.getProperty(key)); } // TODO: load configurable (compile, test, runtime, or system) dependencies onto classpath before executing so they can be used in scripts? // run the scripts int scriptNum = 1; for (String script : scripts) { Closer closer = Closer.create(); try { try { URL url = new URL(script); // it's a URL to a script getLog().info("Fetching Groovy script from " + url.toString() + "."); BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); StringBuilder scriptSource = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { scriptSource.append(line).append("\n"); } if (!scriptSource.toString().isEmpty()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString()); } } catch (MalformedURLException e) { // it's not a URL to a script, treat as a script body ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script); } catch (Throwable throwable) { throw closer.rethrow(throwable); } finally { closer.close(); } } catch (IOException ioe) { if (continueExecuting) { getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe); } else { throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe); } } scriptNum++; } } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e); } catch (InvocationTargetException e) { throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e); } catch (InstantiationException e) { throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e); } catch (IllegalAccessException e) { throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e); } } else { getLog().error("Your Groovy version (" + getGroovyVersion() + ") script execution. The minimum version of Groovy required is " + MIN_GROOVY_VERSION + ". Skipping script execution."); } }
public void execute() throws MojoExecutionException, MojoFailureException { if (groovyVersionSupportsAction()) { logGroovyVersion("execute"); if (scripts == null || scripts.length == 0) { getLog().info("No scripts specified for execution. Skipping."); return; } try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); // create a GroovyShell to run scripts in Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass)); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "settings", settings); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "project", project); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "session", session); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "pluginArtifacts", pluginArtifacts); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "localRepository", localRepository); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "reactorProjects", reactorProjects); // this is intentionally after the default properties so that the user can override if desired for (String key : properties.stringPropertyNames()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.getProperty(key)); } // TODO: load configurable (compile, test, runtime, or system) dependencies onto classpath before executing so they can be used in scripts? // run the scripts int scriptNum = 1; for (String script : scripts) { Closer closer = Closer.create(); try { try { URL url = new URL(script); // it's a URL to a script getLog().info("Fetching Groovy script from " + url.toString() + "."); BufferedReader reader; if (sourceEncoding != null) { reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); } else { reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream()))); } StringBuilder scriptSource = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { scriptSource.append(line).append("\n"); } if (!scriptSource.toString().isEmpty()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString()); } } catch (MalformedURLException e) { // it's not a URL to a script, treat as a script body ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script); } catch (Throwable throwable) { throw closer.rethrow(throwable); } finally { closer.close(); } } catch (IOException ioe) { if (continueExecuting) { getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe); } else { throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe); } } scriptNum++; } } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e); } catch (InvocationTargetException e) { throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e); } catch (InstantiationException e) { throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e); } catch (IllegalAccessException e) { throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e); } } else { getLog().error("Your Groovy version (" + getGroovyVersion() + ") script execution. The minimum version of Groovy required is " + MIN_GROOVY_VERSION + ". Skipping script execution."); } }
diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java index 1cf0b2df4..fe8f5e3bb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java @@ -1,144 +1,144 @@ /** * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.core; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.BitmapDrawable; import com.timsu.astrid.R; import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Functions; import com.todoroo.andlib.sql.Order; import com.todoroo.andlib.sql.QueryTemplate; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.activity.FilterListActivity; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.api.FilterCategory; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.api.SearchFilter; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; import com.todoroo.astrid.model.Task; /** * Exposes Astrid's built in filters to the {@link FilterListActivity} * * @author Tim Su <[email protected]> * */ public final class CoreFilterExposer extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Resources r = context.getResources(); // core filters Filter inbox = buildInboxFilter(r); SearchFilter searchFilter = new SearchFilter(CorePlugin.IDENTIFIER, r.getString(R.string.BFE_Search)); searchFilter.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_search)).getBitmap(); // extended FilterCategory extended = new FilterCategory(r.getString(R.string.BFE_Extended), new Filter[7]); Filter recent = new Filter(r.getString(R.string.BFE_Recent), r.getString(R.string.BFE_Recent), new QueryTemplate().orderBy(Order.desc(Task.MODIFICATION_DATE)).limit(15), null); recent.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_new)).getBitmap(); ContentValues hiddenValues = new ContentValues(); hiddenValues.put(Task.HIDE_UNTIL.name, DateUtilities.now() + DateUtilities.ONE_DAY); Filter hidden = new Filter(r.getString(R.string.BFE_Hidden), r.getString(R.string.BFE_Hidden), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), Criterion.not(TaskCriteria.isVisible()))). orderBy(Order.asc(Task.HIDE_UNTIL)), hiddenValues); hidden.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_clouds)).getBitmap(); ContentValues completedValues = new ContentValues(); hiddenValues.put(Task.COMPLETION_DATE.name, DateUtilities.now()); Filter completed = new Filter(r.getString(R.string.BFE_Completed), r.getString(R.string.BFE_Completed), new QueryTemplate().where(Criterion.and(TaskCriteria.completed(), Criterion.not(TaskCriteria.isDeleted()))). orderBy(Order.desc(Task.COMPLETION_DATE)), completedValues); completed.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_check)).getBitmap(); Filter deleted = new Filter(r.getString(R.string.BFE_Deleted), r.getString(R.string.BFE_Deleted), new QueryTemplate().where(TaskCriteria.isDeleted()). orderBy(Order.desc(Task.DELETION_DATE)), null); deleted.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_trash)).getBitmap(); // sorting filters Filter alphabetical = new Filter(r.getString(R.string.BFE_Alphabetical), r.getString(R.string.BFE_Alphabetical), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). - orderBy(Order.asc(Task.TITLE)), + orderBy(Order.asc(Functions.upper(Task.TITLE))), null); alphabetical.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_alpha)).getBitmap(); Filter dueDate = new Filter(r.getString(R.string.BFE_DueDate), r.getString(R.string.BFE_DueDate), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Functions.caseStatement(Task.DUE_DATE.eq(0), DateUtilities.now()*2, Task.DUE_DATE) + "+" + Task.IMPORTANCE)), //$NON-NLS-1$ null); dueDate.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_calendar)).getBitmap(); Filter importance = new Filter(r.getString(R.string.BFE_Importance), r.getString(R.string.BFE_Importance), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Task.IMPORTANCE + "*" + (2*DateUtilities.now()) + //$NON-NLS-1$ "+" + Functions.caseStatement(Task.DUE_DATE.eq(0), //$NON-NLS-1$ Functions.now() + "+" + DateUtilities.ONE_WEEK, //$NON-NLS-1$ Task.DUE_DATE))), null); importance.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_warning)).getBitmap(); extended.children[0] = recent; extended.children[1] = hidden; extended.children[2] = completed; extended.children[3] = deleted; extended.children[4] = alphabetical; extended.children[5] = dueDate; extended.children[6] = importance; // transmit filter list FilterListItem[] list = new FilterListItem[3]; list[0] = inbox; list[1] = searchFilter; list[2] = extended; Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, list); context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); } /** * Build inbox filter * @return */ public static Filter buildInboxFilter(Resources r) { Filter inbox = new Filter(r.getString(R.string.BFE_Active), r.getString(R.string.BFE_Active_title), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())), null); inbox.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_home)).getBitmap(); return inbox; } }
true
true
public void onReceive(Context context, Intent intent) { Resources r = context.getResources(); // core filters Filter inbox = buildInboxFilter(r); SearchFilter searchFilter = new SearchFilter(CorePlugin.IDENTIFIER, r.getString(R.string.BFE_Search)); searchFilter.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_search)).getBitmap(); // extended FilterCategory extended = new FilterCategory(r.getString(R.string.BFE_Extended), new Filter[7]); Filter recent = new Filter(r.getString(R.string.BFE_Recent), r.getString(R.string.BFE_Recent), new QueryTemplate().orderBy(Order.desc(Task.MODIFICATION_DATE)).limit(15), null); recent.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_new)).getBitmap(); ContentValues hiddenValues = new ContentValues(); hiddenValues.put(Task.HIDE_UNTIL.name, DateUtilities.now() + DateUtilities.ONE_DAY); Filter hidden = new Filter(r.getString(R.string.BFE_Hidden), r.getString(R.string.BFE_Hidden), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), Criterion.not(TaskCriteria.isVisible()))). orderBy(Order.asc(Task.HIDE_UNTIL)), hiddenValues); hidden.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_clouds)).getBitmap(); ContentValues completedValues = new ContentValues(); hiddenValues.put(Task.COMPLETION_DATE.name, DateUtilities.now()); Filter completed = new Filter(r.getString(R.string.BFE_Completed), r.getString(R.string.BFE_Completed), new QueryTemplate().where(Criterion.and(TaskCriteria.completed(), Criterion.not(TaskCriteria.isDeleted()))). orderBy(Order.desc(Task.COMPLETION_DATE)), completedValues); completed.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_check)).getBitmap(); Filter deleted = new Filter(r.getString(R.string.BFE_Deleted), r.getString(R.string.BFE_Deleted), new QueryTemplate().where(TaskCriteria.isDeleted()). orderBy(Order.desc(Task.DELETION_DATE)), null); deleted.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_trash)).getBitmap(); // sorting filters Filter alphabetical = new Filter(r.getString(R.string.BFE_Alphabetical), r.getString(R.string.BFE_Alphabetical), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Task.TITLE)), null); alphabetical.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_alpha)).getBitmap(); Filter dueDate = new Filter(r.getString(R.string.BFE_DueDate), r.getString(R.string.BFE_DueDate), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Functions.caseStatement(Task.DUE_DATE.eq(0), DateUtilities.now()*2, Task.DUE_DATE) + "+" + Task.IMPORTANCE)), //$NON-NLS-1$ null); dueDate.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_calendar)).getBitmap(); Filter importance = new Filter(r.getString(R.string.BFE_Importance), r.getString(R.string.BFE_Importance), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Task.IMPORTANCE + "*" + (2*DateUtilities.now()) + //$NON-NLS-1$ "+" + Functions.caseStatement(Task.DUE_DATE.eq(0), //$NON-NLS-1$ Functions.now() + "+" + DateUtilities.ONE_WEEK, //$NON-NLS-1$ Task.DUE_DATE))), null); importance.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_warning)).getBitmap(); extended.children[0] = recent; extended.children[1] = hidden; extended.children[2] = completed; extended.children[3] = deleted; extended.children[4] = alphabetical; extended.children[5] = dueDate; extended.children[6] = importance; // transmit filter list FilterListItem[] list = new FilterListItem[3]; list[0] = inbox; list[1] = searchFilter; list[2] = extended; Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, list); context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); }
public void onReceive(Context context, Intent intent) { Resources r = context.getResources(); // core filters Filter inbox = buildInboxFilter(r); SearchFilter searchFilter = new SearchFilter(CorePlugin.IDENTIFIER, r.getString(R.string.BFE_Search)); searchFilter.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_search)).getBitmap(); // extended FilterCategory extended = new FilterCategory(r.getString(R.string.BFE_Extended), new Filter[7]); Filter recent = new Filter(r.getString(R.string.BFE_Recent), r.getString(R.string.BFE_Recent), new QueryTemplate().orderBy(Order.desc(Task.MODIFICATION_DATE)).limit(15), null); recent.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_new)).getBitmap(); ContentValues hiddenValues = new ContentValues(); hiddenValues.put(Task.HIDE_UNTIL.name, DateUtilities.now() + DateUtilities.ONE_DAY); Filter hidden = new Filter(r.getString(R.string.BFE_Hidden), r.getString(R.string.BFE_Hidden), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), Criterion.not(TaskCriteria.isVisible()))). orderBy(Order.asc(Task.HIDE_UNTIL)), hiddenValues); hidden.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_clouds)).getBitmap(); ContentValues completedValues = new ContentValues(); hiddenValues.put(Task.COMPLETION_DATE.name, DateUtilities.now()); Filter completed = new Filter(r.getString(R.string.BFE_Completed), r.getString(R.string.BFE_Completed), new QueryTemplate().where(Criterion.and(TaskCriteria.completed(), Criterion.not(TaskCriteria.isDeleted()))). orderBy(Order.desc(Task.COMPLETION_DATE)), completedValues); completed.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_check)).getBitmap(); Filter deleted = new Filter(r.getString(R.string.BFE_Deleted), r.getString(R.string.BFE_Deleted), new QueryTemplate().where(TaskCriteria.isDeleted()). orderBy(Order.desc(Task.DELETION_DATE)), null); deleted.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_trash)).getBitmap(); // sorting filters Filter alphabetical = new Filter(r.getString(R.string.BFE_Alphabetical), r.getString(R.string.BFE_Alphabetical), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Functions.upper(Task.TITLE))), null); alphabetical.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_alpha)).getBitmap(); Filter dueDate = new Filter(r.getString(R.string.BFE_DueDate), r.getString(R.string.BFE_DueDate), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Functions.caseStatement(Task.DUE_DATE.eq(0), DateUtilities.now()*2, Task.DUE_DATE) + "+" + Task.IMPORTANCE)), //$NON-NLS-1$ null); dueDate.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_calendar)).getBitmap(); Filter importance = new Filter(r.getString(R.string.BFE_Importance), r.getString(R.string.BFE_Importance), new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())). orderBy(Order.asc(Task.IMPORTANCE + "*" + (2*DateUtilities.now()) + //$NON-NLS-1$ "+" + Functions.caseStatement(Task.DUE_DATE.eq(0), //$NON-NLS-1$ Functions.now() + "+" + DateUtilities.ONE_WEEK, //$NON-NLS-1$ Task.DUE_DATE))), null); importance.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_warning)).getBitmap(); extended.children[0] = recent; extended.children[1] = hidden; extended.children[2] = completed; extended.children[3] = deleted; extended.children[4] = alphabetical; extended.children[5] = dueDate; extended.children[6] = importance; // transmit filter list FilterListItem[] list = new FilterListItem[3]; list[0] = inbox; list[1] = searchFilter; list[2] = extended; Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, list); context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); }
diff --git a/src/contributions/resources/yanel-user/src/java/org/wyona/yanel/impl/resources/yaneluser/EditYanelUserProfileResource.java b/src/contributions/resources/yanel-user/src/java/org/wyona/yanel/impl/resources/yaneluser/EditYanelUserProfileResource.java index 4892e784c..2e0c3417c 100644 --- a/src/contributions/resources/yanel-user/src/java/org/wyona/yanel/impl/resources/yaneluser/EditYanelUserProfileResource.java +++ b/src/contributions/resources/yanel-user/src/java/org/wyona/yanel/impl/resources/yaneluser/EditYanelUserProfileResource.java @@ -1,215 +1,220 @@ /* * Copyright 2010 Wyona */ package org.wyona.yanel.impl.resources.yaneluser; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.impl.resources.BasicXMLResource; import org.wyona.security.core.api.User; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; /** * A resource to edit/update the profile of a user */ public class EditYanelUserProfileResource extends BasicXMLResource { private static Logger log = Logger.getLogger(EditYanelUserProfileResource.class); private String transformerParameterName; private String transformerParameterValue; /* * @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String) */ protected InputStream getContentXML(String viewId) { if (log.isDebugEnabled()) { log.debug("requested viewId: " + viewId); } String oldPassword = getEnvironment().getRequest().getParameter("oldPassword"); if (oldPassword != null) { updatePassword(oldPassword); } String email = getEnvironment().getRequest().getParameter("email"); if (email != null) { updateProfile(email); } try { return getXMLAsStream(); } catch(Exception e) { log.error(e, e); return null; } } /** * Get user profile as XML as stream */ private java.io.InputStream getXMLAsStream() throws Exception { String userId = getUserId(); if (userId != null) { User user = realm.getIdentityManager().getUserManager().getUser(userId); StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<user id=\"" + userId + "\" email=\"" + user.getEmail() + "\" language=\"" + user.getLanguage() + "\">"); sb.append(" <name>" + user.getName() + "</name>"); sb.append(" <expiration-date>" + user.getExpirationDate() + "</expiration-date>"); sb.append(" <description>" + user.getDescription() + "</description>"); org.wyona.security.core.api.Group[] groups = user.getGroups(); if (groups != null && groups.length > 0) { sb.append(" <groups>"); for (int i = 0; i < groups.length; i++) { sb.append(" <group id=\"" + groups[i].getID() + "\"/>"); } sb.append(" </groups>"); } sb.append("</user>"); return new java.io.StringBufferInputStream(sb.toString()); } else { return new java.io.StringBufferInputStream("<no-user-id/>"); } } /** * Get user id from resource configuration */ private String getUserId() throws Exception { + String userId = null; // 1) - if (getEnvironment().getRequest().getParameter("id") != null) { - return getEnvironment().getRequest().getParameter("id"); + userId = getEnvironment().getRequest().getParameter("id"); + if (userId != null) { + if (getRealm().getPolicyManager().authorize("/yanel/users/" + userId + ".html", getEnvironment().getIdentity(), new org.wyona.security.core.api.Usecase("view"))) { // INFO: Because the policymanager has no mean to check (or interpret) query strings we need to recheck programmatically + return userId; + } else { + //throw new Exception("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!"); + log.warn("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!"); + } } // 2) ResourceConfiguration resConfig = getConfiguration(); - String userId = null; if(resConfig != null) { userId = getConfiguration().getProperty("user"); } else { log.warn("DEPRECATED: Do not use RTI but rather a resource configuration"); userId = getRTI().getProperty("user"); } if (userId != null) { return userId; } // 3) - final String userName = getPath().substring(getPath().lastIndexOf("/") + 1, getPath().lastIndexOf(".html")); - log.debug("User name: " + userName); - if (userName != null && getRealm().getIdentityManager().getUserManager().existsUser(userName)) { - return userName; + userId = getPath().substring(getPath().lastIndexOf("/") + 1, getPath().lastIndexOf(".html")); + if (userId != null && getRealm().getIdentityManager().getUserManager().existsUser(userId)) { + return userId; } else { - throw new Exception("No such user '" + userName + "'"); + throw new Exception("No such user '" + userId + "'"); } } /** * Change user password * * @param oldPassword Existing current password */ private void updatePassword(String oldPassword) { try { String userId = getUserId(); if (!getRealm().getIdentityManager().getUserManager().getUser(userId).authenticate(oldPassword)) { setTransformerParameter("error", "Authentication of user '" +userId + "' failed!"); log.error("Authentication of user '" + userId + "' failed!"); return; } String newPassword = getEnvironment().getRequest().getParameter("newPassword"); String newPasswordConfirmed = getEnvironment().getRequest().getParameter("newPasswordConfirmation"); if (newPassword != null && !newPassword.equals("")) { if (newPassword.equals(newPasswordConfirmed)) { User user = getRealm().getIdentityManager().getUserManager().getUser(userId); user.setPassword(newPassword); user.save(); setTransformerParameter("success", "Password updated successfully"); } else { setTransformerParameter("error", "New password and its confirmation do not match!"); } } else { setTransformerParameter("error", "No new password was specified!"); } } catch (Exception e) { log.error(e, e); } } /** * Updates the user profile * * @param email E-Mail address of user */ private void updateProfile(String email) { if (email == null || ("").equals(email)) { setTransformerParameter("error", "emailNotSet"); } else if (!validateEmail(email)) { setTransformerParameter("error", "emailNotValid"); } else { try { String userId = getUserId(); User user = realm.getIdentityManager().getUserManager().getUser(userId); user.setEmail(getEnvironment().getRequest().getParameter("email")); user.setName(getEnvironment().getRequest().getParameter("userName")); user.setLanguage(getEnvironment().getRequest().getParameter("user-profile-language")); user.save(); setTransformerParameter("success", "Profile updated successfully"); } catch (Exception e) { log.error(e, e); setTransformerParameter("error", e.getMessage()); } } } /** * */ private void setTransformerParameter(String name, String value) { transformerParameterName = name; transformerParameterValue = value; } /** * @see org.wyona.yanel.impl.resources.BasicXMLResource#passTransformerParameters(Transformer) */ protected void passTransformerParameters(javax.xml.transform.Transformer transformer) throws Exception { super.passTransformerParameters(transformer); try { if (transformerParameterName != null && transformerParameterValue != null) { transformer.setParameter(transformerParameterName, transformerParameterValue); transformerParameterName = null; transformerParameterValue = null; } } catch (Exception e) { log.error(e, e); } } /** * This method checks if the specified email is valid against a regex * * @param email * @return true if email is valid */ private boolean validateEmail(String email) { String emailRegEx = "(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*"; Pattern pattern = Pattern.compile(emailRegEx); Matcher matcher = pattern.matcher(email); return matcher.find(); } }
false
true
private String getUserId() throws Exception { // 1) if (getEnvironment().getRequest().getParameter("id") != null) { return getEnvironment().getRequest().getParameter("id"); } // 2) ResourceConfiguration resConfig = getConfiguration(); String userId = null; if(resConfig != null) { userId = getConfiguration().getProperty("user"); } else { log.warn("DEPRECATED: Do not use RTI but rather a resource configuration"); userId = getRTI().getProperty("user"); } if (userId != null) { return userId; } // 3) final String userName = getPath().substring(getPath().lastIndexOf("/") + 1, getPath().lastIndexOf(".html")); log.debug("User name: " + userName); if (userName != null && getRealm().getIdentityManager().getUserManager().existsUser(userName)) { return userName; } else { throw new Exception("No such user '" + userName + "'"); } }
private String getUserId() throws Exception { String userId = null; // 1) userId = getEnvironment().getRequest().getParameter("id"); if (userId != null) { if (getRealm().getPolicyManager().authorize("/yanel/users/" + userId + ".html", getEnvironment().getIdentity(), new org.wyona.security.core.api.Usecase("view"))) { // INFO: Because the policymanager has no mean to check (or interpret) query strings we need to recheck programmatically return userId; } else { //throw new Exception("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!"); log.warn("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!"); } } // 2) ResourceConfiguration resConfig = getConfiguration(); if(resConfig != null) { userId = getConfiguration().getProperty("user"); } else { log.warn("DEPRECATED: Do not use RTI but rather a resource configuration"); userId = getRTI().getProperty("user"); } if (userId != null) { return userId; } // 3) userId = getPath().substring(getPath().lastIndexOf("/") + 1, getPath().lastIndexOf(".html")); if (userId != null && getRealm().getIdentityManager().getUserManager().existsUser(userId)) { return userId; } else { throw new Exception("No such user '" + userId + "'"); } }
diff --git a/storage/memory/src/main/java/eu/europeana/uim/store/memory/MemoryMetaDataRecord.java b/storage/memory/src/main/java/eu/europeana/uim/store/memory/MemoryMetaDataRecord.java index 86a76569..a7cdbf6d 100644 --- a/storage/memory/src/main/java/eu/europeana/uim/store/memory/MemoryMetaDataRecord.java +++ b/storage/memory/src/main/java/eu/europeana/uim/store/memory/MemoryMetaDataRecord.java @@ -1,175 +1,178 @@ package eu.europeana.uim.store.memory; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import eu.europeana.uim.MetaDataRecord; import eu.europeana.uim.TKey; import eu.europeana.uim.store.Request; /** Core and generic representation of a meta data record. * * @author [email protected] * * @param <N> */ public class MemoryMetaDataRecord implements MetaDataRecord { private HashMap<TKey<?,?>, Object> fields = new HashMap<TKey<?,?>, Object>(); private HashMap<TKey<?,?>, Map<String, Object>> qFields = new HashMap<TKey<?,?>, Map<String, Object>>(); private long id; private Request request; private String identifier; public MemoryMetaDataRecord() { } public MemoryMetaDataRecord(long id) { this.id = id; } public long getId() { return id; } public void setId(long id) { this.id = id; } @Override public Request getRequest() { return request; } public void setRequest(Request request) { this.request = request; } @Override public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } /** * @param key * @param value */ @Override public <N, T extends Serializable> void setFirstField(TKey<N,T> key, T value){ if (!fields.containsKey(key)) { fields.put(key, new ArrayList<T>()); } if (((ArrayList<T>)fields.get(key)).isEmpty()) { ((ArrayList<T>)fields.get(key)).add(value); } else { ((ArrayList<T>)fields.get(key)).set(0, value); } } @Override public <N, T extends Serializable> T getFirstField(TKey<N,T> nttKey) { List<T> list = getField(nttKey); if (list != null && !list.isEmpty()) { return list.get(0); } return null; } /** * @param key * @param value */ @Override public <N, T extends Serializable> void setFirstQField(TKey<N,T> key, String qualifier, T value){ if (!qFields.containsKey(key)) { qFields.put(key, new HashMap<String, Object>()); } if (((ArrayList<T>)qFields.get(key)).isEmpty()) { ((ArrayList<T>)qFields.get(key).get(qualifier)).add(value); } else { ((ArrayList<T>)qFields.get(key).get(qualifier)).set(0,value); } } @Override public <N, T extends Serializable> T getFirstQField(TKey<N,T> nttKey, String qualifier) { List<T> list = getQField(nttKey, qualifier); if (list != null && !list.isEmpty()) { return list.get(0); } return null; } /** * @param key * @param value */ @Override @SuppressWarnings("unchecked") public <N, T extends Serializable> void addField(TKey<N, T> key, T value){ if (!fields.containsKey(key)) { fields.put(key, new ArrayList<T>()); } ((ArrayList<T>)fields.get(key)).add(value); } @Override public <N, T extends Serializable> List<T> getField(TKey<N, T> nttKey) { List<T> result = new ArrayList<T>(); if (fields.containsKey(nttKey)) { result.addAll(((ArrayList<T>) fields.get(nttKey))); } for (TKey<?, ?> qkey : qFields.keySet()) { if (qkey.equals(nttKey)) { - result.addAll((Collection<? extends T>) qFields.get(qkey).values()); + Collection<Object> values = qFields.get(qkey).values(); + for (Object object : values) { + result.add((T)object); + } } } return result; } /** * @param key * @param value */ @Override @SuppressWarnings("unchecked") public <N, T extends Serializable> void addQField(TKey<N, T> key, String qualifier, T value){ if (!qFields.containsKey(key)) { qFields.put(key, new HashMap<String, Object>()); } if (!qFields.get(key).containsKey(qualifier)) { qFields.get(key).put(qualifier, new ArrayList<T>()); } ((ArrayList<T>)qFields.get(key).get(qualifier)).add(value); } @Override public <N, T extends Serializable> List<T> getQField(TKey<N, T> nttKey, String qualifier) { return (ArrayList<T>)qFields.get(nttKey).get(qualifier); } }
true
true
public <N, T extends Serializable> List<T> getField(TKey<N, T> nttKey) { List<T> result = new ArrayList<T>(); if (fields.containsKey(nttKey)) { result.addAll(((ArrayList<T>) fields.get(nttKey))); } for (TKey<?, ?> qkey : qFields.keySet()) { if (qkey.equals(nttKey)) { result.addAll((Collection<? extends T>) qFields.get(qkey).values()); } } return result; }
public <N, T extends Serializable> List<T> getField(TKey<N, T> nttKey) { List<T> result = new ArrayList<T>(); if (fields.containsKey(nttKey)) { result.addAll(((ArrayList<T>) fields.get(nttKey))); } for (TKey<?, ?> qkey : qFields.keySet()) { if (qkey.equals(nttKey)) { Collection<Object> values = qFields.get(qkey).values(); for (Object object : values) { result.add((T)object); } } } return result; }
diff --git a/src/net/java/sip/communicator/impl/callhistory/CallHistoryServiceImpl.java b/src/net/java/sip/communicator/impl/callhistory/CallHistoryServiceImpl.java index e9e54f84f..54ef4b655 100644 --- a/src/net/java/sip/communicator/impl/callhistory/CallHistoryServiceImpl.java +++ b/src/net/java/sip/communicator/impl/callhistory/CallHistoryServiceImpl.java @@ -1,1207 +1,1215 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.callhistory; import java.io.*; import java.util.*; import org.osgi.framework.*; import net.java.sip.communicator.service.callhistory.*; import net.java.sip.communicator.service.callhistory.event.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.history.*; import net.java.sip.communicator.service.history.event.*; import net.java.sip.communicator.service.history.event.ProgressEvent; import net.java.sip.communicator.service.history.records.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; /** * The Call History Service stores info about the calls made. * Logs calls info for all protocol providers that support basic telephony * (i.e. those that implement OperationSetBasicTelephony). * * @author Damian Minkov * @author Lubomir Marinov */ public class CallHistoryServiceImpl implements CallHistoryService, CallListener, ServiceListener { /** * The logger for this class. */ private static final Logger logger = Logger.getLogger(CallHistoryServiceImpl.class); private static String[] STRUCTURE_NAMES = new String[] { "accountUID", "callStart", "callEnd", "dir", "callParticipantIDs", "callParticipantStart", "callParticipantEnd", "callParticipantStates", "callEndReason" }; private static HistoryRecordStructure recordStructure = new HistoryRecordStructure(STRUCTURE_NAMES); private static final String DELIM = ","; /** * The BundleContext that we got from the OSGI bus. */ private BundleContext bundleContext = null; private HistoryService historyService = null; private Object syncRoot_HistoryService = new Object(); private final Map<CallHistorySearchProgressListener, SearchProgressWrapper> progressListeners = new Hashtable<CallHistorySearchProgressListener, SearchProgressWrapper>(); private final List<CallRecordImpl> currentCallRecords = new Vector<CallRecordImpl>(); private final CallChangeListener historyCallChangeListener = new HistoryCallChangeListener(); private HistoryReader historyReader; /** * Returns the underlying history service. * @return the underlying history service */ public HistoryService getHistoryService() { return historyService; } /** * Returns all the calls made by all the contacts in the supplied * <tt>contact</tt> after the given date. * * @param contact MetaContact which contacts participate in * the returned calls * @param startDate Date the start date of the calls * @return the <tt>CallHistoryQuery</tt>, corresponding to this find * @throws RuntimeException */ public Collection<CallRecord> findByStartDate( MetaContact contact, Date startDate) throws RuntimeException { throw new UnsupportedOperationException("Not implemented yet!"); } /** * Returns all the calls made after the given date * * @param startDate Date the start date of the calls * @return the <tt>CallHistoryQuery</tt>, corresponding to this find * @throws RuntimeException */ public Collection<CallRecord> findByStartDate(Date startDate) { TreeSet<CallRecord> result = new TreeSet<CallRecord>(new CallRecordComparator()); try { // the default ones History history = this.getHistory(null, null); historyReader = history.getReader(); addHistorySearchProgressListeners(historyReader, 1); QueryResultSet<HistoryRecord> rs = historyReader.findByStartDate(startDate); while (rs.hasNext()) { HistoryRecord hr = rs.next(); result.add(convertHistoryRecordToCallRecord(hr)); } removeHistorySearchProgressListeners(historyReader); } catch (IOException ex) { logger.error("Could not read history", ex); } return result; } /** * Returns all the calls made by all the contacts * in the supplied metacontact before the given date * * @param contact MetaContact which contacts participate in * the returned calls * @param endDate Date the end date of the calls * @return Collection of CallRecords with CallPeerRecord * @throws RuntimeException */ public Collection<CallRecord> findByEndDate(MetaContact contact, Date endDate) throws RuntimeException { throw new UnsupportedOperationException("Not implemented yet!"); } /** * Returns all the calls made before the given date * * @param endDate Date the end date of the calls * @return Collection of CallRecords with CallPeerRecord * @throws RuntimeException */ public Collection<CallRecord> findByEndDate(Date endDate) throws RuntimeException { TreeSet<CallRecord> result = new TreeSet<CallRecord>(new CallRecordComparator()); try { // the default ones History history = this.getHistory(null, null); historyReader = history.getReader(); addHistorySearchProgressListeners(historyReader, 1); QueryResultSet<HistoryRecord> rs = historyReader.findByEndDate(endDate); while (rs.hasNext()) { HistoryRecord hr = rs.next(); result.add(convertHistoryRecordToCallRecord(hr)); } removeHistorySearchProgressListeners(historyReader); } catch (IOException ex) { logger.error("Could not read history", ex); } return result; } /** * Returns all the calls made by all the contacts * in the supplied metacontact between the given dates * * @param contact MetaContact * @param startDate Date the start date of the calls * @param endDate Date the end date of the conversations * @return Collection of CallRecords with CallPeerRecord * @throws RuntimeException */ public Collection<CallRecord> findByPeriod(MetaContact contact, Date startDate, Date endDate) throws RuntimeException { throw new UnsupportedOperationException("Not implemented yet!"); } /** * Returns all the calls made between the given dates * * @param startDate Date the start date of the calls * @param endDate Date the end date of the conversations * @return Collection of CallRecords with CallPeerRecord * @throws RuntimeException */ public Collection<CallRecord> findByPeriod(Date startDate, Date endDate) throws RuntimeException { TreeSet<CallRecord> result = new TreeSet<CallRecord>(new CallRecordComparator()); try { // the default ones History history = this.getHistory(null, null); historyReader = history.getReader(); addHistorySearchProgressListeners(historyReader, 1); QueryResultSet<HistoryRecord> rs = historyReader.findByPeriod(startDate, endDate); while (rs.hasNext()) { HistoryRecord hr = rs.next(); result.add(convertHistoryRecordToCallRecord(hr)); } removeHistorySearchProgressListeners(historyReader); } catch (IOException ex) { logger.error("Could not read history", ex); } return result; } /** * Returns the supplied number of calls by all the contacts * in the supplied metacontact * * @param contact MetaContact which contacts participate in * the returned calls * @param count calls count * @return Collection of CallRecords with CallPeerRecord * @throws RuntimeException */ public Collection<CallRecord> findLast(MetaContact contact, int count) throws RuntimeException { throw new UnsupportedOperationException("Not implemented yet!"); } /** * Returns the supplied number of calls made * * @param count calls count * @return Collection of CallRecords with CallPeerRecord * @throws RuntimeException */ public Collection<CallRecord> findLast(int count) throws RuntimeException { TreeSet<CallRecord> result = new TreeSet<CallRecord>(new CallRecordComparator()); try { // the default ones History history = this.getHistory(null, null); historyReader = history.getReader(); QueryResultSet<HistoryRecord> rs = historyReader.findLast(count); while (rs.hasNext()) { HistoryRecord hr = rs.next(); result.add(convertHistoryRecordToCallRecord(hr)); } } catch (IOException ex) { logger.error("Could not read history", ex); } return result; } /** * Find the calls made by the supplied peer address * @param address String the address of the peer * @param recordCount the number of records to return * @return Collection of CallRecords with CallPeerRecord * @throws RuntimeException */ public CallHistoryQuery findByPeer(String address, int recordCount) throws RuntimeException { CallHistoryQueryImpl callQuery = null; try { // the default ones History history = this.getHistory(null, null); InteractiveHistoryReader historyReader = history.getInteractiveReader(); HistoryQuery historyQuery = historyReader.findByKeyword( address, "callParticipantIDs", recordCount); callQuery = new CallHistoryQueryImpl(historyQuery); } catch (IOException ex) { logger.error("Could not read history", ex); } return callQuery; } /** * Returns the history by specified local and remote contact * if one of them is null the default is used * * @param localContact Contact * @param remoteContact Contact * @return History * @throws IOException */ private History getHistory(Contact localContact, Contact remoteContact) throws IOException { History retVal = null; String localId = localContact == null ? "default" : localContact .getAddress(); String remoteId = remoteContact == null ? "default" : remoteContact .getAddress(); HistoryID historyId = HistoryID.createFromRawID( new String[] { "callhistory", localId, remoteId }); if (this.historyService.isHistoryExisting(historyId)) { retVal = this.historyService.getHistory(historyId); retVal.setHistoryRecordsStructure(recordStructure); } else { retVal = this.historyService.createHistory(historyId, recordStructure); } return retVal; } /** * Used to convert HistoryRecord in CallReord and CallPeerRecord * which are returned by the finder methods * * @param hr HistoryRecord * @return Object CallRecord */ static CallRecord convertHistoryRecordToCallRecord(HistoryRecord hr) { CallRecordImpl result = new CallRecordImpl(); List<String> callPeerIDs = null; List<String> callPeerStart = null; List<String> callPeerEnd = null; List<CallPeerState> callPeerStates = null; // History structure // 0 - callStart // 1 - callEnd // 2 - dir // 3 - callParticipantIDs // 4 - callParticipantStart // 5 - callParticipantEnd for (int i = 0; i < hr.getPropertyNames().length; i++) { String propName = hr.getPropertyNames()[i]; String value = hr.getPropertyValues()[i]; if (propName.equals(STRUCTURE_NAMES[0])) result.setProtocolProvider(getProtocolProvider(value)); else if(propName.equals(STRUCTURE_NAMES[1])) result.setStartTime(new Date(Long.parseLong(value))); else if(propName.equals(STRUCTURE_NAMES[2])) result.setEndTime(new Date(Long.parseLong(value))); else if(propName.equals(STRUCTURE_NAMES[3])) result.setDirection(value); else if(propName.equals(STRUCTURE_NAMES[4])) callPeerIDs = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[5])) callPeerStart = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[6])) callPeerEnd = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[7])) callPeerStates = getStates(value); else if(propName.equals(STRUCTURE_NAMES[8])) result.setEndReason(Integer.parseInt(value)); } final int callPeerCount = callPeerIDs == null ? 0 : callPeerIDs.size(); for (int i = 0; i < callPeerCount; i++) { // As we iterate over the CallPeer IDs we could not be sure that // for some reason the start or end call list could result in // different size lists, so we check this first. Date callPeerStartValue = null; Date callPeerEndValue = null; if (i < callPeerStart.size()) { callPeerStartValue = new Date(Long.parseLong(callPeerStart.get(i))); } else { callPeerStartValue = result.getStartTime(); - if (logger.isTraceEnabled()) - logger.trace( + if (logger.isInfoEnabled()) + logger.info( "Call history start time list different from ids list: " + hr.toString()); } if (i < callPeerEnd.size()) { callPeerEndValue = new Date(Long.parseLong(callPeerEnd.get(i))); + if (logger.isInfoEnabled()) + logger.info( + "Call history end time list different from ids list: " + + hr.toString()); } else { callPeerEndValue = result.getEndTime(); } CallPeerRecordImpl cpr = new CallPeerRecordImpl(callPeerIDs.get(i), callPeerStartValue, callPeerEndValue); - // if there is no record about the states (backward compability) - if (callPeerStates != null) + // if there is no record about the states (backward compatibility) + if (callPeerStates != null && i < callPeerStates.size()) cpr.setState(callPeerStates.get(i)); + else if (logger.isInfoEnabled()) + logger.info( + "Call history state list different from ids list: " + + hr.toString()); result.getPeerRecords().add(cpr); } return result; } /** * Returns list of String items contained in the supplied string * separated by DELIM * @param str String * @return LinkedList */ private static List<String> getCSVs(String str) { List<String> result = new LinkedList<String>(); StringTokenizer toks = new StringTokenizer(str, DELIM); while(toks.hasMoreTokens()) { result.add(toks.nextToken()); } return result; } /** * Get the delimited strings and converts them to CallPeerState * * @param str String delimited string states * @return LinkedList the converted values list */ private static List<CallPeerState> getStates(String str) { List<CallPeerState> result = new LinkedList<CallPeerState>(); Collection<String> stateStrs = getCSVs(str); for (String item : stateStrs) { result.add(convertStateStringToState(item)); } return result; } /** * Converts the state string to state * @param state String the string * @return CallPeerState the state */ private static CallPeerState convertStateStringToState(String state) { if(state.equals(CallPeerState._CONNECTED)) return CallPeerState.CONNECTED; else if(state.equals(CallPeerState._BUSY)) return CallPeerState.BUSY; else if(state.equals(CallPeerState._FAILED)) return CallPeerState.FAILED; else if(state.equals(CallPeerState._DISCONNECTED)) return CallPeerState.DISCONNECTED; else if(state.equals(CallPeerState._ALERTING_REMOTE_SIDE)) return CallPeerState.ALERTING_REMOTE_SIDE; else if(state.equals(CallPeerState._CONNECTING)) return CallPeerState.CONNECTING; else if(state.equals(CallPeerState._ON_HOLD_LOCALLY)) return CallPeerState.ON_HOLD_LOCALLY; else if(state.equals(CallPeerState._ON_HOLD_MUTUALLY)) return CallPeerState.ON_HOLD_MUTUALLY; else if(state.equals(CallPeerState._ON_HOLD_REMOTELY)) return CallPeerState.ON_HOLD_REMOTELY; else if(state.equals(CallPeerState._INITIATING_CALL)) return CallPeerState.INITIATING_CALL; else if(state.equals(CallPeerState._INCOMING_CALL)) return CallPeerState.INCOMING_CALL; else return CallPeerState.UNKNOWN; } /** * starts the service. Check the current registerd protocol providers * which supports BasicTelephony and adds calls listener to them * * @param bc BundleContext */ public void start(BundleContext bc) { if (logger.isDebugEnabled()) logger.debug("Starting the call history implementation."); this.bundleContext = bc; // start listening for newly register or removed protocol providers bc.addServiceListener(this); ServiceReference[] protocolProviderRefs = null; try { protocolProviderRefs = bc.getServiceReferences( ProtocolProviderService.class.getName(), null); } catch (InvalidSyntaxException ex) { // this shouldn't happen since we're providing no parameter string // but let's log just in case. logger.error( "Error while retrieving service refs", ex); return; } // in case we found any if (protocolProviderRefs != null) { if (logger.isDebugEnabled()) logger.debug("Found " + protocolProviderRefs.length + " already installed providers."); for (int i = 0; i < protocolProviderRefs.length; i++) { ProtocolProviderService provider = (ProtocolProviderService) bc .getService(protocolProviderRefs[i]); this.handleProviderAdded(provider); } } } /** * stops the service. * * @param bc BundleContext */ public void stop(BundleContext bc) { bc.removeServiceListener(this); ServiceReference[] protocolProviderRefs = null; try { protocolProviderRefs = bc.getServiceReferences( ProtocolProviderService.class.getName(), null); } catch (InvalidSyntaxException ex) { // this shouldn't happen since we're providing no parameter string // but let's log just in case. logger.error("Error while retrieving service refs", ex); return; } // in case we found any if (protocolProviderRefs != null) { for (int i = 0; i < protocolProviderRefs.length; i++) { ProtocolProviderService provider = (ProtocolProviderService) bc .getService(protocolProviderRefs[i]); this.handleProviderRemoved(provider); } } } /** * Writes the given record to the history service * @param callRecord CallRecord * @param source Contact * @param destination Contact */ private void writeCall( CallRecordImpl callRecord, Contact source, Contact destination) { try { History history = this.getHistory(source, destination); HistoryWriter historyWriter = history.getWriter(); StringBuffer callPeerIDs = new StringBuffer(); StringBuffer callPeerStartTime = new StringBuffer(); StringBuffer callPeerEndTime = new StringBuffer(); StringBuffer callPeerStates = new StringBuffer(); for (CallPeerRecord item : callRecord .getPeerRecords()) { if (callPeerIDs.length() > 0) { callPeerIDs.append(DELIM); callPeerStartTime.append(DELIM); callPeerEndTime.append(DELIM); callPeerStates.append(DELIM); } callPeerIDs.append(item.getPeerAddress()); callPeerStartTime.append(String.valueOf(item .getStartTime().getTime())); callPeerEndTime.append(String.valueOf(item.getEndTime() .getTime())); callPeerStates.append(item.getState().getStateString()); } historyWriter.addRecord(new String[] { callRecord.getSourceCall().getProtocolProvider() .getAccountID().getAccountUniqueID(), String.valueOf(callRecord.getStartTime().getTime()), String.valueOf(callRecord.getEndTime().getTime()), callRecord.getDirection(), callPeerIDs.toString(), callPeerStartTime.toString(), callPeerEndTime.toString(), callPeerStates.toString(), String.valueOf(callRecord.getEndReason())}, new Date()); // this date is when the history // record is written } catch (IOException e) { logger.error("Could not add call to history", e); } } /** * Set the configuration service. * * @param historyService HistoryService * @throws IOException * @throws IllegalArgumentException */ public void setHistoryService(HistoryService historyService) throws IllegalArgumentException, IOException { synchronized (this.syncRoot_HistoryService) { this.historyService = historyService; if (logger.isDebugEnabled()) logger.debug("New history service registered."); } } /** * Remove a configuration service. * * @param hService HistoryService */ public void unsetHistoryService(HistoryService hService) { synchronized (this.syncRoot_HistoryService) { if (this.historyService == hService) { this.historyService = null; if (logger.isDebugEnabled()) logger.debug("History service unregistered."); } } } /** * When new protocol provider is registered we check * does it supports BasicTelephony and if so add a listener to it * * @param serviceEvent ServiceEvent */ public void serviceChanged(ServiceEvent serviceEvent) { Object sService = bundleContext.getService(serviceEvent.getServiceReference()); if (logger.isTraceEnabled()) logger.trace("Received a service event for: " + sService.getClass().getName()); // we don't care if the source service is not a protocol provider if (! (sService instanceof ProtocolProviderService)) { return; } if (logger.isDebugEnabled()) logger.debug("Service is a protocol provider."); if (serviceEvent.getType() == ServiceEvent.REGISTERED) { if (logger.isDebugEnabled()) logger.debug("Handling registration of a new Protocol Provider."); this.handleProviderAdded((ProtocolProviderService)sService); } else if (serviceEvent.getType() == ServiceEvent.UNREGISTERING) { this.handleProviderRemoved( (ProtocolProviderService) sService); } } /** * Used to attach the Call History Service to existing or * just registered protocol provider. Checks if the provider has * implementation of OperationSetBasicTelephony * * @param provider ProtocolProviderService */ private void handleProviderAdded(ProtocolProviderService provider) { if (logger.isDebugEnabled()) logger.debug("Adding protocol provider " + provider.getProtocolName()); // check whether the provider has a basic telephony operation set OperationSetBasicTelephony<?> opSetTelephony = provider.getOperationSet(OperationSetBasicTelephony.class); if (opSetTelephony != null) { opSetTelephony.addCallListener(this); } else { if (logger.isTraceEnabled()) logger.trace("Service did not have a basic telephony op. set."); } } /** * Removes the specified provider from the list of currently known providers * and ignores all the calls made by it * * @param provider the ProtocolProviderService that has been unregistered. */ private void handleProviderRemoved(ProtocolProviderService provider) { OperationSetBasicTelephony<?> opSetTelephony = provider.getOperationSet(OperationSetBasicTelephony.class); if (opSetTelephony != null) { opSetTelephony.removeCallListener(this); } } /** * Adding progress listener for monitoring progress of search process * * @param listener HistorySearchProgressListener */ public void addSearchProgressListener(CallHistorySearchProgressListener listener) { synchronized (progressListeners) { progressListeners .put(listener, new SearchProgressWrapper(listener)); } } /** * Removing progress listener * * @param listener HistorySearchProgressListener */ public void removeSearchProgressListener( CallHistorySearchProgressListener listener) { synchronized(progressListeners){ progressListeners.remove(listener); } } /** * Add the registered CallHistorySearchProgressListeners to the given * HistoryReader * * @param reader HistoryReader * @param countContacts number of contacts will search */ private void addHistorySearchProgressListeners(HistoryReader reader, int countContacts) { synchronized (progressListeners) { for (SearchProgressWrapper l : progressListeners.values()) { l.contactCount = countContacts; reader.addSearchProgressListener(l); } } } /** * Removes the registered CallHistorySearchProgressListeners from the given * HistoryReader * * @param reader HistoryReader */ private void removeHistorySearchProgressListeners(HistoryReader reader) { synchronized (progressListeners) { for (SearchProgressWrapper l : progressListeners.values()) { l.clear(); reader.removeSearchProgressListener(l); } } } /** * CallListener implementation for incoming calls * @param event CallEvent */ public void incomingCallReceived(CallEvent event) { handleNewCall(event.getSourceCall(), CallRecord.IN); } /** * CallListener implementation for outgoing calls * @param event CallEvent */ public void outgoingCallCreated(CallEvent event) { handleNewCall(event.getSourceCall(), CallRecord.OUT); } /** * CallListener implementation for call endings * @param event CallEvent */ public void callEnded(CallEvent event) { // We store the call in the callStateChangeEvent where we // have more information on the previous state of the call. } /** * Adding a record for joining peer * @param callPeer CallPeer */ private void handlePeerAdded(CallPeer callPeer) { CallRecord callRecord = findCallRecord(callPeer.getCall()); // no such call if(callRecord == null) return; callPeer.addCallPeerListener(new CallPeerAdapter() { @Override public void peerStateChanged(CallPeerChangeEvent evt) { if(evt.getNewValue().equals(CallPeerState.DISCONNECTED)) return; else { CallPeerRecordImpl peerRecord = findPeerRecord(evt.getSourceCallPeer()); if(peerRecord == null) return; CallPeerState newState = (CallPeerState) evt.getNewValue(); if (newState.equals(CallPeerState.CONNECTED) && !CallPeerState.isOnHold((CallPeerState) evt.getOldValue())) peerRecord.setStartTime(new Date()); peerRecord.setState(newState); //Disconnected / Busy //Disconnected / Connecting - fail //Disconnected / Connected } } }); Date startDate = new Date(); CallPeerRecordImpl newRec = new CallPeerRecordImpl( callPeer.getAddress(), startDate, startDate); callRecord.getPeerRecords().add(newRec); } /** * Adding a record for removing peer from call * @param callPeer CallPeer * @param srcCall Call */ private void handlePeerRemoved( CallPeer callPeer, Call srcCall) { CallRecord callRecord = findCallRecord(srcCall); String pAddress = callPeer.getAddress(); if (callRecord == null) return; CallPeerRecordImpl cpRecord = (CallPeerRecordImpl)callRecord.findPeerRecord(pAddress); // no such peer if(cpRecord == null) return; if(!callPeer.getState().equals(CallPeerState.DISCONNECTED)) cpRecord.setState(callPeer.getState()); CallPeerState cpRecordState = cpRecord.getState(); if (cpRecordState.equals(CallPeerState.CONNECTED) || CallPeerState.isOnHold(cpRecordState)) { cpRecord.setEndTime(new Date()); } } /** * Finding a CallRecord for the given call * * @param call Call * @return CallRecord */ private CallRecordImpl findCallRecord(Call call) { for (CallRecordImpl item : currentCallRecords) { if (item.getSourceCall().equals(call)) return item; } return null; } /** * Returns the peer record for the given peer * @param callPeer CallPeer peer * @return CallPeerRecordImpl the corresponding record */ private CallPeerRecordImpl findPeerRecord( CallPeer callPeer) { CallRecord record = findCallRecord(callPeer.getCall()); if (record == null) return null; return (CallPeerRecordImpl) record.findPeerRecord( callPeer.getAddress()); } /** * Adding a record for a new call * @param sourceCall Call * @param direction String */ private void handleNewCall(Call sourceCall, String direction) { // if call exist. its not new for (CallRecordImpl currentCallRecord : currentCallRecords) { if (currentCallRecord.getSourceCall().equals(sourceCall)) return; } CallRecordImpl newRecord = new CallRecordImpl( direction, new Date(), null); newRecord.setSourceCall(sourceCall); sourceCall.addCallChangeListener(historyCallChangeListener); currentCallRecords.add(newRecord); // if has already perticipants Dispatch them Iterator<? extends CallPeer> iter = sourceCall.getCallPeers(); while (iter.hasNext()) { handlePeerAdded(iter.next()); } } /** * A wrapper around HistorySearchProgressListener * that fires events for CallHistorySearchProgressListener */ private class SearchProgressWrapper implements HistorySearchProgressListener { private CallHistorySearchProgressListener listener = null; int contactCount = 0; int currentContactCount = 0; int currentProgress = 0; int lastHistoryProgress = 0; SearchProgressWrapper(CallHistorySearchProgressListener listener) { this.listener = listener; } public void progressChanged(ProgressEvent evt) { int progress = getProgressMapping(evt.getProgress()); listener.progressChanged( new net.java.sip.communicator.service.callhistory.event. ProgressEvent(CallHistoryServiceImpl.this, evt, progress)); } /** * Calculates the progress according the count of the contacts * we will search * @param historyProgress int * @return int */ private int getProgressMapping(int historyProgress) { currentProgress += (historyProgress - lastHistoryProgress)/contactCount; if(historyProgress == HistorySearchProgressListener.PROGRESS_MAXIMUM_VALUE) { currentContactCount++; lastHistoryProgress = 0; // this is the last one and the last event fire the max // there will be looses in currentProgress due to the devision if(currentContactCount == contactCount) currentProgress = CallHistorySearchProgressListener.PROGRESS_MAXIMUM_VALUE; } else lastHistoryProgress = historyProgress; return currentProgress; } /** * clear the values */ void clear() { contactCount = 0; currentProgress = 0; lastHistoryProgress = 0; currentContactCount = 0; } } /** * Used to compare CallRecords and to be ordered in TreeSet according their * timestamp */ private static class CallRecordComparator implements Comparator<CallRecord> { public int compare(CallRecord o1, CallRecord o2) { return o2.getStartTime().compareTo(o1.getStartTime()); } } /** * Receive events for adding or removing peers from a call */ private class HistoryCallChangeListener implements CallChangeListener { /** * Indicates that a new call peer has joined the source call. * * @param evt the <tt>CallPeerEvent</tt> containing the source call * and call peer. */ public void callPeerAdded(CallPeerEvent evt) { handlePeerAdded(evt.getSourceCallPeer()); } /** * Indicates that a call peer has left the source call. * * @param evt the <tt>CallPeerEvent</tt> containing the source call * and call peer. */ public void callPeerRemoved(CallPeerEvent evt) { handlePeerRemoved(evt.getSourceCallPeer(), evt.getSourceCall()); } /** * A dummy implementation of this listener's callStateChanged() method. * * @param evt the <tt>CallChangeEvent</tt> instance containing the source * calls and its old and new state. */ public void callStateChanged(CallChangeEvent evt) { CallRecordImpl callRecord = findCallRecord(evt.getSourceCall()); // no such call if (callRecord == null) return; if (evt.getNewValue().equals(CallState.CALL_ENDED)) { if(evt.getOldValue().equals(CallState.CALL_INITIALIZATION)) { callRecord.setEndTime(callRecord.getStartTime()); // if call was answered elsewhere, add its reason // so we can distinguish it from missed if(evt.getCause() != null && evt.getCause().getReasonCode() == CallPeerChangeEvent.NORMAL_CALL_CLEARING) { callRecord.setEndReason(evt.getCause().getReasonCode()); } } else callRecord.setEndTime(new Date()); writeCall(callRecord, null, null); currentCallRecords.remove(callRecord); } } } /** * Returns the <tt>ProtocolProviderService</tt> corresponding to the given * account identifier. * @param accountUID the identifier of the account. * @return the <tt>ProtocolProviderService</tt> corresponding to the given * account identifier */ private static ProtocolProviderService getProtocolProvider(String accountUID) { for (ProtocolProviderFactory providerFactory : CallHistoryActivator.getProtocolProviderFactories().values()) { ServiceReference serRef; for (AccountID accountID : providerFactory.getRegisteredAccounts()) { if (accountID.getAccountUniqueID().equals(accountUID)) { serRef = providerFactory.getProviderForAccount(accountID); return (ProtocolProviderService) CallHistoryActivator .bundleContext.getService(serRef); } } } return null; } }
false
true
static CallRecord convertHistoryRecordToCallRecord(HistoryRecord hr) { CallRecordImpl result = new CallRecordImpl(); List<String> callPeerIDs = null; List<String> callPeerStart = null; List<String> callPeerEnd = null; List<CallPeerState> callPeerStates = null; // History structure // 0 - callStart // 1 - callEnd // 2 - dir // 3 - callParticipantIDs // 4 - callParticipantStart // 5 - callParticipantEnd for (int i = 0; i < hr.getPropertyNames().length; i++) { String propName = hr.getPropertyNames()[i]; String value = hr.getPropertyValues()[i]; if (propName.equals(STRUCTURE_NAMES[0])) result.setProtocolProvider(getProtocolProvider(value)); else if(propName.equals(STRUCTURE_NAMES[1])) result.setStartTime(new Date(Long.parseLong(value))); else if(propName.equals(STRUCTURE_NAMES[2])) result.setEndTime(new Date(Long.parseLong(value))); else if(propName.equals(STRUCTURE_NAMES[3])) result.setDirection(value); else if(propName.equals(STRUCTURE_NAMES[4])) callPeerIDs = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[5])) callPeerStart = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[6])) callPeerEnd = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[7])) callPeerStates = getStates(value); else if(propName.equals(STRUCTURE_NAMES[8])) result.setEndReason(Integer.parseInt(value)); } final int callPeerCount = callPeerIDs == null ? 0 : callPeerIDs.size(); for (int i = 0; i < callPeerCount; i++) { // As we iterate over the CallPeer IDs we could not be sure that // for some reason the start or end call list could result in // different size lists, so we check this first. Date callPeerStartValue = null; Date callPeerEndValue = null; if (i < callPeerStart.size()) { callPeerStartValue = new Date(Long.parseLong(callPeerStart.get(i))); } else { callPeerStartValue = result.getStartTime(); if (logger.isTraceEnabled()) logger.trace( "Call history start time list different from ids list: " + hr.toString()); } if (i < callPeerEnd.size()) { callPeerEndValue = new Date(Long.parseLong(callPeerEnd.get(i))); } else { callPeerEndValue = result.getEndTime(); } CallPeerRecordImpl cpr = new CallPeerRecordImpl(callPeerIDs.get(i), callPeerStartValue, callPeerEndValue); // if there is no record about the states (backward compability) if (callPeerStates != null) cpr.setState(callPeerStates.get(i)); result.getPeerRecords().add(cpr); } return result; }
static CallRecord convertHistoryRecordToCallRecord(HistoryRecord hr) { CallRecordImpl result = new CallRecordImpl(); List<String> callPeerIDs = null; List<String> callPeerStart = null; List<String> callPeerEnd = null; List<CallPeerState> callPeerStates = null; // History structure // 0 - callStart // 1 - callEnd // 2 - dir // 3 - callParticipantIDs // 4 - callParticipantStart // 5 - callParticipantEnd for (int i = 0; i < hr.getPropertyNames().length; i++) { String propName = hr.getPropertyNames()[i]; String value = hr.getPropertyValues()[i]; if (propName.equals(STRUCTURE_NAMES[0])) result.setProtocolProvider(getProtocolProvider(value)); else if(propName.equals(STRUCTURE_NAMES[1])) result.setStartTime(new Date(Long.parseLong(value))); else if(propName.equals(STRUCTURE_NAMES[2])) result.setEndTime(new Date(Long.parseLong(value))); else if(propName.equals(STRUCTURE_NAMES[3])) result.setDirection(value); else if(propName.equals(STRUCTURE_NAMES[4])) callPeerIDs = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[5])) callPeerStart = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[6])) callPeerEnd = getCSVs(value); else if(propName.equals(STRUCTURE_NAMES[7])) callPeerStates = getStates(value); else if(propName.equals(STRUCTURE_NAMES[8])) result.setEndReason(Integer.parseInt(value)); } final int callPeerCount = callPeerIDs == null ? 0 : callPeerIDs.size(); for (int i = 0; i < callPeerCount; i++) { // As we iterate over the CallPeer IDs we could not be sure that // for some reason the start or end call list could result in // different size lists, so we check this first. Date callPeerStartValue = null; Date callPeerEndValue = null; if (i < callPeerStart.size()) { callPeerStartValue = new Date(Long.parseLong(callPeerStart.get(i))); } else { callPeerStartValue = result.getStartTime(); if (logger.isInfoEnabled()) logger.info( "Call history start time list different from ids list: " + hr.toString()); } if (i < callPeerEnd.size()) { callPeerEndValue = new Date(Long.parseLong(callPeerEnd.get(i))); if (logger.isInfoEnabled()) logger.info( "Call history end time list different from ids list: " + hr.toString()); } else { callPeerEndValue = result.getEndTime(); } CallPeerRecordImpl cpr = new CallPeerRecordImpl(callPeerIDs.get(i), callPeerStartValue, callPeerEndValue); // if there is no record about the states (backward compatibility) if (callPeerStates != null && i < callPeerStates.size()) cpr.setState(callPeerStates.get(i)); else if (logger.isInfoEnabled()) logger.info( "Call history state list different from ids list: " + hr.toString()); result.getPeerRecords().add(cpr); } return result; }
diff --git a/components/bio-formats/src/loci/formats/in/SlidebookReader.java b/components/bio-formats/src/loci/formats/in/SlidebookReader.java index 71176e529..506f854a7 100644 --- a/components/bio-formats/src/loci/formats/in/SlidebookReader.java +++ b/components/bio-formats/src/loci/formats/in/SlidebookReader.java @@ -1,494 +1,504 @@ // // SlidebookReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.*; import java.util.Vector; import loci.common.*; import loci.formats.*; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; /** * SlidebookReader is the file format reader for 3I Slidebook files. * The strategies employed by this reader are highly suboptimal, as we * have very little information on the Slidebook format. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/SlidebookReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/SlidebookReader.java">SVN</a></dd></dl> * * @author Melissa Linkert linkert at wisc.edu */ public class SlidebookReader extends FormatReader { // -- Fields -- private Vector metadataOffsets; private Vector pixelOffsets; private Vector pixelLengths; // -- Constructor -- /** Constructs a new Slidebook reader. */ public SlidebookReader() { super("Olympus Slidebook", "sld"); blockCheckLen = 8; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessStream) */ public boolean isThisType(RandomAccessStream stream) throws IOException { if (!FormatTools.validStream(stream, blockCheckLen, false)) return false; return stream.readLong() == 0x6c000001494900L; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); FormatTools.checkPlaneNumber(this, no); FormatTools.checkBufferSize(this, buf.length, w, h); int plane = getSizeX() * getSizeY() * 2; long offset = ((Long) pixelOffsets.get(series)).longValue() + plane * no; in.seek(offset); readPlane(in, x, y, w, h, buf); return buf; } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); metadataOffsets = pixelOffsets = pixelLengths = null; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (debug) debug("SlidebookReader.initFile(" + id + ")"); super.initFile(id); in = new RandomAccessStream(id); status("Finding offsets to pixel data"); // Slidebook files appear to be comprised of four types of blocks: // variable length pixel data blocks, 512 byte metadata blocks, // 128 byte metadata blocks, and variable length metadata blocks. // // Fixed-length metadata blocks begin with a 2 byte identifier, // e.g. 'i' or 'h'. // Following this are two unknown bytes (usually 256), then a 2 byte // endianness identifier - II or MM, for little or big endian, respectively. // Presumably these blocks contain useful information, but for the most // part we aren't sure what it is or how to extract it. // // Variable length metadata blocks begin with 0xffff and are // (as far as I know) always between two fixed-length metadata blocks. // These appear to be a relatively new addition to the format - they are // only present in files received on/after March 30, 2008. // // Each pixel data block corresponds to one series. // The first 'i' metadata block after each pixel data block contains // the width and height of the planes in that block - this can (and does) // vary between blocks. // // Z, C, and T sizes are computed heuristically based on the number of // metadata blocks of a specific type. in.skipBytes(4); core[0].littleEndian = in.read() == 0x49; in.order(isLittleEndian()); metadataOffsets = new Vector(); pixelOffsets = new Vector(); pixelLengths = new Vector(); in.seek(0); // gather offsets to metadata and pixel data blocks while (in.getFilePointer() < in.length() - 8) { in.skipBytes(4); int checkOne = in.read(); int checkTwo = in.read(); if ((checkOne == 'I' && checkTwo == 'I') || (checkOne == 'M' && checkTwo == 'M')) { metadataOffsets.add(new Long(in.getFilePointer() - 6)); in.skipBytes(in.readShort() - 8); } else if (checkOne == -1 && checkTwo == -1) { boolean foundBlock = false; byte[] block = new byte[8192]; in.read(block); while (!foundBlock) { for (int i=0; i<block.length-2; i++) { if ((block[i] == 'M' && block[i + 1] == 'M') || (block[i] == 'I' && block[i + 1] == 'I')) { foundBlock = true; in.seek(in.getFilePointer() - block.length + i - 2); metadataOffsets.add(new Long(in.getFilePointer() - 2)); in.skipBytes(in.readShort() - 5); break; } } if (!foundBlock) { block[0] = block[block.length - 2]; block[1] = block[block.length - 1]; in.read(block, 2, block.length - 2); } } } else { String s = null; long fp = in.getFilePointer() - 6; in.seek(fp); int len = in.read(); if (len > 0 && len <= 32) { s = in.readString(len); } if (s != null && s.indexOf("Annotation") != -1) { if (s.equals("CTimelapseAnnotation")) { in.skipBytes(41); if (in.read() == 0) in.skipBytes(10); else in.seek(in.getFilePointer() - 1); } else if (s.equals("CIntensityBarAnnotation")) { in.skipBytes(56); int n = in.read(); while (n == 0 || n < 6 || n > 0x80) n = in.read(); in.seek(in.getFilePointer() - 1); } else if (s.equals("CCubeAnnotation")) { in.skipBytes(66); int n = in.read(); if (n != 0) in.seek(in.getFilePointer() - 1); } else if (s.equals("CScaleBarAnnotation")) { in.skipBytes(38); int extra = in.read(); if (extra <= 16) in.skipBytes(3 + extra); else in.skipBytes(2); } } else if (s != null && s.indexOf("Decon") != -1) { in.seek(fp); while (in.read() != ']'); } else { if ((fp % 2) == 1) fp -= 2; in.seek(fp); pixelOffsets.add(new Long(fp)); try { byte[] buf = new byte[8192]; boolean found = false; int n = in.read(buf); while (!found && in.getFilePointer() < in.length()) { for (int i=0; i<buf.length-6; i++) { if ((buf[i] == 'h' && buf[i+4] == 'I' && buf[i+5] == 'I') || (buf[i+1] == 'h' && buf[i+4] == 'M' && buf[i+5] == 'M')) { found = true; in.seek(in.getFilePointer() - n + i - 20); break; } } if (!found) { byte[] tmp = buf; buf = new byte[8192]; System.arraycopy(tmp, tmp.length - 20, buf, 0, 20); n = in.read(buf, 20, buf.length - 20); } } if (in.getFilePointer() <= in.length()) { pixelLengths.add(new Long(in.getFilePointer() - fp)); } else pixelOffsets.remove(pixelOffsets.size() - 1); } catch (EOFException e) { pixelOffsets.remove(pixelOffsets.size() - 1); } } } } for (int i=0; i<pixelOffsets.size(); i++) { long length = ((Long) pixelLengths.get(i)).longValue(); long offset = ((Long) pixelOffsets.get(i)).longValue(); in.seek(offset); byte checkByte = in.readByte(); if (length + offset >= in.length()) { pixelOffsets.remove(i); pixelLengths.remove(i); i--; } else if (checkByte == 'l') { long lengthSum = ((Long) pixelLengths.get(0)).longValue(); while (pixelLengths.size() > 1) { int size = pixelLengths.size() - 1; lengthSum += ((Long) pixelLengths.get(size)).longValue(); pixelLengths.remove(size); pixelOffsets.remove(size); } for (int q=0; q<metadataOffsets.size(); q++) { long mOffset = ((Long) metadataOffsets.get(q)).longValue(); if (mOffset > lengthSum) { lengthSum = mOffset - offset; break; } } pixelLengths.setElementAt(new Long(lengthSum), 0); break; } } if (pixelOffsets.size() > 1) { if (pixelOffsets.size() > 2) { int size = pixelOffsets.size(); long last = ((Long) pixelOffsets.get(size - 1)).longValue(); long nextToLast = ((Long) pixelOffsets.get(size - 2)).longValue(); long diff = in.length() - last; if (last - nextToLast > 2*diff && diff < (256 * 256 * 2)) { pixelOffsets.removeElementAt(size - 1); } } boolean little = isLittleEndian(); core = new CoreMetadata[pixelOffsets.size()]; for (int i=0; i<getSeriesCount(); i++) { core[i] = new CoreMetadata(); core[i].littleEndian = little; } } status("Determining dimensions"); // determine total number of pixel bytes float pixelSize = 1f; String objective = null; Vector pixelSizeZ = new Vector(); long pixelBytes = 0; for (int i=0; i<pixelLengths.size(); i++) { pixelBytes += ((Long) pixelLengths.get(i)).longValue(); } String[] imageNames = new String[getSeriesCount()]; Vector channelNames = new Vector(); int nextName = 0; // try to find the width and height int iCount = 0; int hCount = 0; int uCount = 0; int prevSeries = -1; int prevSeriesU = -1; int nextChannel = 0; for (int i=0; i<metadataOffsets.size(); i++) { long off = ((Long) metadataOffsets.get(i)).longValue(); in.seek(off); long next = i == metadataOffsets.size() - 1 ? in.length() : ((Long) metadataOffsets.get(i + 1)).longValue(); int totalBlocks = (int) ((next - off) / 128); for (int q=0; q<totalBlocks; q++) { if (withinPixels(off + q * 128)) break; in.seek(off + q * 128); char n = (char) in.readShort(); if (n == 'i') { iCount++; in.skipBytes(94); pixelSizeZ.add(new Float(in.readFloat())); in.seek(in.getFilePointer() - 20); for (int j=0; j<pixelOffsets.size(); j++) { long end = j == pixelOffsets.size() - 1 ? in.length() : ((Long) pixelOffsets.get(j + 1)).longValue(); if (in.getFilePointer() < end) { if (core[j].sizeX == 0) { core[j].sizeX = in.readShort(); core[j].sizeY = in.readShort(); int checkX = in.readShort(); int checkY = in.readShort(); int div = in.readShort(); - core[j].sizeX /= div; + core[j].sizeX /= (div == 0 ? 1 : div); div = in.readShort(); - core[j].sizeY /= div; + core[j].sizeY /= (div == 0 ? 1 : div); } if (prevSeries != j) { iCount = 1; } prevSeries = j; core[j].sizeC = iCount; break; } } } else if (n == 'u') { uCount++; for (int j=0; j<pixelOffsets.size(); j++) { long end = j == pixelOffsets.size() - 1 ? in.length() : ((Long) pixelOffsets.get(j + 1)).longValue(); if (in.getFilePointer() < end) { if (prevSeriesU != j) { uCount = 1; } prevSeriesU = j; core[j].sizeZ = uCount; break; } } } else if (n == 'h') hCount++; else if (n == 'j') { in.skipBytes(2); String check = in.readString(2); if (check.equals("II") || check.equals("MM")) { // this block should contain an image name in.skipBytes(10); if (nextName < imageNames.length) { imageNames[nextName++] = in.readCString().trim(); } + if (core[nextName - 1].sizeX == 0 || core[nextName - 1].sizeY == 0) + { + in.skipBytes(123); + core[nextName - 1].sizeX = in.readInt(); + core[nextName - 1].sizeY = in.readInt(); + int div = in.readInt(); + core[nextName - 1].sizeX /= (div == 0 ? 1 : div); + div = in.readInt(); + core[nextName - 1].sizeY /= (div == 0 ? 1 : div); + } } } else if (n == 'm') { // this block should contain a channel name if (in.getFilePointer() > ((Long) pixelOffsets.get(0)).longValue()) { in.skipBytes(14); channelNames.add(in.readCString().trim()); } } else if (n == 'd') { // objective info and pixel size X/Y in.skipBytes(6); objective = in.readCString(); in.skipBytes(126); pixelSize = in.readFloat(); } } } for (int i=0; i<getSeriesCount(); i++) { setSeries(i); long pixels = ((Long) pixelLengths.get(i)).longValue() / 2; boolean x = true; while (getSizeX() * getSizeY() * getSizeC() * getSizeZ() > pixels) { if (x) core[i].sizeX /= 2; else core[i].sizeY /= 2; x = !x; } if (getSizeZ() == 0) core[i].sizeZ = 1; core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * getSizeZ() * getSizeC())); if (getSizeT() == 0) core[i].sizeT = 1; core[i].imageCount = getSizeZ() * getSizeC() * getSizeT(); core[i].pixelType = FormatTools.UINT16; core[i].dimensionOrder = "XYZTC"; core[i].indexed = false; core[i].falseColor = false; core[i].metadataComplete = true; } setSeries(0); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this); // link Instrument and Image store.setInstrumentID("Instrument:0", 0); store.setImageInstrumentRef("Instrument:0", 0); int index = 0; // populate Objective data store.setObjectiveModel(objective, 0, 0); // link Objective to Image store.setObjectiveID("Objective:0", 0, 0); store.setObjectiveSettingsObjective("Objective:0", 0); // populate Image data for (int i=0; i<getSeriesCount(); i++) { store.setImageName(imageNames[i], i); MetadataTools.setDefaultCreationDate(store, id, i); } // populate Dimensions data for (int i=0; i<getSeriesCount(); i++) { store.setDimensionsPhysicalSizeX(new Float(pixelSize), i, 0); store.setDimensionsPhysicalSizeY(new Float(pixelSize), i, 0); int idx = 0; for (int q=0; q<i; q++) { idx += core[q].sizeC; } if (idx < pixelSizeZ.size()) { store.setDimensionsPhysicalSizeZ((Float) pixelSizeZ.get(idx), i, 0); } } // populate LogicalChannel data for (int i=0; i<getSeriesCount(); i++) { for (int c=0; c<core[i].sizeC; c++) { if (index < channelNames.size()) { store.setLogicalChannelName((String) channelNames.get(index++), i, c); addMeta(imageNames[i] + " channel " + c, channelNames.get(index - 1)); } } } } // -- Helper methods -- private boolean withinPixels(long offset) { for (int i=0; i<pixelOffsets.size(); i++) { long pixelOffset = ((Long) pixelOffsets.get(i)).longValue(); long pixelLength = ((Long) pixelLengths.get(i)).longValue(); if (offset >= pixelOffset && offset < (pixelOffset + pixelLength)) { return true; } } return false; } }
false
true
protected void initFile(String id) throws FormatException, IOException { if (debug) debug("SlidebookReader.initFile(" + id + ")"); super.initFile(id); in = new RandomAccessStream(id); status("Finding offsets to pixel data"); // Slidebook files appear to be comprised of four types of blocks: // variable length pixel data blocks, 512 byte metadata blocks, // 128 byte metadata blocks, and variable length metadata blocks. // // Fixed-length metadata blocks begin with a 2 byte identifier, // e.g. 'i' or 'h'. // Following this are two unknown bytes (usually 256), then a 2 byte // endianness identifier - II or MM, for little or big endian, respectively. // Presumably these blocks contain useful information, but for the most // part we aren't sure what it is or how to extract it. // // Variable length metadata blocks begin with 0xffff and are // (as far as I know) always between two fixed-length metadata blocks. // These appear to be a relatively new addition to the format - they are // only present in files received on/after March 30, 2008. // // Each pixel data block corresponds to one series. // The first 'i' metadata block after each pixel data block contains // the width and height of the planes in that block - this can (and does) // vary between blocks. // // Z, C, and T sizes are computed heuristically based on the number of // metadata blocks of a specific type. in.skipBytes(4); core[0].littleEndian = in.read() == 0x49; in.order(isLittleEndian()); metadataOffsets = new Vector(); pixelOffsets = new Vector(); pixelLengths = new Vector(); in.seek(0); // gather offsets to metadata and pixel data blocks while (in.getFilePointer() < in.length() - 8) { in.skipBytes(4); int checkOne = in.read(); int checkTwo = in.read(); if ((checkOne == 'I' && checkTwo == 'I') || (checkOne == 'M' && checkTwo == 'M')) { metadataOffsets.add(new Long(in.getFilePointer() - 6)); in.skipBytes(in.readShort() - 8); } else if (checkOne == -1 && checkTwo == -1) { boolean foundBlock = false; byte[] block = new byte[8192]; in.read(block); while (!foundBlock) { for (int i=0; i<block.length-2; i++) { if ((block[i] == 'M' && block[i + 1] == 'M') || (block[i] == 'I' && block[i + 1] == 'I')) { foundBlock = true; in.seek(in.getFilePointer() - block.length + i - 2); metadataOffsets.add(new Long(in.getFilePointer() - 2)); in.skipBytes(in.readShort() - 5); break; } } if (!foundBlock) { block[0] = block[block.length - 2]; block[1] = block[block.length - 1]; in.read(block, 2, block.length - 2); } } } else { String s = null; long fp = in.getFilePointer() - 6; in.seek(fp); int len = in.read(); if (len > 0 && len <= 32) { s = in.readString(len); } if (s != null && s.indexOf("Annotation") != -1) { if (s.equals("CTimelapseAnnotation")) { in.skipBytes(41); if (in.read() == 0) in.skipBytes(10); else in.seek(in.getFilePointer() - 1); } else if (s.equals("CIntensityBarAnnotation")) { in.skipBytes(56); int n = in.read(); while (n == 0 || n < 6 || n > 0x80) n = in.read(); in.seek(in.getFilePointer() - 1); } else if (s.equals("CCubeAnnotation")) { in.skipBytes(66); int n = in.read(); if (n != 0) in.seek(in.getFilePointer() - 1); } else if (s.equals("CScaleBarAnnotation")) { in.skipBytes(38); int extra = in.read(); if (extra <= 16) in.skipBytes(3 + extra); else in.skipBytes(2); } } else if (s != null && s.indexOf("Decon") != -1) { in.seek(fp); while (in.read() != ']'); } else { if ((fp % 2) == 1) fp -= 2; in.seek(fp); pixelOffsets.add(new Long(fp)); try { byte[] buf = new byte[8192]; boolean found = false; int n = in.read(buf); while (!found && in.getFilePointer() < in.length()) { for (int i=0; i<buf.length-6; i++) { if ((buf[i] == 'h' && buf[i+4] == 'I' && buf[i+5] == 'I') || (buf[i+1] == 'h' && buf[i+4] == 'M' && buf[i+5] == 'M')) { found = true; in.seek(in.getFilePointer() - n + i - 20); break; } } if (!found) { byte[] tmp = buf; buf = new byte[8192]; System.arraycopy(tmp, tmp.length - 20, buf, 0, 20); n = in.read(buf, 20, buf.length - 20); } } if (in.getFilePointer() <= in.length()) { pixelLengths.add(new Long(in.getFilePointer() - fp)); } else pixelOffsets.remove(pixelOffsets.size() - 1); } catch (EOFException e) { pixelOffsets.remove(pixelOffsets.size() - 1); } } } } for (int i=0; i<pixelOffsets.size(); i++) { long length = ((Long) pixelLengths.get(i)).longValue(); long offset = ((Long) pixelOffsets.get(i)).longValue(); in.seek(offset); byte checkByte = in.readByte(); if (length + offset >= in.length()) { pixelOffsets.remove(i); pixelLengths.remove(i); i--; } else if (checkByte == 'l') { long lengthSum = ((Long) pixelLengths.get(0)).longValue(); while (pixelLengths.size() > 1) { int size = pixelLengths.size() - 1; lengthSum += ((Long) pixelLengths.get(size)).longValue(); pixelLengths.remove(size); pixelOffsets.remove(size); } for (int q=0; q<metadataOffsets.size(); q++) { long mOffset = ((Long) metadataOffsets.get(q)).longValue(); if (mOffset > lengthSum) { lengthSum = mOffset - offset; break; } } pixelLengths.setElementAt(new Long(lengthSum), 0); break; } } if (pixelOffsets.size() > 1) { if (pixelOffsets.size() > 2) { int size = pixelOffsets.size(); long last = ((Long) pixelOffsets.get(size - 1)).longValue(); long nextToLast = ((Long) pixelOffsets.get(size - 2)).longValue(); long diff = in.length() - last; if (last - nextToLast > 2*diff && diff < (256 * 256 * 2)) { pixelOffsets.removeElementAt(size - 1); } } boolean little = isLittleEndian(); core = new CoreMetadata[pixelOffsets.size()]; for (int i=0; i<getSeriesCount(); i++) { core[i] = new CoreMetadata(); core[i].littleEndian = little; } } status("Determining dimensions"); // determine total number of pixel bytes float pixelSize = 1f; String objective = null; Vector pixelSizeZ = new Vector(); long pixelBytes = 0; for (int i=0; i<pixelLengths.size(); i++) { pixelBytes += ((Long) pixelLengths.get(i)).longValue(); } String[] imageNames = new String[getSeriesCount()]; Vector channelNames = new Vector(); int nextName = 0; // try to find the width and height int iCount = 0; int hCount = 0; int uCount = 0; int prevSeries = -1; int prevSeriesU = -1; int nextChannel = 0; for (int i=0; i<metadataOffsets.size(); i++) { long off = ((Long) metadataOffsets.get(i)).longValue(); in.seek(off); long next = i == metadataOffsets.size() - 1 ? in.length() : ((Long) metadataOffsets.get(i + 1)).longValue(); int totalBlocks = (int) ((next - off) / 128); for (int q=0; q<totalBlocks; q++) { if (withinPixels(off + q * 128)) break; in.seek(off + q * 128); char n = (char) in.readShort(); if (n == 'i') { iCount++; in.skipBytes(94); pixelSizeZ.add(new Float(in.readFloat())); in.seek(in.getFilePointer() - 20); for (int j=0; j<pixelOffsets.size(); j++) { long end = j == pixelOffsets.size() - 1 ? in.length() : ((Long) pixelOffsets.get(j + 1)).longValue(); if (in.getFilePointer() < end) { if (core[j].sizeX == 0) { core[j].sizeX = in.readShort(); core[j].sizeY = in.readShort(); int checkX = in.readShort(); int checkY = in.readShort(); int div = in.readShort(); core[j].sizeX /= div; div = in.readShort(); core[j].sizeY /= div; } if (prevSeries != j) { iCount = 1; } prevSeries = j; core[j].sizeC = iCount; break; } } } else if (n == 'u') { uCount++; for (int j=0; j<pixelOffsets.size(); j++) { long end = j == pixelOffsets.size() - 1 ? in.length() : ((Long) pixelOffsets.get(j + 1)).longValue(); if (in.getFilePointer() < end) { if (prevSeriesU != j) { uCount = 1; } prevSeriesU = j; core[j].sizeZ = uCount; break; } } } else if (n == 'h') hCount++; else if (n == 'j') { in.skipBytes(2); String check = in.readString(2); if (check.equals("II") || check.equals("MM")) { // this block should contain an image name in.skipBytes(10); if (nextName < imageNames.length) { imageNames[nextName++] = in.readCString().trim(); } } } else if (n == 'm') { // this block should contain a channel name if (in.getFilePointer() > ((Long) pixelOffsets.get(0)).longValue()) { in.skipBytes(14); channelNames.add(in.readCString().trim()); } } else if (n == 'd') { // objective info and pixel size X/Y in.skipBytes(6); objective = in.readCString(); in.skipBytes(126); pixelSize = in.readFloat(); } } } for (int i=0; i<getSeriesCount(); i++) { setSeries(i); long pixels = ((Long) pixelLengths.get(i)).longValue() / 2; boolean x = true; while (getSizeX() * getSizeY() * getSizeC() * getSizeZ() > pixels) { if (x) core[i].sizeX /= 2; else core[i].sizeY /= 2; x = !x; } if (getSizeZ() == 0) core[i].sizeZ = 1; core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * getSizeZ() * getSizeC())); if (getSizeT() == 0) core[i].sizeT = 1; core[i].imageCount = getSizeZ() * getSizeC() * getSizeT(); core[i].pixelType = FormatTools.UINT16; core[i].dimensionOrder = "XYZTC"; core[i].indexed = false; core[i].falseColor = false; core[i].metadataComplete = true; } setSeries(0); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this); // link Instrument and Image store.setInstrumentID("Instrument:0", 0); store.setImageInstrumentRef("Instrument:0", 0); int index = 0; // populate Objective data store.setObjectiveModel(objective, 0, 0); // link Objective to Image store.setObjectiveID("Objective:0", 0, 0); store.setObjectiveSettingsObjective("Objective:0", 0); // populate Image data for (int i=0; i<getSeriesCount(); i++) { store.setImageName(imageNames[i], i); MetadataTools.setDefaultCreationDate(store, id, i); } // populate Dimensions data for (int i=0; i<getSeriesCount(); i++) { store.setDimensionsPhysicalSizeX(new Float(pixelSize), i, 0); store.setDimensionsPhysicalSizeY(new Float(pixelSize), i, 0); int idx = 0; for (int q=0; q<i; q++) { idx += core[q].sizeC; } if (idx < pixelSizeZ.size()) { store.setDimensionsPhysicalSizeZ((Float) pixelSizeZ.get(idx), i, 0); } } // populate LogicalChannel data for (int i=0; i<getSeriesCount(); i++) { for (int c=0; c<core[i].sizeC; c++) { if (index < channelNames.size()) { store.setLogicalChannelName((String) channelNames.get(index++), i, c); addMeta(imageNames[i] + " channel " + c, channelNames.get(index - 1)); } } } }
protected void initFile(String id) throws FormatException, IOException { if (debug) debug("SlidebookReader.initFile(" + id + ")"); super.initFile(id); in = new RandomAccessStream(id); status("Finding offsets to pixel data"); // Slidebook files appear to be comprised of four types of blocks: // variable length pixel data blocks, 512 byte metadata blocks, // 128 byte metadata blocks, and variable length metadata blocks. // // Fixed-length metadata blocks begin with a 2 byte identifier, // e.g. 'i' or 'h'. // Following this are two unknown bytes (usually 256), then a 2 byte // endianness identifier - II or MM, for little or big endian, respectively. // Presumably these blocks contain useful information, but for the most // part we aren't sure what it is or how to extract it. // // Variable length metadata blocks begin with 0xffff and are // (as far as I know) always between two fixed-length metadata blocks. // These appear to be a relatively new addition to the format - they are // only present in files received on/after March 30, 2008. // // Each pixel data block corresponds to one series. // The first 'i' metadata block after each pixel data block contains // the width and height of the planes in that block - this can (and does) // vary between blocks. // // Z, C, and T sizes are computed heuristically based on the number of // metadata blocks of a specific type. in.skipBytes(4); core[0].littleEndian = in.read() == 0x49; in.order(isLittleEndian()); metadataOffsets = new Vector(); pixelOffsets = new Vector(); pixelLengths = new Vector(); in.seek(0); // gather offsets to metadata and pixel data blocks while (in.getFilePointer() < in.length() - 8) { in.skipBytes(4); int checkOne = in.read(); int checkTwo = in.read(); if ((checkOne == 'I' && checkTwo == 'I') || (checkOne == 'M' && checkTwo == 'M')) { metadataOffsets.add(new Long(in.getFilePointer() - 6)); in.skipBytes(in.readShort() - 8); } else if (checkOne == -1 && checkTwo == -1) { boolean foundBlock = false; byte[] block = new byte[8192]; in.read(block); while (!foundBlock) { for (int i=0; i<block.length-2; i++) { if ((block[i] == 'M' && block[i + 1] == 'M') || (block[i] == 'I' && block[i + 1] == 'I')) { foundBlock = true; in.seek(in.getFilePointer() - block.length + i - 2); metadataOffsets.add(new Long(in.getFilePointer() - 2)); in.skipBytes(in.readShort() - 5); break; } } if (!foundBlock) { block[0] = block[block.length - 2]; block[1] = block[block.length - 1]; in.read(block, 2, block.length - 2); } } } else { String s = null; long fp = in.getFilePointer() - 6; in.seek(fp); int len = in.read(); if (len > 0 && len <= 32) { s = in.readString(len); } if (s != null && s.indexOf("Annotation") != -1) { if (s.equals("CTimelapseAnnotation")) { in.skipBytes(41); if (in.read() == 0) in.skipBytes(10); else in.seek(in.getFilePointer() - 1); } else if (s.equals("CIntensityBarAnnotation")) { in.skipBytes(56); int n = in.read(); while (n == 0 || n < 6 || n > 0x80) n = in.read(); in.seek(in.getFilePointer() - 1); } else if (s.equals("CCubeAnnotation")) { in.skipBytes(66); int n = in.read(); if (n != 0) in.seek(in.getFilePointer() - 1); } else if (s.equals("CScaleBarAnnotation")) { in.skipBytes(38); int extra = in.read(); if (extra <= 16) in.skipBytes(3 + extra); else in.skipBytes(2); } } else if (s != null && s.indexOf("Decon") != -1) { in.seek(fp); while (in.read() != ']'); } else { if ((fp % 2) == 1) fp -= 2; in.seek(fp); pixelOffsets.add(new Long(fp)); try { byte[] buf = new byte[8192]; boolean found = false; int n = in.read(buf); while (!found && in.getFilePointer() < in.length()) { for (int i=0; i<buf.length-6; i++) { if ((buf[i] == 'h' && buf[i+4] == 'I' && buf[i+5] == 'I') || (buf[i+1] == 'h' && buf[i+4] == 'M' && buf[i+5] == 'M')) { found = true; in.seek(in.getFilePointer() - n + i - 20); break; } } if (!found) { byte[] tmp = buf; buf = new byte[8192]; System.arraycopy(tmp, tmp.length - 20, buf, 0, 20); n = in.read(buf, 20, buf.length - 20); } } if (in.getFilePointer() <= in.length()) { pixelLengths.add(new Long(in.getFilePointer() - fp)); } else pixelOffsets.remove(pixelOffsets.size() - 1); } catch (EOFException e) { pixelOffsets.remove(pixelOffsets.size() - 1); } } } } for (int i=0; i<pixelOffsets.size(); i++) { long length = ((Long) pixelLengths.get(i)).longValue(); long offset = ((Long) pixelOffsets.get(i)).longValue(); in.seek(offset); byte checkByte = in.readByte(); if (length + offset >= in.length()) { pixelOffsets.remove(i); pixelLengths.remove(i); i--; } else if (checkByte == 'l') { long lengthSum = ((Long) pixelLengths.get(0)).longValue(); while (pixelLengths.size() > 1) { int size = pixelLengths.size() - 1; lengthSum += ((Long) pixelLengths.get(size)).longValue(); pixelLengths.remove(size); pixelOffsets.remove(size); } for (int q=0; q<metadataOffsets.size(); q++) { long mOffset = ((Long) metadataOffsets.get(q)).longValue(); if (mOffset > lengthSum) { lengthSum = mOffset - offset; break; } } pixelLengths.setElementAt(new Long(lengthSum), 0); break; } } if (pixelOffsets.size() > 1) { if (pixelOffsets.size() > 2) { int size = pixelOffsets.size(); long last = ((Long) pixelOffsets.get(size - 1)).longValue(); long nextToLast = ((Long) pixelOffsets.get(size - 2)).longValue(); long diff = in.length() - last; if (last - nextToLast > 2*diff && diff < (256 * 256 * 2)) { pixelOffsets.removeElementAt(size - 1); } } boolean little = isLittleEndian(); core = new CoreMetadata[pixelOffsets.size()]; for (int i=0; i<getSeriesCount(); i++) { core[i] = new CoreMetadata(); core[i].littleEndian = little; } } status("Determining dimensions"); // determine total number of pixel bytes float pixelSize = 1f; String objective = null; Vector pixelSizeZ = new Vector(); long pixelBytes = 0; for (int i=0; i<pixelLengths.size(); i++) { pixelBytes += ((Long) pixelLengths.get(i)).longValue(); } String[] imageNames = new String[getSeriesCount()]; Vector channelNames = new Vector(); int nextName = 0; // try to find the width and height int iCount = 0; int hCount = 0; int uCount = 0; int prevSeries = -1; int prevSeriesU = -1; int nextChannel = 0; for (int i=0; i<metadataOffsets.size(); i++) { long off = ((Long) metadataOffsets.get(i)).longValue(); in.seek(off); long next = i == metadataOffsets.size() - 1 ? in.length() : ((Long) metadataOffsets.get(i + 1)).longValue(); int totalBlocks = (int) ((next - off) / 128); for (int q=0; q<totalBlocks; q++) { if (withinPixels(off + q * 128)) break; in.seek(off + q * 128); char n = (char) in.readShort(); if (n == 'i') { iCount++; in.skipBytes(94); pixelSizeZ.add(new Float(in.readFloat())); in.seek(in.getFilePointer() - 20); for (int j=0; j<pixelOffsets.size(); j++) { long end = j == pixelOffsets.size() - 1 ? in.length() : ((Long) pixelOffsets.get(j + 1)).longValue(); if (in.getFilePointer() < end) { if (core[j].sizeX == 0) { core[j].sizeX = in.readShort(); core[j].sizeY = in.readShort(); int checkX = in.readShort(); int checkY = in.readShort(); int div = in.readShort(); core[j].sizeX /= (div == 0 ? 1 : div); div = in.readShort(); core[j].sizeY /= (div == 0 ? 1 : div); } if (prevSeries != j) { iCount = 1; } prevSeries = j; core[j].sizeC = iCount; break; } } } else if (n == 'u') { uCount++; for (int j=0; j<pixelOffsets.size(); j++) { long end = j == pixelOffsets.size() - 1 ? in.length() : ((Long) pixelOffsets.get(j + 1)).longValue(); if (in.getFilePointer() < end) { if (prevSeriesU != j) { uCount = 1; } prevSeriesU = j; core[j].sizeZ = uCount; break; } } } else if (n == 'h') hCount++; else if (n == 'j') { in.skipBytes(2); String check = in.readString(2); if (check.equals("II") || check.equals("MM")) { // this block should contain an image name in.skipBytes(10); if (nextName < imageNames.length) { imageNames[nextName++] = in.readCString().trim(); } if (core[nextName - 1].sizeX == 0 || core[nextName - 1].sizeY == 0) { in.skipBytes(123); core[nextName - 1].sizeX = in.readInt(); core[nextName - 1].sizeY = in.readInt(); int div = in.readInt(); core[nextName - 1].sizeX /= (div == 0 ? 1 : div); div = in.readInt(); core[nextName - 1].sizeY /= (div == 0 ? 1 : div); } } } else if (n == 'm') { // this block should contain a channel name if (in.getFilePointer() > ((Long) pixelOffsets.get(0)).longValue()) { in.skipBytes(14); channelNames.add(in.readCString().trim()); } } else if (n == 'd') { // objective info and pixel size X/Y in.skipBytes(6); objective = in.readCString(); in.skipBytes(126); pixelSize = in.readFloat(); } } } for (int i=0; i<getSeriesCount(); i++) { setSeries(i); long pixels = ((Long) pixelLengths.get(i)).longValue() / 2; boolean x = true; while (getSizeX() * getSizeY() * getSizeC() * getSizeZ() > pixels) { if (x) core[i].sizeX /= 2; else core[i].sizeY /= 2; x = !x; } if (getSizeZ() == 0) core[i].sizeZ = 1; core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * getSizeZ() * getSizeC())); if (getSizeT() == 0) core[i].sizeT = 1; core[i].imageCount = getSizeZ() * getSizeC() * getSizeT(); core[i].pixelType = FormatTools.UINT16; core[i].dimensionOrder = "XYZTC"; core[i].indexed = false; core[i].falseColor = false; core[i].metadataComplete = true; } setSeries(0); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this); // link Instrument and Image store.setInstrumentID("Instrument:0", 0); store.setImageInstrumentRef("Instrument:0", 0); int index = 0; // populate Objective data store.setObjectiveModel(objective, 0, 0); // link Objective to Image store.setObjectiveID("Objective:0", 0, 0); store.setObjectiveSettingsObjective("Objective:0", 0); // populate Image data for (int i=0; i<getSeriesCount(); i++) { store.setImageName(imageNames[i], i); MetadataTools.setDefaultCreationDate(store, id, i); } // populate Dimensions data for (int i=0; i<getSeriesCount(); i++) { store.setDimensionsPhysicalSizeX(new Float(pixelSize), i, 0); store.setDimensionsPhysicalSizeY(new Float(pixelSize), i, 0); int idx = 0; for (int q=0; q<i; q++) { idx += core[q].sizeC; } if (idx < pixelSizeZ.size()) { store.setDimensionsPhysicalSizeZ((Float) pixelSizeZ.get(idx), i, 0); } } // populate LogicalChannel data for (int i=0; i<getSeriesCount(); i++) { for (int c=0; c<core[i].sizeC; c++) { if (index < channelNames.size()) { store.setLogicalChannelName((String) channelNames.get(index++), i, c); addMeta(imageNames[i] + " channel " + c, channelNames.get(index - 1)); } } } }
diff --git a/h2/src/main/org/h2/command/Command.java b/h2/src/main/org/h2/command/Command.java index 2a52599cb..e6cfe2885 100644 --- a/h2/src/main/org/h2/command/Command.java +++ b/h2/src/main/org/h2/command/Command.java @@ -1,254 +1,268 @@ /* * Copyright 2004-2008 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.command; import java.sql.SQLException; import org.h2.constant.ErrorCode; import org.h2.engine.Constants; import org.h2.engine.Database; import org.h2.engine.Session; import org.h2.message.Message; import org.h2.message.Trace; import org.h2.message.TraceObject; import org.h2.result.LocalResult; import org.h2.result.ResultInterface; import org.h2.util.ObjectArray; /** * Represents a SQL statement. This object is only used on the server side. */ public abstract class Command implements CommandInterface { /** * The session. */ protected final Session session; /** * The trace module. */ protected final Trace trace; /** * The last start time. */ protected long startTime; /** * If this query was canceled. */ private volatile boolean cancel; private final String sql; public Command(Parser parser, String sql) { this.session = parser.getSession(); this.sql = sql; trace = session.getDatabase().getTrace(Trace.COMMAND); } /** * Check if this command is transactional. * If it is not, then it forces the current transaction to commit. * * @return true if it is */ public abstract boolean isTransactional(); /** * Check if this command is a query. * * @return true if it is */ public abstract boolean isQuery(); /** * Get the list of parameters. * * @return the list of parameters */ public abstract ObjectArray getParameters(); /** * Check if this command is read only. * * @return true if it is */ public abstract boolean isReadOnly(); /** * Get an empty result set containing the meta data. * * @return an empty result set */ public abstract LocalResult queryMeta() throws SQLException; /** * Execute an updating statement, if this is possible. * * @return the update count * @throws SQLException if the command is not an updating statement */ public int update() throws SQLException { throw Message.getSQLException(ErrorCode.METHOD_NOT_ALLOWED_FOR_QUERY); } /** * Execute a query statement, if this is possible. * * @param maxrows the maximum number of rows returned * @return the local result set * @throws SQLException if the command is not a query */ public LocalResult query(int maxrows) throws SQLException { throw Message.getSQLException(ErrorCode.METHOD_ONLY_ALLOWED_FOR_QUERY); } public final LocalResult getMetaDataLocal() throws SQLException { return queryMeta(); } public final ResultInterface getMetaData() throws SQLException { return queryMeta(); } public ResultInterface executeQuery(int maxrows, boolean scrollable) throws SQLException { return executeQueryLocal(maxrows); } /** * Execute a query and return a local result set. * This method prepares everything and calls {@link #query(int)} finally. * * @param maxrows the maximum number of rows to return * @return the local result set */ public LocalResult executeQueryLocal(int maxrows) throws SQLException { startTime = System.currentTimeMillis(); Database database = session.getDatabase(); Object sync = database.isMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { try { database.checkPowerOff(); session.setCurrentCommand(this, startTime); return query(maxrows); } catch (Exception e) { SQLException s = Message.convert(e, sql); database.exceptionThrown(s, sql); throw s; } finally { stop(); } } } /** * Start the stopwatch. */ void start() { startTime = System.currentTimeMillis(); } /** * Check if this command has been canceled, and throw an exception if yes. * * @throws SQLException if the statement has been canceled */ public void checkCanceled() throws SQLException { if (cancel) { cancel = false; throw Message.getSQLException(ErrorCode.STATEMENT_WAS_CANCELED); } } private void stop() throws SQLException { session.closeTemporaryResults(); session.setCurrentCommand(null, 0); if (!isTransactional()) { session.commit(true); } else if (session.getAutoCommit()) { session.commit(false); } else if (session.getDatabase().isMultiThreaded()) { Database db = session.getDatabase(); if (db != null) { if (db.getLockMode() == Constants.LOCK_MODE_READ_COMMITTED) { session.unlockReadLocks(); } } } if (trace.isInfoEnabled()) { long time = System.currentTimeMillis() - startTime; if (time > Constants.SLOW_QUERY_LIMIT_MS) { trace.info("slow query: " + time); } } } public int executeUpdate() throws SQLException { long start = startTime = System.currentTimeMillis(); Database database = session.getDatabase(); database.allocateReserveMemory(); Object sync = database.isMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { int rollback = session.getLogId(); session.setCurrentCommand(this, startTime); try { while (true) { database.checkPowerOff(); try { return update(); } catch (OutOfMemoryError e) { database.freeReserveMemory(); throw Message.convert(e); } catch (SQLException e) { if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) { long now = System.currentTimeMillis(); if (now - start > session.getLockTimeout()) { throw e; } try { database.wait(100); } catch (InterruptedException e1) { // ignore } continue; } throw e; } catch (Throwable e) { throw Message.convert(e); } } } catch (SQLException e) { database.exceptionThrown(e, sql); database.checkPowerOff(); if (e.getErrorCode() == ErrorCode.DEADLOCK_1) { session.rollback(); + } else if (e.getErrorCode() == ErrorCode.OUT_OF_MEMORY) { + // try to rollback, saving memory + try { + session.rollbackTo(rollback, true); + } catch (SQLException e2) { + if (e2.getErrorCode() == ErrorCode.OUT_OF_MEMORY) { + // if rollback didn't work, there is a serious problem: + // the transaction may be applied partially + // in this case we need to panic: + // close the database + session.getDatabase().shutdownImmediately(); + } + throw e2; + } } else { - session.rollbackTo(rollback); + session.rollbackTo(rollback, false); } throw e; } finally { stop(); } } } public void close() { // nothing to do } public void cancel() { this.cancel = true; } public String toString() { return TraceObject.toString(sql, getParameters()); } }
false
true
public int executeUpdate() throws SQLException { long start = startTime = System.currentTimeMillis(); Database database = session.getDatabase(); database.allocateReserveMemory(); Object sync = database.isMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { int rollback = session.getLogId(); session.setCurrentCommand(this, startTime); try { while (true) { database.checkPowerOff(); try { return update(); } catch (OutOfMemoryError e) { database.freeReserveMemory(); throw Message.convert(e); } catch (SQLException e) { if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) { long now = System.currentTimeMillis(); if (now - start > session.getLockTimeout()) { throw e; } try { database.wait(100); } catch (InterruptedException e1) { // ignore } continue; } throw e; } catch (Throwable e) { throw Message.convert(e); } } } catch (SQLException e) { database.exceptionThrown(e, sql); database.checkPowerOff(); if (e.getErrorCode() == ErrorCode.DEADLOCK_1) { session.rollback(); } else { session.rollbackTo(rollback); } throw e; } finally { stop(); } } }
public int executeUpdate() throws SQLException { long start = startTime = System.currentTimeMillis(); Database database = session.getDatabase(); database.allocateReserveMemory(); Object sync = database.isMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { int rollback = session.getLogId(); session.setCurrentCommand(this, startTime); try { while (true) { database.checkPowerOff(); try { return update(); } catch (OutOfMemoryError e) { database.freeReserveMemory(); throw Message.convert(e); } catch (SQLException e) { if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) { long now = System.currentTimeMillis(); if (now - start > session.getLockTimeout()) { throw e; } try { database.wait(100); } catch (InterruptedException e1) { // ignore } continue; } throw e; } catch (Throwable e) { throw Message.convert(e); } } } catch (SQLException e) { database.exceptionThrown(e, sql); database.checkPowerOff(); if (e.getErrorCode() == ErrorCode.DEADLOCK_1) { session.rollback(); } else if (e.getErrorCode() == ErrorCode.OUT_OF_MEMORY) { // try to rollback, saving memory try { session.rollbackTo(rollback, true); } catch (SQLException e2) { if (e2.getErrorCode() == ErrorCode.OUT_OF_MEMORY) { // if rollback didn't work, there is a serious problem: // the transaction may be applied partially // in this case we need to panic: // close the database session.getDatabase().shutdownImmediately(); } throw e2; } } else { session.rollbackTo(rollback, false); } throw e; } finally { stop(); } } }
diff --git a/WEB-INF/src/hygeia/Algorithm.java b/WEB-INF/src/hygeia/Algorithm.java index 66b1776..8bdb9e8 100644 --- a/WEB-INF/src/hygeia/Algorithm.java +++ b/WEB-INF/src/hygeia/Algorithm.java @@ -1,145 +1,145 @@ package hygeia; import java.sql.*; import java.security.*; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Random; public class Algorithm { private Database db; private int uid; private static final int BREAKFAST = 0x08; private static final int LUNCH = 0x04; private static final int DINNER = 0x02; private static final int SNACK = 0x01; private static final double SAME = 1.1; //used as a margin of error for relatively balanced meals public Algorithm(Database db, User u) { this.uid = u.getUid(); this.db = u.getDb(); } /* Main algorithm. */ /* Based on what kind of meal requested an int matching the legend is passed. */ public static Meal suggestMeal(User u, int type) { try { Meal m = suggestMeal0(u, type); u.getDb().free(); return m; } catch (SQLException e) { u.getDb().free(); return null; } } public static Meal suggestMeal0(User u, int type) throws SQLException { if (u == null) { return null; } Database db = u.getDb(); //pulls all meals from the universal meal list and the user's personal meals ResultSet rs = db.execute("select mid from meals where (uid = " + u.getUid() + " or uid = 0) and type & " + type + " = " + type + ";"); //arraylist of meal IDs that come from the database ArrayList<Integer> results = new ArrayList<Integer>(); while(rs.next()) { results.add(rs.getInt("mid")); } //retrieves a list of food in the inventory Inventory inven = new Inventory(u); Food.Update[] fu = inven.getInventory(); if (fu == null) { return null; } //random generator to select a meal at random from available MIDs Random r = new Random(); //if the inventorymatchcount variable equals the number of ingredients in a recipe, all necessary ingredients are available int inventorymatchcount = 0; //Meal m is the variable used to store meals as they are accessed for comparison to ingredients Meal m = null; //while loop runs while a suitable meal isn't found yet while (results.size() > 0) { inventorymatchcount = 0; int nextInt = r.nextInt(results.size()); m = new Meal(db, results.get(nextInt)); Food.Update mu[] = m.getMeal(); // System.out.println("mu length " + mu.length + " fu length " + fu.length); for (int i = 0; i < mu.length; i++) { for (int j = 0; j < fu.length; j++) { if (mu[i].equals(fu[j])) { inventorymatchcount += 1; } } } if (inventorymatchcount == mu.length) { //begins balanced suggestion based on the 40:30:30 ideal, //+ and - 10% (defined as constant SAME, Suggest A Meal Error) to find relatively balanced meals Nutrition n = m.getNutrition(); double totalGrams = 0; totalGrams = (n.getCarbohydrates() + n.getProtein() + n.getFat()); if (n.getCarbohydrates() / totalGrams > 0.4 - SAME && n.getCarbohydrates() / totalGrams < 0.4 + SAME) { if (n.getProtein() / totalGrams > 0.3 - SAME && n.getProtein() / totalGrams < 0.3 + SAME) { if (n.getFat() / totalGrams > 0.3 - SAME && n.getFat() / totalGrams < 0.3 + SAME) { return m; } } } } /*else { */ //if the contents of the inventory don't satisfy the recipe, remove that recipe //from the ArrayList of meals so it won't accidentally be compared again results.remove(nextInt); /* }*/ } //if no meal matches the SAME margin of error for balancedness, return null - return null; + return new Meal(db, 0); } /* Sanitizes a String for use. */ public static String Clean(String s) { StringTokenizer toke = new StringTokenizer(s, "*/\\\"\':;-()=+[]"); String r = new String(""); while(toke.hasMoreTokens()) { r = new String(r + toke.nextToken()); } return r; } /* Should return MD5 hashes.. but may be platform dependent. And this was written by some anonymous author. FYI. */ public static String MD5(String md5) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { } return null; } }
true
true
public static Meal suggestMeal0(User u, int type) throws SQLException { if (u == null) { return null; } Database db = u.getDb(); //pulls all meals from the universal meal list and the user's personal meals ResultSet rs = db.execute("select mid from meals where (uid = " + u.getUid() + " or uid = 0) and type & " + type + " = " + type + ";"); //arraylist of meal IDs that come from the database ArrayList<Integer> results = new ArrayList<Integer>(); while(rs.next()) { results.add(rs.getInt("mid")); } //retrieves a list of food in the inventory Inventory inven = new Inventory(u); Food.Update[] fu = inven.getInventory(); if (fu == null) { return null; } //random generator to select a meal at random from available MIDs Random r = new Random(); //if the inventorymatchcount variable equals the number of ingredients in a recipe, all necessary ingredients are available int inventorymatchcount = 0; //Meal m is the variable used to store meals as they are accessed for comparison to ingredients Meal m = null; //while loop runs while a suitable meal isn't found yet while (results.size() > 0) { inventorymatchcount = 0; int nextInt = r.nextInt(results.size()); m = new Meal(db, results.get(nextInt)); Food.Update mu[] = m.getMeal(); // System.out.println("mu length " + mu.length + " fu length " + fu.length); for (int i = 0; i < mu.length; i++) { for (int j = 0; j < fu.length; j++) { if (mu[i].equals(fu[j])) { inventorymatchcount += 1; } } } if (inventorymatchcount == mu.length) { //begins balanced suggestion based on the 40:30:30 ideal, //+ and - 10% (defined as constant SAME, Suggest A Meal Error) to find relatively balanced meals Nutrition n = m.getNutrition(); double totalGrams = 0; totalGrams = (n.getCarbohydrates() + n.getProtein() + n.getFat()); if (n.getCarbohydrates() / totalGrams > 0.4 - SAME && n.getCarbohydrates() / totalGrams < 0.4 + SAME) { if (n.getProtein() / totalGrams > 0.3 - SAME && n.getProtein() / totalGrams < 0.3 + SAME) { if (n.getFat() / totalGrams > 0.3 - SAME && n.getFat() / totalGrams < 0.3 + SAME) { return m; } } } } /*else { */ //if the contents of the inventory don't satisfy the recipe, remove that recipe //from the ArrayList of meals so it won't accidentally be compared again results.remove(nextInt); /* }*/ } //if no meal matches the SAME margin of error for balancedness, return null return null; } /* Sanitizes a String for use. */ public static String Clean(String s) { StringTokenizer toke = new StringTokenizer(s, "*/\\\"\':;-()=+[]"); String r = new String(""); while(toke.hasMoreTokens()) { r = new String(r + toke.nextToken()); } return r; } /* Should return MD5 hashes.. but may be platform dependent. And this was written by some anonymous author. FYI. */ public static String MD5(String md5) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { } return null; } }
public static Meal suggestMeal0(User u, int type) throws SQLException { if (u == null) { return null; } Database db = u.getDb(); //pulls all meals from the universal meal list and the user's personal meals ResultSet rs = db.execute("select mid from meals where (uid = " + u.getUid() + " or uid = 0) and type & " + type + " = " + type + ";"); //arraylist of meal IDs that come from the database ArrayList<Integer> results = new ArrayList<Integer>(); while(rs.next()) { results.add(rs.getInt("mid")); } //retrieves a list of food in the inventory Inventory inven = new Inventory(u); Food.Update[] fu = inven.getInventory(); if (fu == null) { return null; } //random generator to select a meal at random from available MIDs Random r = new Random(); //if the inventorymatchcount variable equals the number of ingredients in a recipe, all necessary ingredients are available int inventorymatchcount = 0; //Meal m is the variable used to store meals as they are accessed for comparison to ingredients Meal m = null; //while loop runs while a suitable meal isn't found yet while (results.size() > 0) { inventorymatchcount = 0; int nextInt = r.nextInt(results.size()); m = new Meal(db, results.get(nextInt)); Food.Update mu[] = m.getMeal(); // System.out.println("mu length " + mu.length + " fu length " + fu.length); for (int i = 0; i < mu.length; i++) { for (int j = 0; j < fu.length; j++) { if (mu[i].equals(fu[j])) { inventorymatchcount += 1; } } } if (inventorymatchcount == mu.length) { //begins balanced suggestion based on the 40:30:30 ideal, //+ and - 10% (defined as constant SAME, Suggest A Meal Error) to find relatively balanced meals Nutrition n = m.getNutrition(); double totalGrams = 0; totalGrams = (n.getCarbohydrates() + n.getProtein() + n.getFat()); if (n.getCarbohydrates() / totalGrams > 0.4 - SAME && n.getCarbohydrates() / totalGrams < 0.4 + SAME) { if (n.getProtein() / totalGrams > 0.3 - SAME && n.getProtein() / totalGrams < 0.3 + SAME) { if (n.getFat() / totalGrams > 0.3 - SAME && n.getFat() / totalGrams < 0.3 + SAME) { return m; } } } } /*else { */ //if the contents of the inventory don't satisfy the recipe, remove that recipe //from the ArrayList of meals so it won't accidentally be compared again results.remove(nextInt); /* }*/ } //if no meal matches the SAME margin of error for balancedness, return null return new Meal(db, 0); } /* Sanitizes a String for use. */ public static String Clean(String s) { StringTokenizer toke = new StringTokenizer(s, "*/\\\"\':;-()=+[]"); String r = new String(""); while(toke.hasMoreTokens()) { r = new String(r + toke.nextToken()); } return r; } /* Should return MD5 hashes.. but may be platform dependent. And this was written by some anonymous author. FYI. */ public static String MD5(String md5) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { } return null; } }
diff --git a/Oberien/src/controller/Options.java b/Oberien/src/controller/Options.java index 8e7c97b..571572d 100644 --- a/Oberien/src/controller/Options.java +++ b/Oberien/src/controller/Options.java @@ -1,302 +1,305 @@ package controller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import org.lwjgl.util.Dimension; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.SlickException; public class Options { /** * AppGameContainer the settings are applied to */ private static AppGameContainer game; /** * indicates whether vertical synchronisation is activated */ private static boolean vsync = true; private static boolean vsyncChanged = false; /** * 0 = fullscreen <br> * 1 = windowed <br> * 2 = borderless <br> */ private static int screenMode = 0; private static boolean screenModeChanged = false; /** * width and height of the game */ private static Dimension resolution; private static boolean resolutionChanged = false; /** * indicates wheather the game is only rendered when it is visible or not */ private static boolean onlyUpdateWhenVisible = true; private static boolean onlyUpdateWhenVisibleChanged = false; /** * indicates wheather anti aliasing is enabled or not */ private static boolean antiAliasing = false; /** * sets the loading speed (0-1)<br> * higher values result in less notifications but in a higher load speed */ private static double loadingSpeed = 0.01; /** * indicates the number of frames per second to be displayed<br> * <= 0 => max FPS */ private static int fps = 0; private static boolean fpsChanged = false; /** * indicates whether to show the fps in the top left corner or not */ private static boolean showFps = true; private static boolean showFpsChanged = false; /** * Volume of music and sound, and the overall volume. Not implemented yet. */ private static int masterVolume = 100, musicVolume = 100, soundVolume = 100; public static void initOptions(AppGameContainer agc) { game = agc; resolution = new Dimension(game.getScreenWidth(), game.getScreenHeight()); } public static void applySettings() throws SlickException, IllegalStateException { if (game == null) { throw new IllegalStateException("AppGameContainer in Options not initialized. Please use Options.init(AppGameContainer) first."); } if (resolutionChanged) { game.setDisplayMode(resolution.getWidth(), resolution.getHeight(), screenMode == 0); resolutionChanged = false; } if (resolutionChanged || screenModeChanged) { if (Options.screenMode == 0) { game.setFullscreen(true); } else if (Options.screenMode == 1) { + System.setProperty("org.lwjgl.opengl.Window.undecorated", "false"); + game.setFullscreen(true); + game.setFullscreen(false); + } else if (Options.screenMode == 2) { + System.setProperty("org.lwjgl.opengl.Window.undecorated", "true"); + game.setFullscreen(true); game.setFullscreen(false); - if (Options.screenMode == 2) { - System.setProperty("org.lwjgl.opengl.Window.undecorated", "true"); - } } screenModeChanged = false; } if (vsyncChanged) { game.setVSync(vsync); vsyncChanged = false; } if (onlyUpdateWhenVisibleChanged) { game.setUpdateOnlyWhenVisible(Options.onlyUpdateWhenVisible); onlyUpdateWhenVisibleChanged = false; } if (fpsChanged) { game.setTargetFrameRate(Options.fps); fpsChanged = false; } if (showFpsChanged) { game.setShowFPS(showFps); showFpsChanged = false; } } public static void save() { try { File f = new File("cfg/settings.properties"); if (!f.exists()) { new File("cfg").mkdirs(); f.createNewFile(); } Properties properties = new Properties(); properties.setProperty("vsync", vsync + ""); properties.setProperty("screenMode", screenMode + ""); properties.setProperty("resolution", resolution.getWidth() + ":" + resolution.getHeight()); properties.setProperty("onlyUpdateWhenVisible", onlyUpdateWhenVisible + ""); properties.setProperty("antiAliasing", antiAliasing + ""); properties.setProperty("loadingSpeed", loadingSpeed + ""); properties.setProperty("fps", fps + ""); properties.setProperty("showFps", showFps + ""); properties.setProperty("masterVolume", masterVolume + ""); properties.setProperty("musicVolume", musicVolume + ""); properties.setProperty("soundVolume", soundVolume + ""); properties.store(new FileOutputStream("cfg/settings.properties"), null); } catch (IOException e) { e.printStackTrace(); } } public static void load() { if (game == null) { throw new IllegalStateException("AppGameContainer in Options not initialized. Please use Options.init(AppGameContainer) first."); } try { Properties properties = new Properties(); properties.load(new FileInputStream("cfg/settings.properties")); vsync = Boolean.parseBoolean(properties.getProperty("vsync", "true")); screenMode = Integer.parseInt(properties.getProperty("screenMode", "0")); String[] res = properties.getProperty("resolution", game.getScreenWidth() + ":" + game.getScreenHeight()).split(":"); resolution = new Dimension(Integer.parseInt(res[0]), Integer.parseInt(res[1])); onlyUpdateWhenVisible = Boolean.parseBoolean(properties.getProperty("onlyUpdateWhenVisible", "true")); antiAliasing = Boolean.parseBoolean(properties.getProperty("antiAliaising", "false")); loadingSpeed = Double.parseDouble(properties.getProperty("loadingSpeed", "0.01")); fps = Integer.parseInt(properties.getProperty("fps", "0")); showFps = Boolean.parseBoolean(properties.getProperty("showFps", "true")); masterVolume = Integer.parseInt(properties.getProperty("masterVolume", "100")); musicVolume = Integer.parseInt(properties.getProperty("musicVolume", "100")); soundVolume = Integer.parseInt(properties.getProperty("soundVolume", "100")); vsyncChanged = true; screenModeChanged = true; resolutionChanged = true; onlyUpdateWhenVisible = true; fpsChanged = true; showFpsChanged = true; } catch (FileNotFoundException e) { save(); } catch (IOException e) {e.printStackTrace();} } public static boolean isVsync() { return vsync; } public static void setVsync(boolean vsync) { if (Options.vsync == vsync) { return; } else { Options.vsync = vsync; Options.vsyncChanged = true; } } public static int getScreenMode() { return screenMode; } public static void setScreenMode(int screenMode) { if (Options.screenMode == screenMode) { return; } else { Options.screenMode = screenMode; screenModeChanged = true; } } public static boolean isOnlyUpdateWhenVisible() { return onlyUpdateWhenVisible; } public static void setOnlyUpdateWhenVisible(boolean onlyUpdateWhenVisible) { if (Options.onlyUpdateWhenVisible == onlyUpdateWhenVisible) { return; } else { Options.onlyUpdateWhenVisible = onlyUpdateWhenVisible; onlyUpdateWhenVisibleChanged = true; } } public static boolean isAntiAliasing() { return antiAliasing; } public static void setAntiAliasing(boolean antiAliasing) { if (Options.antiAliasing == antiAliasing) { return; } else { Options.antiAliasing = antiAliasing; } } public static double getLoadingSpeed() { return loadingSpeed; } public static void setLoadingSpeed(double loadingSpeed) { if (Options.loadingSpeed == loadingSpeed) { return; } else { Options.loadingSpeed = loadingSpeed; } } public static int getFps() { return fps; } public static void setFps(int fps) { if (Options.fps == fps) { return; } else { Options.fps = fps; fpsChanged = false; } } public static int getMasterVolume() { return masterVolume; } public static void setMasterVolume(int masterVolume) { if (Options.masterVolume == masterVolume) { return; } else { Options.masterVolume = masterVolume; } } public static int getMusicVolume() { return musicVolume; } public static void setMusicVolume(int musicVolume) { if (Options.musicVolume == musicVolume) { return; } else { Options.musicVolume = musicVolume; } } public static int getSoundVolume() { return soundVolume; } public static void setSoundVolume(int soundVolume) { if (Options.soundVolume == soundVolume) { return; } else { Options.soundVolume = soundVolume; } } public static boolean isShowFps() { return showFps; } public static void setShowFps(boolean showFps) { if (Options.showFps == showFps) { return; } else { Options.showFps = showFps; showFpsChanged = true; } } public static Dimension getResolution() { return resolution; } public static void setResolution(Dimension resolution) { if (Options.resolution.equals(resolution)) { return; } else { Options.resolution = resolution; resolutionChanged = true; } } }
false
true
public static void applySettings() throws SlickException, IllegalStateException { if (game == null) { throw new IllegalStateException("AppGameContainer in Options not initialized. Please use Options.init(AppGameContainer) first."); } if (resolutionChanged) { game.setDisplayMode(resolution.getWidth(), resolution.getHeight(), screenMode == 0); resolutionChanged = false; } if (resolutionChanged || screenModeChanged) { if (Options.screenMode == 0) { game.setFullscreen(true); } else if (Options.screenMode == 1) { game.setFullscreen(false); if (Options.screenMode == 2) { System.setProperty("org.lwjgl.opengl.Window.undecorated", "true"); } } screenModeChanged = false; } if (vsyncChanged) { game.setVSync(vsync); vsyncChanged = false; } if (onlyUpdateWhenVisibleChanged) { game.setUpdateOnlyWhenVisible(Options.onlyUpdateWhenVisible); onlyUpdateWhenVisibleChanged = false; } if (fpsChanged) { game.setTargetFrameRate(Options.fps); fpsChanged = false; } if (showFpsChanged) { game.setShowFPS(showFps); showFpsChanged = false; } }
public static void applySettings() throws SlickException, IllegalStateException { if (game == null) { throw new IllegalStateException("AppGameContainer in Options not initialized. Please use Options.init(AppGameContainer) first."); } if (resolutionChanged) { game.setDisplayMode(resolution.getWidth(), resolution.getHeight(), screenMode == 0); resolutionChanged = false; } if (resolutionChanged || screenModeChanged) { if (Options.screenMode == 0) { game.setFullscreen(true); } else if (Options.screenMode == 1) { System.setProperty("org.lwjgl.opengl.Window.undecorated", "false"); game.setFullscreen(true); game.setFullscreen(false); } else if (Options.screenMode == 2) { System.setProperty("org.lwjgl.opengl.Window.undecorated", "true"); game.setFullscreen(true); game.setFullscreen(false); } screenModeChanged = false; } if (vsyncChanged) { game.setVSync(vsync); vsyncChanged = false; } if (onlyUpdateWhenVisibleChanged) { game.setUpdateOnlyWhenVisible(Options.onlyUpdateWhenVisible); onlyUpdateWhenVisibleChanged = false; } if (fpsChanged) { game.setTargetFrameRate(Options.fps); fpsChanged = false; } if (showFpsChanged) { game.setShowFPS(showFps); showFpsChanged = false; } }
diff --git a/src/com/google/android/apps/dashclock/ui/SwipeDismissListViewTouchListener.java b/src/com/google/android/apps/dashclock/ui/SwipeDismissListViewTouchListener.java index 6243489..1b1df4c 100644 --- a/src/com/google/android/apps/dashclock/ui/SwipeDismissListViewTouchListener.java +++ b/src/com/google/android/apps/dashclock/ui/SwipeDismissListViewTouchListener.java @@ -1,358 +1,360 @@ /* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // THIS IS A BETA! I DON'T RECOMMEND USING IT IN PRODUCTION CODE JUST YET package com.google.android.apps.dashclock.ui; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.graphics.Rect; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListView; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A {@link android.view.View.OnTouchListener} that makes the list items in a {@link ListView} * dismissable. {@link ListView} is given special treatment because by default it handles touches * for its list items... i.e. it's in charge of drawing the pressed state (the list selector), * handling list item clicks, etc. * * <p>After creating the listener, the caller should also call {@link * ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}, passing in the scroll * listener returned by {@link #makeScrollListener()}. If a scroll listener is already assigned, the * caller should still pass scroll changes through to this listener. This will ensure that this * {@link SwipeDismissListViewTouchListener} is paused during list view scrolling.</p> * * <p>Example usage:</p> * * <pre> * SwipeDismissListViewTouchListener touchListener = * new SwipeDismissListViewTouchListener( * listView, * new SwipeDismissListViewTouchListener.OnDismissCallback() { * public void onDismiss(ListView listView, int[] reverseSortedPositions) { * for (int position : reverseSortedPositions) { * adapter.remove(adapter.getItem(position)); * } * adapter.notifyDataSetChanged(); * } * }); * listView.setOnTouchListener(touchListener); * listView.setOnScrollListener(touchListener.makeScrollListener()); * </pre> * * <p>This class Requires API level 12 or later due to use of {@link * android.view.ViewPropertyAnimator}.</p> */ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { // Cached ViewConfiguration and system-wide constant values private int mSlop; private int mMinFlingVelocity; private int mMaxFlingVelocity; private long mAnimationTime; // Fixed properties private ListView mListView; private DismissCallbacks mCallbacks; private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero // Transient properties private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>(); private int mDismissAnimationRefCount = 0; private float mDownX; private boolean mSwiping; private VelocityTracker mVelocityTracker; private int mDownPosition; private View mDownView; private boolean mPaused; /** * The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client * about a successful dismissal of one or more list item positions. */ public interface DismissCallbacks { /** * Called to determine whether the given position can be dismissed. */ boolean canDismiss(int position); /** * Called when the user has indicated they she would like to dismiss one or more list item * positions. * * @param listView The originating {@link ListView}. * @param reverseSortedPositions An array of positions to dismiss, sorted in descending * order for convenience. */ void onDismiss(ListView listView, int[] reverseSortedPositions); } /** * Constructs a new swipe-to-dismiss touch listener for the given list view. * * @param listView The list view whose items should be dismissable. * @param callbacks The callback to trigger when the user has indicated that she would like to * dismiss one or more list items. */ public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) { ViewConfiguration vc = ViewConfiguration.get(listView.getContext()); mSlop = vc.getScaledTouchSlop(); mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16; mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); mAnimationTime = listView.getContext().getResources().getInteger( android.R.integer.config_shortAnimTime); mListView = listView; mCallbacks = callbacks; } /** * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures. * * @param enabled Whether or not to watch for gestures. */ public void setEnabled(boolean enabled) { mPaused = !enabled; } /** * Returns an {@link android.widget.AbsListView.OnScrollListener} to be added to the {@link * ListView} using {@link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}. * If a scroll listener is already assigned, the caller should still pass scroll changes through * to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is * paused during list view scrolling.</p> * * @see SwipeDismissListViewTouchListener */ public AbsListView.OnScrollListener makeScrollListener() { return new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); } @Override public void onScroll(AbsListView absListView, int i, int i1, int i2) { } }; } @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mListView.getWidth(); } switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mPaused) { return false; } // TODO: ensure this is a finger, and set a flag // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mListView.getChildCount(); int[] listViewCoords = new int[2]; mListView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; for (int i = 0; i < childCount; i++) { child = mListView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { mDownView = child; break; } } if (mDownView != null) { mDownX = motionEvent.getRawX(); mDownPosition = mListView.getPositionForView(mDownView); if (mCallbacks.canDismiss(mDownPosition)) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); + } else { + mDownView = null; } } view.onTouchEvent(motionEvent); return true; } case MotionEvent.ACTION_UP: { if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss) { // dismiss final View downView = mDownView; // mDownView gets null'd before animation ends final int downPosition = mDownPosition; ++mDismissAnimationRefCount; mDownView.animate() .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); } else { // cancel mDownView.animate() .translationX(0) .alpha(1) .setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; if (Math.abs(deltaX) > mSlop) { mSwiping = true; mListView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mListView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } if (mSwiping) { mDownView.setTranslationX(deltaX); mDownView.setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } break; } } return false; } class PendingDismissData implements Comparable<PendingDismissData> { public int position; public View view; public PendingDismissData(int position, View view) { this.position = position; this.view = view; } @Override public int compareTo(PendingDismissData other) { // Sort by descending position return other.position - position; } } private void performDismiss(final View dismissView, final int dismissPosition) { // Animate the dismissed list item to zero-height and fire the dismiss callback when // all dismissed list item animations have completed. This triggers layout on each animation // frame; in the future we may want to do something smarter and more performant. final ViewGroup.LayoutParams lp = dismissView.getLayoutParams(); final int originalHeight = dismissView.getHeight(); ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { --mDismissAnimationRefCount; if (mDismissAnimationRefCount == 0) { // No active animations, process all pending dismisses. // Sort by descending position Collections.sort(mPendingDismisses); int[] dismissPositions = new int[mPendingDismisses.size()]; for (int i = mPendingDismisses.size() - 1; i >= 0; i--) { dismissPositions[i] = mPendingDismisses.get(i).position; } mCallbacks.onDismiss(mListView, dismissPositions); ViewGroup.LayoutParams lp; for (PendingDismissData pendingDismiss : mPendingDismisses) { // Reset view presentation pendingDismiss.view.setAlpha(1f); pendingDismiss.view.setTranslationX(0); lp = pendingDismiss.view.getLayoutParams(); lp.height = originalHeight; pendingDismiss.view.setLayoutParams(lp); } mPendingDismisses.clear(); } } }); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { lp.height = (Integer) valueAnimator.getAnimatedValue(); dismissView.setLayoutParams(lp); } }); mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView)); animator.start(); } }
true
true
public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mListView.getWidth(); } switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mPaused) { return false; } // TODO: ensure this is a finger, and set a flag // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mListView.getChildCount(); int[] listViewCoords = new int[2]; mListView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; for (int i = 0; i < childCount; i++) { child = mListView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { mDownView = child; break; } } if (mDownView != null) { mDownX = motionEvent.getRawX(); mDownPosition = mListView.getPositionForView(mDownView); if (mCallbacks.canDismiss(mDownPosition)) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); } } view.onTouchEvent(motionEvent); return true; } case MotionEvent.ACTION_UP: { if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss) { // dismiss final View downView = mDownView; // mDownView gets null'd before animation ends final int downPosition = mDownPosition; ++mDismissAnimationRefCount; mDownView.animate() .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); } else { // cancel mDownView.animate() .translationX(0) .alpha(1) .setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; if (Math.abs(deltaX) > mSlop) { mSwiping = true; mListView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mListView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } if (mSwiping) { mDownView.setTranslationX(deltaX); mDownView.setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } break; } } return false; }
public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mListView.getWidth(); } switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mPaused) { return false; } // TODO: ensure this is a finger, and set a flag // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mListView.getChildCount(); int[] listViewCoords = new int[2]; mListView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; for (int i = 0; i < childCount; i++) { child = mListView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { mDownView = child; break; } } if (mDownView != null) { mDownX = motionEvent.getRawX(); mDownPosition = mListView.getPositionForView(mDownView); if (mCallbacks.canDismiss(mDownPosition)) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); } else { mDownView = null; } } view.onTouchEvent(motionEvent); return true; } case MotionEvent.ACTION_UP: { if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss) { // dismiss final View downView = mDownView; // mDownView gets null'd before animation ends final int downPosition = mDownPosition; ++mDismissAnimationRefCount; mDownView.animate() .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); } else { // cancel mDownView.animate() .translationX(0) .alpha(1) .setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; if (Math.abs(deltaX) > mSlop) { mSwiping = true; mListView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mListView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } if (mSwiping) { mDownView.setTranslationX(deltaX); mDownView.setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } break; } } return false; }
diff --git a/src/main/org/jboss/jms/server/connectionfactory/ConnectionFactory.java b/src/main/org/jboss/jms/server/connectionfactory/ConnectionFactory.java index b5f07719d..fac86c93b 100644 --- a/src/main/org/jboss/jms/server/connectionfactory/ConnectionFactory.java +++ b/src/main/org/jboss/jms/server/connectionfactory/ConnectionFactory.java @@ -1,490 +1,489 @@ /** * JBoss, Home of Professional Open Source * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.jms.server.connectionfactory; import java.util.Map; import javax.management.ObjectName; import org.jboss.jms.client.plugin.LoadBalancingFactory; import org.jboss.jms.server.ConnectionFactoryManager; import org.jboss.jms.server.ConnectionManager; import org.jboss.jms.server.ConnectorManager; import org.jboss.jms.server.ServerPeer; import org.jboss.messaging.util.ExceptionUtil; import org.jboss.messaging.util.JMXAccessor; import org.jboss.remoting.InvokerLocator; import org.jboss.system.ServiceMBeanSupport; import org.w3c.dom.Element; /** * A deployable JBoss Messaging connection factory. * * The default connection factory does not support load balancing or * automatic failover. * * * @author <a href="mailto:[email protected]">Ovidiu Feodorov</a> * @author <a href="mailto:[email protected]">Tim Fox</a> * @version <tt>$Revision$</tt> * * $Id$ */ public class ConnectionFactory extends ServiceMBeanSupport { // Constants ------------------------------------------------------------------------------------ // Static --------------------------------------------------------------------------------------- // Attributes ----------------------------------------------------------------------------------- private String clientID; private JNDIBindings jndiBindings; private int prefetchSize = 150; private boolean slowConsumers; private boolean supportsFailover; private boolean supportsLoadBalancing; private LoadBalancingFactory loadBalancingFactory; private int defaultTempQueueFullSize = 200000; private int defaultTempQueuePageSize = 2000; private int defaultTempQueueDownCacheSize = 2000; private int dupsOKBatchSize = 1000; private ObjectName serverPeerObjectName; private ConnectionFactoryManager connectionFactoryManager; private ConnectorManager connectorManager; private ConnectionManager connectionManager; private ObjectName connectorObjectName; private boolean started; private boolean strictTck; private boolean disableRemotingChecks; // Constructors --------------------------------------------------------------------------------- public ConnectionFactory() { this(null); } public ConnectionFactory(String clientID) { this.clientID = clientID; // by default, a clustered connection uses a round-robin load balancing policy this.loadBalancingFactory = LoadBalancingFactory.getDefaultFactory(); } // ServiceMBeanSupport overrides ---------------------------------------------------------------- public synchronized void startService() throws Exception { try { log.debug(this + " starting"); started = true; if (connectorObjectName == null) { throw new IllegalArgumentException("A Connector must be specified for " + "each Connection Factory"); } if (serverPeerObjectName == null) { throw new IllegalArgumentException("ServerPeer must be specified for " + "each Connection Factory"); } String locatorURI = (String)JMXAccessor.getJMXAttributeOverSecurity(server, connectorObjectName, "InvokerLocator"); ServerPeer serverPeer = (ServerPeer)JMXAccessor.getJMXAttributeOverSecurity(server, serverPeerObjectName, "Instance"); if (!serverPeer.isSupportsFailover()) { this.supportsFailover = false; } InvokerLocator locator = new InvokerLocator(locatorURI); String protocol = locator.getProtocol(); if (!disableRemotingChecks && (protocol.equals("bisocket") || protocol.equals("sslbisocket"))) { //Sanity check - If users are using the AS Service Binding Manager to provide the remoting connector //configuration, it is quite easy for them to end up using an old version depending on what version on //the AS they are running in - e.g. if they have forgotten to update it. //This can lead to subtle errors - therefore we do a sanity check by checking the existence of some properties //which should always be there Map params = locator.getParameters(); //The "compulsory" parameters boolean cont = checkParam(params, "marshaller", "org.jboss.jms.wireformat.JMSWireFormat") && checkParam(params, "unmarshaller", "org.jboss.jms.wireformat.JMSWireFormat") && checkParam(params, "dataType", "jms") && checkParam(params, "timeout", "0") && checkParam(params, "clientSocketClass", "org.jboss.jms.client.remoting.ClientSocketWrapper") && - checkParam(params, "serverSocketClass", "org.jboss.jms.server.remoting.ServerSocketWrapper") && checkParam(params, "numberOfCallRetries", "1") && checkParam(params, "pingFrequency", "214748364") && checkParam(params, "pingWindowFactor", "10"); if (!cont) { throw new IllegalArgumentException("Failed to deploy connection factory since remoting configuration seems incorrect."); } String val = (String)params.get("clientLeasePeriod"); if (val != null) { int i = Integer.parseInt(val); if (i < 5000) { log.warn("Value of clientLeasePeriod at " + i + " seems low. Normal values are >= 5000"); } } val = (String)params.get("clientMaxPoolSize"); if (val != null) { int i = Integer.parseInt(val); if (i < 50) { log.warn("Value of clientMaxPoolSize at " + i + " seems low. Normal values are >= 50"); } } } connectionFactoryManager = serverPeer.getConnectionFactoryManager(); connectorManager = serverPeer.getConnectorManager(); connectionManager = serverPeer.getConnectionManager(); int refCount = connectorManager.registerConnector(connectorObjectName.getCanonicalName()); long leasePeriod = (Long)JMXAccessor.getJMXAttributeOverSecurity(server, connectorObjectName, "LeasePeriod"); // if leasePeriod <= 0, disable pinging altogether boolean enablePing = leasePeriod > 0; if (refCount == 1 && enablePing) { // TODO Something is not quite right here, we can detect failure even if pinging is not // enabled, for example if we try to send a callback to the client and sending the // calback fails // install the connection listener that listens for failed connections server.invoke(connectorObjectName, "addConnectionListener", new Object[] {connectionManager}, new String[] {"org.jboss.remoting.ConnectionListener"}); } // We use the MBean service name to uniquely identify the connection factory connectionFactoryManager. registerConnectionFactory(getServiceName().getCanonicalName(), clientID, jndiBindings, locatorURI, enablePing, prefetchSize, slowConsumers, defaultTempQueueFullSize, defaultTempQueuePageSize, defaultTempQueueDownCacheSize, dupsOKBatchSize, supportsFailover, supportsLoadBalancing, loadBalancingFactory, strictTck); String info = "Connector " + locator.getProtocol() + "://" + locator.getHost() + ":" + locator.getPort(); if (enablePing) { info += " has leasing enabled, lease period " + leasePeriod + " milliseconds"; } else { info += " has lease disabled"; } log.info(info); log.info(this + " started"); } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } } public synchronized void stopService() throws Exception { try { started = false; connectionFactoryManager. unregisterConnectionFactory(getServiceName().getCanonicalName(), supportsFailover, supportsLoadBalancing); connectorManager.unregisterConnector(connectorObjectName.getCanonicalName()); log.info(this + " undeployed"); } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } } // JMX managed attributes ----------------------------------------------------------------------- public int getDefaultTempQueueFullSize() { return defaultTempQueueFullSize; } public void setDefaultTempQueueFullSize(int size) { this.defaultTempQueueFullSize = size; } public int getDefaultTempQueuePageSize() { return defaultTempQueuePageSize; } public void setDefaultTempQueuePageSize(int size) { this.defaultTempQueuePageSize = size; } public int getDefaultTempQueueDownCacheSize() { return defaultTempQueueDownCacheSize; } public void setDefaultTempQueueDownCacheSize(int size) { this.defaultTempQueueDownCacheSize = size; } public int getPrefetchSize() { return prefetchSize; } public void setPrefetchSize(int prefetchSize) { this.prefetchSize = prefetchSize; } public boolean isSlowConsumers() { return slowConsumers; } public void setSlowConsumers(boolean slowConsumers) { this.slowConsumers = slowConsumers; } public String getClientID() { return clientID; } public void setJNDIBindings(Element e) throws Exception { jndiBindings = new JNDIBindings(e); } public Element getJNDIBindings() { if (jndiBindings == null) { return null; } return jndiBindings.getDelegate(); } public void setServerPeer(ObjectName on) { if (started) { log.warn("Cannot change the value of associated " + "server ObjectName after initialization!"); return; } serverPeerObjectName = on; } public ObjectName getServerPeer() { return serverPeerObjectName; } public void setConnector(ObjectName on) { if (started) { log.warn("Cannot change the value of associated " + "connector ObjectName after initialization!"); return; } connectorObjectName = on; } public ObjectName getConnector() { return connectorObjectName; } public boolean isSupportsFailover() { return supportsFailover; } public void setSupportsFailover(boolean supportsFailover) { if (started) { log.warn("supportsFailover can only be changed when connection factory is stopped"); return; } this.supportsFailover = supportsFailover; } public boolean isSupportsLoadBalancing() { return supportsLoadBalancing; } public void setSupportsLoadBalancing(boolean supportsLoadBalancing) { if (started) { log.warn("supportsLoadBalancing can only be changed when connection factory is stopped"); return; } this.supportsLoadBalancing = supportsLoadBalancing; } public String getLoadBalancingFactory() { return loadBalancingFactory.getClass().getName(); } public void setLoadBalancingFactory(String factoryName) throws Exception { if (started) { log.warn("Load balancing policy can only be changed when connection factory is stopped"); return; } //We don't use Class.forName() since then it won't work with scoped deployments Class clz = Thread.currentThread().getContextClassLoader().loadClass(factoryName); loadBalancingFactory = (LoadBalancingFactory)clz.newInstance(); } public void setDupsOKBatchSize(int size) throws Exception { if (started) { log.warn("DupsOKBatchSize can only be changed when connection factory is stopped"); return; } this.dupsOKBatchSize = size; } public int getDupsOKBatchSize() { return dupsOKBatchSize; } public boolean isStrictTck() { return strictTck; } public void setStrictTck(boolean strictTck) { if (started) { log.warn("StrictTCK can only be changed when connection factory is stopped"); return; } this.strictTck = strictTck; } public boolean isDisableRemotingChecks() { return disableRemotingChecks; } public void setDisableRemotingChecks(boolean disable) { if (started) { log.warn("DisableRemotingChecks can only be changed when connection factory is stopped"); return; } this.disableRemotingChecks = disable; } // JMX managed operations ----------------------------------------------------------------------- // Public --------------------------------------------------------------------------------------- // Package protected ---------------------------------------------------------------------------- // Protected ------------------------------------------------------------------------------------ // Private -------------------------------------------------------------------------------------- private boolean checkParam(Map params, String key, String value) { String val = (String)params.get(key); if (val == null) { log.error("Parameter " + key + " is not specified in the remoting congiguration"); return false; } else if (!val.equals(value)) { log.error("Parameter " + key + " has a different value ( " + val + ") to the default shipped with this version of " + "JBM (" + value + "). " + "There is rarely a valid reason to change this parameter value. " + "If you are using ServiceBindingManager to supply the remoting configuration you should check " + "that the parameter value specified there exactly matches the value in the configuration supplied with JBM. " + "This connection factory will now not deploy. To override these checks set 'disableRemotingChecks' to " + "true on the connection factory. Only do this if you are absolutely sure you know the consequences."); return false; } else { return true; } } // Inner classes -------------------------------------------------------------------------------- }
true
true
public synchronized void startService() throws Exception { try { log.debug(this + " starting"); started = true; if (connectorObjectName == null) { throw new IllegalArgumentException("A Connector must be specified for " + "each Connection Factory"); } if (serverPeerObjectName == null) { throw new IllegalArgumentException("ServerPeer must be specified for " + "each Connection Factory"); } String locatorURI = (String)JMXAccessor.getJMXAttributeOverSecurity(server, connectorObjectName, "InvokerLocator"); ServerPeer serverPeer = (ServerPeer)JMXAccessor.getJMXAttributeOverSecurity(server, serverPeerObjectName, "Instance"); if (!serverPeer.isSupportsFailover()) { this.supportsFailover = false; } InvokerLocator locator = new InvokerLocator(locatorURI); String protocol = locator.getProtocol(); if (!disableRemotingChecks && (protocol.equals("bisocket") || protocol.equals("sslbisocket"))) { //Sanity check - If users are using the AS Service Binding Manager to provide the remoting connector //configuration, it is quite easy for them to end up using an old version depending on what version on //the AS they are running in - e.g. if they have forgotten to update it. //This can lead to subtle errors - therefore we do a sanity check by checking the existence of some properties //which should always be there Map params = locator.getParameters(); //The "compulsory" parameters boolean cont = checkParam(params, "marshaller", "org.jboss.jms.wireformat.JMSWireFormat") && checkParam(params, "unmarshaller", "org.jboss.jms.wireformat.JMSWireFormat") && checkParam(params, "dataType", "jms") && checkParam(params, "timeout", "0") && checkParam(params, "clientSocketClass", "org.jboss.jms.client.remoting.ClientSocketWrapper") && checkParam(params, "serverSocketClass", "org.jboss.jms.server.remoting.ServerSocketWrapper") && checkParam(params, "numberOfCallRetries", "1") && checkParam(params, "pingFrequency", "214748364") && checkParam(params, "pingWindowFactor", "10"); if (!cont) { throw new IllegalArgumentException("Failed to deploy connection factory since remoting configuration seems incorrect."); } String val = (String)params.get("clientLeasePeriod"); if (val != null) { int i = Integer.parseInt(val); if (i < 5000) { log.warn("Value of clientLeasePeriod at " + i + " seems low. Normal values are >= 5000"); } } val = (String)params.get("clientMaxPoolSize"); if (val != null) { int i = Integer.parseInt(val); if (i < 50) { log.warn("Value of clientMaxPoolSize at " + i + " seems low. Normal values are >= 50"); } } } connectionFactoryManager = serverPeer.getConnectionFactoryManager(); connectorManager = serverPeer.getConnectorManager(); connectionManager = serverPeer.getConnectionManager(); int refCount = connectorManager.registerConnector(connectorObjectName.getCanonicalName()); long leasePeriod = (Long)JMXAccessor.getJMXAttributeOverSecurity(server, connectorObjectName, "LeasePeriod"); // if leasePeriod <= 0, disable pinging altogether boolean enablePing = leasePeriod > 0; if (refCount == 1 && enablePing) { // TODO Something is not quite right here, we can detect failure even if pinging is not // enabled, for example if we try to send a callback to the client and sending the // calback fails // install the connection listener that listens for failed connections server.invoke(connectorObjectName, "addConnectionListener", new Object[] {connectionManager}, new String[] {"org.jboss.remoting.ConnectionListener"}); } // We use the MBean service name to uniquely identify the connection factory connectionFactoryManager. registerConnectionFactory(getServiceName().getCanonicalName(), clientID, jndiBindings, locatorURI, enablePing, prefetchSize, slowConsumers, defaultTempQueueFullSize, defaultTempQueuePageSize, defaultTempQueueDownCacheSize, dupsOKBatchSize, supportsFailover, supportsLoadBalancing, loadBalancingFactory, strictTck); String info = "Connector " + locator.getProtocol() + "://" + locator.getHost() + ":" + locator.getPort(); if (enablePing) { info += " has leasing enabled, lease period " + leasePeriod + " milliseconds"; } else { info += " has lease disabled"; } log.info(info); log.info(this + " started"); } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } }
public synchronized void startService() throws Exception { try { log.debug(this + " starting"); started = true; if (connectorObjectName == null) { throw new IllegalArgumentException("A Connector must be specified for " + "each Connection Factory"); } if (serverPeerObjectName == null) { throw new IllegalArgumentException("ServerPeer must be specified for " + "each Connection Factory"); } String locatorURI = (String)JMXAccessor.getJMXAttributeOverSecurity(server, connectorObjectName, "InvokerLocator"); ServerPeer serverPeer = (ServerPeer)JMXAccessor.getJMXAttributeOverSecurity(server, serverPeerObjectName, "Instance"); if (!serverPeer.isSupportsFailover()) { this.supportsFailover = false; } InvokerLocator locator = new InvokerLocator(locatorURI); String protocol = locator.getProtocol(); if (!disableRemotingChecks && (protocol.equals("bisocket") || protocol.equals("sslbisocket"))) { //Sanity check - If users are using the AS Service Binding Manager to provide the remoting connector //configuration, it is quite easy for them to end up using an old version depending on what version on //the AS they are running in - e.g. if they have forgotten to update it. //This can lead to subtle errors - therefore we do a sanity check by checking the existence of some properties //which should always be there Map params = locator.getParameters(); //The "compulsory" parameters boolean cont = checkParam(params, "marshaller", "org.jboss.jms.wireformat.JMSWireFormat") && checkParam(params, "unmarshaller", "org.jboss.jms.wireformat.JMSWireFormat") && checkParam(params, "dataType", "jms") && checkParam(params, "timeout", "0") && checkParam(params, "clientSocketClass", "org.jboss.jms.client.remoting.ClientSocketWrapper") && checkParam(params, "numberOfCallRetries", "1") && checkParam(params, "pingFrequency", "214748364") && checkParam(params, "pingWindowFactor", "10"); if (!cont) { throw new IllegalArgumentException("Failed to deploy connection factory since remoting configuration seems incorrect."); } String val = (String)params.get("clientLeasePeriod"); if (val != null) { int i = Integer.parseInt(val); if (i < 5000) { log.warn("Value of clientLeasePeriod at " + i + " seems low. Normal values are >= 5000"); } } val = (String)params.get("clientMaxPoolSize"); if (val != null) { int i = Integer.parseInt(val); if (i < 50) { log.warn("Value of clientMaxPoolSize at " + i + " seems low. Normal values are >= 50"); } } } connectionFactoryManager = serverPeer.getConnectionFactoryManager(); connectorManager = serverPeer.getConnectorManager(); connectionManager = serverPeer.getConnectionManager(); int refCount = connectorManager.registerConnector(connectorObjectName.getCanonicalName()); long leasePeriod = (Long)JMXAccessor.getJMXAttributeOverSecurity(server, connectorObjectName, "LeasePeriod"); // if leasePeriod <= 0, disable pinging altogether boolean enablePing = leasePeriod > 0; if (refCount == 1 && enablePing) { // TODO Something is not quite right here, we can detect failure even if pinging is not // enabled, for example if we try to send a callback to the client and sending the // calback fails // install the connection listener that listens for failed connections server.invoke(connectorObjectName, "addConnectionListener", new Object[] {connectionManager}, new String[] {"org.jboss.remoting.ConnectionListener"}); } // We use the MBean service name to uniquely identify the connection factory connectionFactoryManager. registerConnectionFactory(getServiceName().getCanonicalName(), clientID, jndiBindings, locatorURI, enablePing, prefetchSize, slowConsumers, defaultTempQueueFullSize, defaultTempQueuePageSize, defaultTempQueueDownCacheSize, dupsOKBatchSize, supportsFailover, supportsLoadBalancing, loadBalancingFactory, strictTck); String info = "Connector " + locator.getProtocol() + "://" + locator.getHost() + ":" + locator.getPort(); if (enablePing) { info += " has leasing enabled, lease period " + leasePeriod + " milliseconds"; } else { info += " has lease disabled"; } log.info(info); log.info(this + " started"); } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } }
diff --git a/plugin-manager/src/main/java/org/orbisgis/pluginManager/ui/SaveFilePanel.java b/plugin-manager/src/main/java/org/orbisgis/pluginManager/ui/SaveFilePanel.java index 78b4c7237..4a7d5d8f0 100644 --- a/plugin-manager/src/main/java/org/orbisgis/pluginManager/ui/SaveFilePanel.java +++ b/plugin-manager/src/main/java/org/orbisgis/pluginManager/ui/SaveFilePanel.java @@ -1,98 +1,98 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able * to manipulate and create vector and raster spatial information. OrbisGIS * is distributed under GPL 3 license. It is produced by the geo-informatic team of * the IRSTV Institute <http://www.irstv.cnrs.fr/>, CNRS FR 2488: * Erwan BOCHER, scientific researcher, * Thomas LEDUC, scientific researcher, * Fernando GONZALEZ CORTES, computer engineer. * * Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC * * This file is part of OrbisGIS. * * OrbisGIS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OrbisGIS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: * <http://orbisgis.cerma.archi.fr/> * <http://sourcesup.cru.fr/projects/orbisgis/> * * or contact directly: * erwan.bocher _at_ ec-nantes.fr * fergonco _at_ gmail.com * thomas.leduc _at_ cerma.archi.fr */ package org.orbisgis.pluginManager.ui; import java.io.File; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import javax.swing.plaf.FileChooserUI; import javax.swing.plaf.basic.BasicFileChooserUI; public class SaveFilePanel extends OpenFilePanel { public SaveFilePanel(String id, String title) { super(id, title); getFileChooser().setDialogType(JFileChooser.SAVE_DIALOG); } @Override public File getSelectedFile() { File ret; JFileChooser fc = getFileChooser(); FileChooserUI ui = fc.getUI(); if (ui instanceof BasicFileChooserUI) { BasicFileChooserUI basicUI = (BasicFileChooserUI) ui; String fileName = basicUI.getFileName(); if ((fileName == null) || (fileName.length() == 0)) { ret = null; } else { ret = autoComplete(new File(fileName)); } } else { ret = autoComplete(super.getSelectedFile()); } - if (!ret.isAbsolute()) { + if ((ret != null) && !ret.isAbsolute()) { ret = new File(fc.getCurrentDirectory(), ret.getName()); } return ret; } private File autoComplete(File selectedFile) { FileFilter ff = getFileChooser().getFileFilter(); if (ff instanceof FormatFilter) { FormatFilter filter = (FormatFilter) ff; return filter.autoComplete(selectedFile); } else { return selectedFile; } } public String validateInput() { File file = getSelectedFile(); if (file == null) { return "A file must be specified"; } else { return null; } } @Override public File[] getSelectedFiles() { return new File[] { getSelectedFile() }; } }
true
true
public File getSelectedFile() { File ret; JFileChooser fc = getFileChooser(); FileChooserUI ui = fc.getUI(); if (ui instanceof BasicFileChooserUI) { BasicFileChooserUI basicUI = (BasicFileChooserUI) ui; String fileName = basicUI.getFileName(); if ((fileName == null) || (fileName.length() == 0)) { ret = null; } else { ret = autoComplete(new File(fileName)); } } else { ret = autoComplete(super.getSelectedFile()); } if (!ret.isAbsolute()) { ret = new File(fc.getCurrentDirectory(), ret.getName()); } return ret; }
public File getSelectedFile() { File ret; JFileChooser fc = getFileChooser(); FileChooserUI ui = fc.getUI(); if (ui instanceof BasicFileChooserUI) { BasicFileChooserUI basicUI = (BasicFileChooserUI) ui; String fileName = basicUI.getFileName(); if ((fileName == null) || (fileName.length() == 0)) { ret = null; } else { ret = autoComplete(new File(fileName)); } } else { ret = autoComplete(super.getSelectedFile()); } if ((ret != null) && !ret.isAbsolute()) { ret = new File(fc.getCurrentDirectory(), ret.getName()); } return ret; }
diff --git a/j--/src/jminusminus/Scanner.java b/j--/src/jminusminus/Scanner.java index c73a588..9ac5f9d 100644 --- a/j--/src/jminusminus/Scanner.java +++ b/j--/src/jminusminus/Scanner.java @@ -1,540 +1,538 @@ // Copyright 2013 Bill Campbell, Swami Iyer and Bahar Akbal-Delibas package jminusminus; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.Hashtable; import static jminusminus.TokenKind.*; /** * A lexical analyzer for j--, that has no backtracking mechanism. * * When you add a new token to the scanner, you must also add an entry in the * TokenKind enum in TokenInfo.java specifying the kind and image of the new * token. */ class Scanner { /** End of file character. */ public final static char EOFCH = CharReader.EOFCH; /** Keywords in j--. */ private Hashtable<String, TokenKind> reserved; /** Source characters. */ private CharReader input; /** Next unscanned character. */ private char ch; /** Whether a scanner error has been found. */ private boolean isInError; /** Source file name. */ private String fileName; /** Line number of current token. */ private int line; /** * Construct a Scanner object. * * @param fileName * the name of the file containing the source. * @exception FileNotFoundException * when the named file cannot be found. */ public Scanner(String fileName) throws FileNotFoundException { this.input = new CharReader(fileName); this.fileName = fileName; isInError = false; // Keywords in j-- reserved = new Hashtable<String, TokenKind>(); reserved.put(ABSTRACT.image(), ABSTRACT); reserved.put(BOOLEAN.image(), BOOLEAN); reserved.put(CHAR.image(), CHAR); reserved.put(CLASS.image(), CLASS); reserved.put(ELSE.image(), ELSE); reserved.put(EXTENDS.image(), EXTENDS); reserved.put(FALSE.image(), FALSE); reserved.put(IF.image(), IF); reserved.put(IMPORT.image(), IMPORT); reserved.put(INSTANCEOF.image(), INSTANCEOF); reserved.put(INT.image(), INT); reserved.put(NEW.image(), NEW); reserved.put(NULL.image(), NULL); reserved.put(PACKAGE.image(), PACKAGE); reserved.put(PRIVATE.image(), PRIVATE); reserved.put(PROTECTED.image(), PROTECTED); reserved.put(PUBLIC.image(), PUBLIC); reserved.put(RETURN.image(), RETURN); reserved.put(STATIC.image(), STATIC); reserved.put(SUPER.image(), SUPER); reserved.put(THIS.image(), THIS); reserved.put(TRUE.image(), TRUE); reserved.put(VOID.image(), VOID); reserved.put(WHILE.image(), WHILE); // Prime the pump. nextCh(); } /** * Scan the next token from input. * * @return the the next scanned token. */ public TokenInfo getNextToken() { StringBuffer buffer; boolean moreWhiteSpace = true; while (moreWhiteSpace) { while (isWhitespace(ch)) { nextCh(); } if (ch == '/') { nextCh(); if (ch == '/') { // CharReader maps all new lines to '\n' while (ch != '\n' && ch != EOFCH) { nextCh(); } } else if (ch == '*') { // Skip multilines comments nextCh(); boolean commentOn = true; while( ch != EOFCH && commentOn) { nextCh(); if( ch == '*') { nextCh(); if( ch == '/') { commentOn = false; } } } } else { return new TokenInfo(DIV, line); } } else { moreWhiteSpace = false; } if (ch == '%') { nextCh(); if (ch == '%') { // CharReader maps all new lines to '\n' while (ch != '\n' && ch != EOFCH) { nextCh(); } } else { return new TokenInfo(MOD, line); } - } else { - moreWhiteSpace = false; - } + } } line = input.line(); switch (ch) { case '(': nextCh(); return new TokenInfo(LPAREN, line); case ')': nextCh(); return new TokenInfo(RPAREN, line); case '{': nextCh(); return new TokenInfo(LCURLY, line); case '}': nextCh(); return new TokenInfo(RCURLY, line); case '[': nextCh(); return new TokenInfo(LBRACK, line); case ']': nextCh(); return new TokenInfo(RBRACK, line); case ';': nextCh(); return new TokenInfo(SEMI, line); case ',': nextCh(); return new TokenInfo(COMMA, line); case '=': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(EQUAL, line); } else { return new TokenInfo(ASSIGN, line); } case '!': nextCh(); return new TokenInfo(LNOT, line); case '*': nextCh(); return new TokenInfo(STAR, line); case '+': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(PLUS_ASSIGN, line); } else if (ch == '+') { nextCh(); return new TokenInfo(INC, line); } else { return new TokenInfo(PLUS, line); } case '-': nextCh(); if (ch == '-') { nextCh(); return new TokenInfo(DEC, line); } else { return new TokenInfo(MINUS, line); } case '&': nextCh(); if (ch == '&') { nextCh(); return new TokenInfo(LAND, line); } else { reportScannerError("Operator & is not supported in j--."); return getNextToken(); } case '>': nextCh(); return new TokenInfo(GT, line); case '<': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(LE, line); } else { reportScannerError("Operator < is not supported in j--."); return getNextToken(); } case '\'': buffer = new StringBuffer(); buffer.append('\''); nextCh(); if (ch == '\\') { nextCh(); buffer.append(escape()); } else { buffer.append(ch); nextCh(); } if (ch == '\'') { buffer.append('\''); nextCh(); return new TokenInfo(CHAR_LITERAL, buffer.toString(), line); } else { // Expected a ' ; report error and try to // recover. reportScannerError(ch + " found by scanner where closing ' was expected."); while (ch != '\'' && ch != ';' && ch != '\n') { nextCh(); } return new TokenInfo(CHAR_LITERAL, buffer.toString(), line); } case '"': buffer = new StringBuffer(); buffer.append("\""); nextCh(); while (ch != '"' && ch != '\n' && ch != EOFCH) { if (ch == '\\') { nextCh(); buffer.append(escape()); } else { buffer.append(ch); nextCh(); } } if (ch == '\n') { reportScannerError("Unexpected end of line found in String"); } else if (ch == EOFCH) { reportScannerError("Unexpected end of file found in String"); } else { // Scan the closing " nextCh(); buffer.append("\""); } return new TokenInfo(STRING_LITERAL, buffer.toString(), line); case '.': nextCh(); return new TokenInfo(DOT, line); case EOFCH: return new TokenInfo(EOF, line); case '0': // Handle only simple decimal integers for now. nextCh(); return new TokenInfo(INT_LITERAL, "0", line); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = new StringBuffer(); while (isDigit(ch)) { buffer.append(ch); nextCh(); } return new TokenInfo(INT_LITERAL, buffer.toString(), line); default: if (isIdentifierStart(ch)) { buffer = new StringBuffer(); while (isIdentifierPart(ch)) { buffer.append(ch); nextCh(); } String identifier = buffer.toString(); if (reserved.containsKey(identifier)) { return new TokenInfo(reserved.get(identifier), line); } else { return new TokenInfo(IDENTIFIER, identifier, line); } } else { reportScannerError("Unidentified input token: '%c'", ch); nextCh(); return getNextToken(); } } } /** * Scan and return an escaped character. * * @return escaped character. */ private String escape() { switch (ch) { case 'b': nextCh(); return "\\b"; case 't': nextCh(); return "\\t"; case 'n': nextCh(); return "\\n"; case 'f': nextCh(); return "\\f"; case 'r': nextCh(); return "\\r"; case '"': nextCh(); return "\""; case '\'': nextCh(); return "\\'"; case '\\': nextCh(); return "\\\\"; default: reportScannerError("Badly formed escape: \\%c", ch); nextCh(); return ""; } } /** * Advance ch to the next character from input, and update the line number. */ private void nextCh() { line = input.line(); try { ch = input.nextChar(); } catch (Exception e) { reportScannerError("Unable to read characters from input"); } } /** * Report a lexcial error and record the fact that an error has occured. * This fact can be ascertained from the Scanner by sending it an * errorHasOccurred() message. * * @param message * message identifying the error. * @param args * related values. */ private void reportScannerError(String message, Object... args) { isInError = true; System.err.printf("%s:%d: ", fileName, line); System.err.printf(message, args); System.err.println(); } /** * Return true if the specified character is a digit (0-9); false otherwise. * * @param c * character. * @return true or false. */ private boolean isDigit(char c) { return (c >= '0' && c <= '9'); } /** * Return true if the specified character is a whitespace; false otherwise. * * @param c * character. * @return true or false. */ private boolean isWhitespace(char c) { switch (c) { case ' ': case '\t': case '\n': // CharReader maps all new lines to '\n' case '\f': return true; } return false; } /** * Return true if the specified character can start an identifier name; * false otherwise. * * @param c * character. * @return true or false. */ private boolean isIdentifierStart(char c) { return (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' || c == '$'); } /** * Return true if the specified character can be part of an identifier name; * false otherwise. * * @param c * character. * @return true or false. */ private boolean isIdentifierPart(char c) { return (isIdentifierStart(c) || isDigit(c)); } /** * Has an error occurred up to now in lexical analysis? * * @return true or false. */ public boolean errorHasOccurred() { return isInError; } /** * The name of the source file. * * @return name of the source file. */ public String fileName() { return fileName; } } /** * A buffered character reader. Abstracts out differences between platforms, * mapping all new lines to '\n'. Also, keeps track of line numbers where the * first line is numbered 1. */ class CharReader { /** A representation of the end of file as a character. */ public final static char EOFCH = (char) -1; /** The underlying reader records line numbers. */ private LineNumberReader lineNumberReader; /** Name of the file that is being read. */ private String fileName; /** * Construct a CharReader from a file name. * * @param fileName * the name of the input file. * @exception FileNotFoundException * if the file is not found. */ public CharReader(String fileName) throws FileNotFoundException { lineNumberReader = new LineNumberReader(new FileReader(fileName)); this.fileName = fileName; } /** * Scan the next character. * * @return the character scanned. * @exception IOException * if an I/O error occurs. */ public char nextChar() throws IOException { return (char) lineNumberReader.read(); } /** * The current line number in the source file, starting at 1. * * @return the current line number. */ public int line() { // LineNumberReader counts lines from 0. return lineNumberReader.getLineNumber() + 1; } /** * Return the file name. * * @return the file name. */ public String fileName() { return fileName; } /** * Close the file. * * @exception IOException * if an I/O error occurs. */ public void close() throws IOException { lineNumberReader.close(); } }
true
true
public TokenInfo getNextToken() { StringBuffer buffer; boolean moreWhiteSpace = true; while (moreWhiteSpace) { while (isWhitespace(ch)) { nextCh(); } if (ch == '/') { nextCh(); if (ch == '/') { // CharReader maps all new lines to '\n' while (ch != '\n' && ch != EOFCH) { nextCh(); } } else if (ch == '*') { // Skip multilines comments nextCh(); boolean commentOn = true; while( ch != EOFCH && commentOn) { nextCh(); if( ch == '*') { nextCh(); if( ch == '/') { commentOn = false; } } } } else { return new TokenInfo(DIV, line); } } else { moreWhiteSpace = false; } if (ch == '%') { nextCh(); if (ch == '%') { // CharReader maps all new lines to '\n' while (ch != '\n' && ch != EOFCH) { nextCh(); } } else { return new TokenInfo(MOD, line); } } else { moreWhiteSpace = false; } } line = input.line(); switch (ch) { case '(': nextCh(); return new TokenInfo(LPAREN, line); case ')': nextCh(); return new TokenInfo(RPAREN, line); case '{': nextCh(); return new TokenInfo(LCURLY, line); case '}': nextCh(); return new TokenInfo(RCURLY, line); case '[': nextCh(); return new TokenInfo(LBRACK, line); case ']': nextCh(); return new TokenInfo(RBRACK, line); case ';': nextCh(); return new TokenInfo(SEMI, line); case ',': nextCh(); return new TokenInfo(COMMA, line); case '=': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(EQUAL, line); } else { return new TokenInfo(ASSIGN, line); } case '!': nextCh(); return new TokenInfo(LNOT, line); case '*': nextCh(); return new TokenInfo(STAR, line); case '+': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(PLUS_ASSIGN, line); } else if (ch == '+') { nextCh(); return new TokenInfo(INC, line); } else { return new TokenInfo(PLUS, line); } case '-': nextCh(); if (ch == '-') { nextCh(); return new TokenInfo(DEC, line); } else { return new TokenInfo(MINUS, line); } case '&': nextCh(); if (ch == '&') { nextCh(); return new TokenInfo(LAND, line); } else { reportScannerError("Operator & is not supported in j--."); return getNextToken(); } case '>': nextCh(); return new TokenInfo(GT, line); case '<': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(LE, line); } else { reportScannerError("Operator < is not supported in j--."); return getNextToken(); } case '\'': buffer = new StringBuffer(); buffer.append('\''); nextCh(); if (ch == '\\') { nextCh(); buffer.append(escape()); } else { buffer.append(ch); nextCh(); } if (ch == '\'') { buffer.append('\''); nextCh(); return new TokenInfo(CHAR_LITERAL, buffer.toString(), line); } else { // Expected a ' ; report error and try to // recover. reportScannerError(ch + " found by scanner where closing ' was expected."); while (ch != '\'' && ch != ';' && ch != '\n') { nextCh(); } return new TokenInfo(CHAR_LITERAL, buffer.toString(), line); } case '"': buffer = new StringBuffer(); buffer.append("\""); nextCh(); while (ch != '"' && ch != '\n' && ch != EOFCH) { if (ch == '\\') { nextCh(); buffer.append(escape()); } else { buffer.append(ch); nextCh(); } } if (ch == '\n') { reportScannerError("Unexpected end of line found in String"); } else if (ch == EOFCH) { reportScannerError("Unexpected end of file found in String"); } else { // Scan the closing " nextCh(); buffer.append("\""); } return new TokenInfo(STRING_LITERAL, buffer.toString(), line); case '.': nextCh(); return new TokenInfo(DOT, line); case EOFCH: return new TokenInfo(EOF, line); case '0': // Handle only simple decimal integers for now. nextCh(); return new TokenInfo(INT_LITERAL, "0", line); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = new StringBuffer(); while (isDigit(ch)) { buffer.append(ch); nextCh(); } return new TokenInfo(INT_LITERAL, buffer.toString(), line); default: if (isIdentifierStart(ch)) { buffer = new StringBuffer(); while (isIdentifierPart(ch)) { buffer.append(ch); nextCh(); } String identifier = buffer.toString(); if (reserved.containsKey(identifier)) { return new TokenInfo(reserved.get(identifier), line); } else { return new TokenInfo(IDENTIFIER, identifier, line); } } else { reportScannerError("Unidentified input token: '%c'", ch); nextCh(); return getNextToken(); } } }
public TokenInfo getNextToken() { StringBuffer buffer; boolean moreWhiteSpace = true; while (moreWhiteSpace) { while (isWhitespace(ch)) { nextCh(); } if (ch == '/') { nextCh(); if (ch == '/') { // CharReader maps all new lines to '\n' while (ch != '\n' && ch != EOFCH) { nextCh(); } } else if (ch == '*') { // Skip multilines comments nextCh(); boolean commentOn = true; while( ch != EOFCH && commentOn) { nextCh(); if( ch == '*') { nextCh(); if( ch == '/') { commentOn = false; } } } } else { return new TokenInfo(DIV, line); } } else { moreWhiteSpace = false; } if (ch == '%') { nextCh(); if (ch == '%') { // CharReader maps all new lines to '\n' while (ch != '\n' && ch != EOFCH) { nextCh(); } } else { return new TokenInfo(MOD, line); } } } line = input.line(); switch (ch) { case '(': nextCh(); return new TokenInfo(LPAREN, line); case ')': nextCh(); return new TokenInfo(RPAREN, line); case '{': nextCh(); return new TokenInfo(LCURLY, line); case '}': nextCh(); return new TokenInfo(RCURLY, line); case '[': nextCh(); return new TokenInfo(LBRACK, line); case ']': nextCh(); return new TokenInfo(RBRACK, line); case ';': nextCh(); return new TokenInfo(SEMI, line); case ',': nextCh(); return new TokenInfo(COMMA, line); case '=': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(EQUAL, line); } else { return new TokenInfo(ASSIGN, line); } case '!': nextCh(); return new TokenInfo(LNOT, line); case '*': nextCh(); return new TokenInfo(STAR, line); case '+': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(PLUS_ASSIGN, line); } else if (ch == '+') { nextCh(); return new TokenInfo(INC, line); } else { return new TokenInfo(PLUS, line); } case '-': nextCh(); if (ch == '-') { nextCh(); return new TokenInfo(DEC, line); } else { return new TokenInfo(MINUS, line); } case '&': nextCh(); if (ch == '&') { nextCh(); return new TokenInfo(LAND, line); } else { reportScannerError("Operator & is not supported in j--."); return getNextToken(); } case '>': nextCh(); return new TokenInfo(GT, line); case '<': nextCh(); if (ch == '=') { nextCh(); return new TokenInfo(LE, line); } else { reportScannerError("Operator < is not supported in j--."); return getNextToken(); } case '\'': buffer = new StringBuffer(); buffer.append('\''); nextCh(); if (ch == '\\') { nextCh(); buffer.append(escape()); } else { buffer.append(ch); nextCh(); } if (ch == '\'') { buffer.append('\''); nextCh(); return new TokenInfo(CHAR_LITERAL, buffer.toString(), line); } else { // Expected a ' ; report error and try to // recover. reportScannerError(ch + " found by scanner where closing ' was expected."); while (ch != '\'' && ch != ';' && ch != '\n') { nextCh(); } return new TokenInfo(CHAR_LITERAL, buffer.toString(), line); } case '"': buffer = new StringBuffer(); buffer.append("\""); nextCh(); while (ch != '"' && ch != '\n' && ch != EOFCH) { if (ch == '\\') { nextCh(); buffer.append(escape()); } else { buffer.append(ch); nextCh(); } } if (ch == '\n') { reportScannerError("Unexpected end of line found in String"); } else if (ch == EOFCH) { reportScannerError("Unexpected end of file found in String"); } else { // Scan the closing " nextCh(); buffer.append("\""); } return new TokenInfo(STRING_LITERAL, buffer.toString(), line); case '.': nextCh(); return new TokenInfo(DOT, line); case EOFCH: return new TokenInfo(EOF, line); case '0': // Handle only simple decimal integers for now. nextCh(); return new TokenInfo(INT_LITERAL, "0", line); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = new StringBuffer(); while (isDigit(ch)) { buffer.append(ch); nextCh(); } return new TokenInfo(INT_LITERAL, buffer.toString(), line); default: if (isIdentifierStart(ch)) { buffer = new StringBuffer(); while (isIdentifierPart(ch)) { buffer.append(ch); nextCh(); } String identifier = buffer.toString(); if (reserved.containsKey(identifier)) { return new TokenInfo(reserved.get(identifier), line); } else { return new TokenInfo(IDENTIFIER, identifier, line); } } else { reportScannerError("Unidentified input token: '%c'", ch); nextCh(); return getNextToken(); } } }
diff --git a/src/main/java/io/qdb/server/databind/DataBinder.java b/src/main/java/io/qdb/server/databind/DataBinder.java index af949b6..fea06a5 100644 --- a/src/main/java/io/qdb/server/databind/DataBinder.java +++ b/src/main/java/io/qdb/server/databind/DataBinder.java @@ -1,101 +1,111 @@ package io.qdb.server.databind; import io.qdb.server.controller.JsonService; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; /** * Binds keys and values from a map to objects. Accumulates errors. */ public class DataBinder { private final JsonService jsonService; private boolean ignoreInvalidFields; private boolean updateMap; private Map<String, String> errors; public DataBinder(JsonService jsonService) { this.jsonService = jsonService; } public DataBinder ignoreInvalidFields(boolean on) { this.ignoreInvalidFields = on; return this; } public DataBinder updateMap(boolean on) { this.updateMap = on; return this; } /** * Bind the values of map to matching public field names from dto. Support basic data types and does conversions * from String to these types. If dto implements {@link HasAnySetter} the keys from the map that do not match * field names are passed to {@link HasAnySetter#set(String, Object)}. */ @SuppressWarnings("unchecked") public DataBinder bind(Map map, Object dto) { Class<?> cls = dto.getClass(); for (Object o : map.entrySet()) { Map.Entry e = (Map.Entry)o; String key = (String)e.getKey(); Object v = e.getValue(); Field f; try { f = cls.getField(key); } catch (NoSuchFieldException x) { if (dto instanceof HasAnySetter) { ((HasAnySetter)dto).set(key, v); } else if (!ignoreInvalidFields) { error(key, "Unknown field"); } continue; } - Class t; - if (v instanceof String && (t = f.getType()) != String.class) { + Class t = f.getType(); + if (v instanceof String && t != String.class) { String s = (String)v; try { if (t == Integer.TYPE || t == Integer.class) v = IntegerParser.INSTANCE.parseInt(s); else if (t == Long.TYPE || t == Long.class) v = IntegerParser.INSTANCE.parseLong(s); else if (t == Boolean.TYPE || t == Boolean.class) v = "true".equals(v); else if (t == Date.class) v = DateTimeParser.INSTANCE.parse(s); else if (t == String[].class) v = parseStringArray(s); } catch (Exception x) { error(key, "Invalid value, expected " + t.getSimpleName() + ": [" + v + "]"); continue; } if (updateMap) map.put(key, v); + } else if (t.isArray() && v != null) { + Class vt = v.getClass(); + if (vt.isArray() && vt.getComponentType() == Object.class) { + if (t.getComponentType() == String.class) { + Object[] va = (Object[])v; + String[] sa = new String[va.length]; + for (int i = 0; i < va.length; i++) sa[i] = (String)va[i]; + v = sa; + } + } } try { f.set(dto, v); } catch (Exception x) { error(key, "Invalid value, expected " + f.getType().getSimpleName() + ": [" + v + "]"); } } return this; } private String[] parseStringArray(String s) throws IOException { if (s.length() == 0) return new String[0]; if (s.charAt(0) == '[') return jsonService.fromJson(new ByteArrayInputStream(s.getBytes("UTF8")), String[].class); return s.split("[/s]*,[/s]*"); } private void error(String field, String message) { if (errors == null) errors = new LinkedHashMap<String, String>(); errors.put(field, message); } /** * If there are any errors throw a {@link DataBindingException}. */ public void check() throws DataBindingException { if (errors != null) throw new DataBindingException(errors); } }
false
true
public DataBinder bind(Map map, Object dto) { Class<?> cls = dto.getClass(); for (Object o : map.entrySet()) { Map.Entry e = (Map.Entry)o; String key = (String)e.getKey(); Object v = e.getValue(); Field f; try { f = cls.getField(key); } catch (NoSuchFieldException x) { if (dto instanceof HasAnySetter) { ((HasAnySetter)dto).set(key, v); } else if (!ignoreInvalidFields) { error(key, "Unknown field"); } continue; } Class t; if (v instanceof String && (t = f.getType()) != String.class) { String s = (String)v; try { if (t == Integer.TYPE || t == Integer.class) v = IntegerParser.INSTANCE.parseInt(s); else if (t == Long.TYPE || t == Long.class) v = IntegerParser.INSTANCE.parseLong(s); else if (t == Boolean.TYPE || t == Boolean.class) v = "true".equals(v); else if (t == Date.class) v = DateTimeParser.INSTANCE.parse(s); else if (t == String[].class) v = parseStringArray(s); } catch (Exception x) { error(key, "Invalid value, expected " + t.getSimpleName() + ": [" + v + "]"); continue; } if (updateMap) map.put(key, v); } try { f.set(dto, v); } catch (Exception x) { error(key, "Invalid value, expected " + f.getType().getSimpleName() + ": [" + v + "]"); } } return this; }
public DataBinder bind(Map map, Object dto) { Class<?> cls = dto.getClass(); for (Object o : map.entrySet()) { Map.Entry e = (Map.Entry)o; String key = (String)e.getKey(); Object v = e.getValue(); Field f; try { f = cls.getField(key); } catch (NoSuchFieldException x) { if (dto instanceof HasAnySetter) { ((HasAnySetter)dto).set(key, v); } else if (!ignoreInvalidFields) { error(key, "Unknown field"); } continue; } Class t = f.getType(); if (v instanceof String && t != String.class) { String s = (String)v; try { if (t == Integer.TYPE || t == Integer.class) v = IntegerParser.INSTANCE.parseInt(s); else if (t == Long.TYPE || t == Long.class) v = IntegerParser.INSTANCE.parseLong(s); else if (t == Boolean.TYPE || t == Boolean.class) v = "true".equals(v); else if (t == Date.class) v = DateTimeParser.INSTANCE.parse(s); else if (t == String[].class) v = parseStringArray(s); } catch (Exception x) { error(key, "Invalid value, expected " + t.getSimpleName() + ": [" + v + "]"); continue; } if (updateMap) map.put(key, v); } else if (t.isArray() && v != null) { Class vt = v.getClass(); if (vt.isArray() && vt.getComponentType() == Object.class) { if (t.getComponentType() == String.class) { Object[] va = (Object[])v; String[] sa = new String[va.length]; for (int i = 0; i < va.length; i++) sa[i] = (String)va[i]; v = sa; } } } try { f.set(dto, v); } catch (Exception x) { error(key, "Invalid value, expected " + f.getType().getSimpleName() + ": [" + v + "]"); } } return this; }
diff --git a/src/cs4120/der34dlc287lg342/xi/Driver.java b/src/cs4120/der34dlc287lg342/xi/Driver.java index fafb79d..1e21cbc 100644 --- a/src/cs4120/der34dlc287lg342/xi/Driver.java +++ b/src/cs4120/der34dlc287lg342/xi/Driver.java @@ -1,97 +1,98 @@ package cs4120.der34dlc287lg342.xi; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import cs4120.der34dlc287lg342.xi.ast.AbstractSyntaxTree; import cs4120.der34dlc287lg342.xi.ir.Seq; import cs4120.der34dlc287lg342.xi.ir.context.IRContextStack; import cs4120.der34dlc287lg342.xi.ir.context.InvalidIRContextException; import cs4120.der34dlc287lg342.xi.ir.translate.ConstantFolding; import cs4120.der34dlc287lg342.xi.ir.translate.IRTranslation; import cs4120.der34dlc287lg342.xi.ir.translate.LowerCjump; import cs4120.der34dlc287lg342.xi.typechecker.InvalidXiTypeException; import cs4120.der34dlc287lg342.xi.typechecker.XiTypechecker; import edu.cornell.cs.cs4120.xi.AbstractSyntaxNode; import edu.cornell.cs.cs4120.xi.CompilationException; import edu.cornell.cs.cs4120.xi.parser.Parser; public class Driver { public static void main(String[] args){ AbstractSyntaxTree.PA3 = false; boolean PA4 = false; boolean optimization = true; String file = null; for (String arg : args){ if (arg.equals("--dump_ast")){ AbstractSyntaxTree.PA3 = true; } else if (arg.equals("--dump_ir")){ PA4 = true; } else if (arg.equals("-O")){ optimization = false; } else { if (file == null) file = arg; else System.out.println("Ignoring extraneous argument: "+arg); } } if ((!AbstractSyntaxTree.PA3 && !PA4) || file == null){ System.out.println("Usage: java -jar Driver.jar [-O] [--dump_ast | --dump_ir] sourcefile.xi"); return; } try { FileReader reader = new FileReader(file); String src = ""; BufferedReader input = new BufferedReader(reader); String line = null; while (( line = input.readLine()) != null){ src += line + "\n"; } - Parser parser = new XiParser(new StringReader(src), args[0]); + Parser parser = new XiParser(new StringReader(src), file); AbstractSyntaxNode program = parser.parse(); XiTypechecker tc = new XiTypechecker(program, src); tc.typecheck(); ((AbstractSyntaxTree)(tc.ast)).foldConstants(); if (AbstractSyntaxTree.PA3){ System.out.println("Printing out the AST\n"); TypeAnnotatedTreePrinter printer = new TypeAnnotatedTreePrinter(System.out); printer.print(program); } if (PA4){ System.out.println("Printing out the IR code\n"); IRTranslation tr = ((AbstractSyntaxTree)tc.ast).to_ir(new IRContextStack()); Seq program_ir = tr.stmt().lower(); LowerCjump lcj = new LowerCjump(program_ir); program_ir = lcj.translate(); if (optimization){ program_ir = ConstantFolding.foldConstants(program_ir); } System.out.println(program_ir.prettyPrint()); } reader.close(); } catch (CompilationException e){ System.out.println(e); } catch (FileNotFoundException e) { - System.out.println("File not found: "+args[0]); + e.printStackTrace(); + System.out.println("File not found: "+file); } catch (IOException e) { - System.out.println("Malformed file: "+args[0]); + System.out.println("Malformed file: "+file); } catch (InvalidXiTypeException e) { e.printStackTrace(); System.out.println(e); } catch (InvalidIRContextException e) { e.printStackTrace(); System.out.println(e); } } }
false
true
public static void main(String[] args){ AbstractSyntaxTree.PA3 = false; boolean PA4 = false; boolean optimization = true; String file = null; for (String arg : args){ if (arg.equals("--dump_ast")){ AbstractSyntaxTree.PA3 = true; } else if (arg.equals("--dump_ir")){ PA4 = true; } else if (arg.equals("-O")){ optimization = false; } else { if (file == null) file = arg; else System.out.println("Ignoring extraneous argument: "+arg); } } if ((!AbstractSyntaxTree.PA3 && !PA4) || file == null){ System.out.println("Usage: java -jar Driver.jar [-O] [--dump_ast | --dump_ir] sourcefile.xi"); return; } try { FileReader reader = new FileReader(file); String src = ""; BufferedReader input = new BufferedReader(reader); String line = null; while (( line = input.readLine()) != null){ src += line + "\n"; } Parser parser = new XiParser(new StringReader(src), args[0]); AbstractSyntaxNode program = parser.parse(); XiTypechecker tc = new XiTypechecker(program, src); tc.typecheck(); ((AbstractSyntaxTree)(tc.ast)).foldConstants(); if (AbstractSyntaxTree.PA3){ System.out.println("Printing out the AST\n"); TypeAnnotatedTreePrinter printer = new TypeAnnotatedTreePrinter(System.out); printer.print(program); } if (PA4){ System.out.println("Printing out the IR code\n"); IRTranslation tr = ((AbstractSyntaxTree)tc.ast).to_ir(new IRContextStack()); Seq program_ir = tr.stmt().lower(); LowerCjump lcj = new LowerCjump(program_ir); program_ir = lcj.translate(); if (optimization){ program_ir = ConstantFolding.foldConstants(program_ir); } System.out.println(program_ir.prettyPrint()); } reader.close(); } catch (CompilationException e){ System.out.println(e); } catch (FileNotFoundException e) { System.out.println("File not found: "+args[0]); } catch (IOException e) { System.out.println("Malformed file: "+args[0]); } catch (InvalidXiTypeException e) { e.printStackTrace(); System.out.println(e); } catch (InvalidIRContextException e) { e.printStackTrace(); System.out.println(e); } }
public static void main(String[] args){ AbstractSyntaxTree.PA3 = false; boolean PA4 = false; boolean optimization = true; String file = null; for (String arg : args){ if (arg.equals("--dump_ast")){ AbstractSyntaxTree.PA3 = true; } else if (arg.equals("--dump_ir")){ PA4 = true; } else if (arg.equals("-O")){ optimization = false; } else { if (file == null) file = arg; else System.out.println("Ignoring extraneous argument: "+arg); } } if ((!AbstractSyntaxTree.PA3 && !PA4) || file == null){ System.out.println("Usage: java -jar Driver.jar [-O] [--dump_ast | --dump_ir] sourcefile.xi"); return; } try { FileReader reader = new FileReader(file); String src = ""; BufferedReader input = new BufferedReader(reader); String line = null; while (( line = input.readLine()) != null){ src += line + "\n"; } Parser parser = new XiParser(new StringReader(src), file); AbstractSyntaxNode program = parser.parse(); XiTypechecker tc = new XiTypechecker(program, src); tc.typecheck(); ((AbstractSyntaxTree)(tc.ast)).foldConstants(); if (AbstractSyntaxTree.PA3){ System.out.println("Printing out the AST\n"); TypeAnnotatedTreePrinter printer = new TypeAnnotatedTreePrinter(System.out); printer.print(program); } if (PA4){ System.out.println("Printing out the IR code\n"); IRTranslation tr = ((AbstractSyntaxTree)tc.ast).to_ir(new IRContextStack()); Seq program_ir = tr.stmt().lower(); LowerCjump lcj = new LowerCjump(program_ir); program_ir = lcj.translate(); if (optimization){ program_ir = ConstantFolding.foldConstants(program_ir); } System.out.println(program_ir.prettyPrint()); } reader.close(); } catch (CompilationException e){ System.out.println(e); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("File not found: "+file); } catch (IOException e) { System.out.println("Malformed file: "+file); } catch (InvalidXiTypeException e) { e.printStackTrace(); System.out.println(e); } catch (InvalidIRContextException e) { e.printStackTrace(); System.out.println(e); } }
diff --git a/editor/server/src/de/hpi/epc2pn/PetriNetConverter.java b/editor/server/src/de/hpi/epc2pn/PetriNetConverter.java index 17559dec..6d8f3a83 100644 --- a/editor/server/src/de/hpi/epc2pn/PetriNetConverter.java +++ b/editor/server/src/de/hpi/epc2pn/PetriNetConverter.java @@ -1,214 +1,212 @@ /** * Copyright (c) 2009 Matthias Weidlich * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package de.hpi.epc2pn; import de.hpi.bpt.process.epc.Connection; import de.hpi.bpt.process.epc.Connector; import de.hpi.bpt.process.epc.ControlFlow; import de.hpi.bpt.process.epc.Event; import de.hpi.bpt.process.epc.FlowObject; import de.hpi.bpt.process.epc.Function; import de.hpi.bpt.process.epc.IEPC; import de.hpi.bpt.process.epc.IFlowObject; import de.hpi.bpt.process.epc.NonFlowObject; import de.hpi.bpt.process.epc.ProcessInterface; import de.hpi.petrinet.FlowRelationship; import de.hpi.petrinet.LabeledTransition; import de.hpi.petrinet.Node; import de.hpi.petrinet.PetriNet; import de.hpi.petrinet.PetriNetFactory; import de.hpi.petrinet.Place; import de.hpi.petrinet.Transition; /** * Converts an EPC into a Petri net. * * The EPC must NOT contain any OR connectors!!! * * Main method: convert() * * @author matthias.weidlich * */ public class PetriNetConverter { protected IEPC<ControlFlow, FlowObject, Event, Function, Connector, ProcessInterface, Connection, de.hpi.bpt.process.epc.Node, NonFlowObject> epc; protected PetriNetFactory pnfactory; public PetriNetConverter(IEPC<ControlFlow, FlowObject, Event, Function, Connector, ProcessInterface, Connection, de.hpi.bpt.process.epc.Node, NonFlowObject> epc, PetriNetFactory pnfactory) { this.epc = epc; this.pnfactory = pnfactory; } /** * Creates a Petri net transition representing the EPC function. * * @param net * @param function * @param conversion context capturing the relation between Petri net and EPC elements */ protected void handleFunction(PetriNet net, Function function, ConversionContext c) { LabeledTransition t = this.pnfactory.createLabeledTransition(); t.setId(function.getId()); t.setLabel(function.getName()); net.getTransitions().add(t); c.setAllConversionMaps(function, t); } /** * Creates a Petri net place representing the EPC event. * * @param net * @param event * @param conversion context capturing the relation between Petri net and EPC elements */ protected void handleEvent(PetriNet net, Event event, ConversionContext c) { Place p = this.pnfactory.createPlace(); p.setId(event.getId()); net.getPlaces().add(p); c.setAllConversionMaps(event, p); } /** * Handles control flow of the EPC. Additional places and transitions might * be created, if the corresponding Petri net elements cannot be connected right * away. * * @param net * @param controlflow * @param conversion context capturing the relation between Petri net and EPC elements */ protected void handleControlFlow(PetriNet net, ControlFlow f, ConversionContext c) { Node source = c.getConversionMapOut().get(f.getSource()); Node target = c.getConversionMapIn().get(f.getTarget()); /* * In certain cases the straight-forward mapping of a flow arc * between an XOR split (a place) and an AND join (a transition) * might result in non-free choice constructs, which are not semantically * correct and therefore have to be avoided. */ if (f.getSource() instanceof Connector && f.getTarget() instanceof Connector) { Connector src1 = (Connector) f.getSource(); Connector tar1 = (Connector) f.getTarget(); if (src1.isXOR() && tar1.isAND()) { Transition t = this.pnfactory.createSilentTransition(); t.setId("xor/and helper " + c.getId()); net.getTransitions().add(t); this.createFlowRelationship(net, source, t); connectTwoTransitions(net, t, target, "xor/and helper " + c.getId()); return; } } if ((source instanceof Place && target instanceof Transition) || (source instanceof Transition && target instanceof Place)) { - FlowRelationship flow = this.pnfactory.createFlowRelationship(); - flow.setSource(source); - flow.setTarget(target); + createFlowRelationship(net, source, target); } else if ((source instanceof Place && target instanceof Place)) { connectTwoPlaces(net, source, target, "helper transition " + c.getId() + f.toString()); } else if ((source instanceof Transition && target instanceof Transition)) { connectTwoTransitions(net, source, target, "helper place " + c.getId()); } } protected void createFlowRelationship(PetriNet net, Node src, Node tar) { FlowRelationship f = this.pnfactory.createFlowRelationship(); f.setSource(src); f.setTarget(tar); net.getFlowRelationships().add(f); } protected void connectTwoPlaces(PetriNet net, Node in, Node out, String id) { Transition t = this.pnfactory.createSilentTransition(); t.setId(id); net.getTransitions().add(t); this.createFlowRelationship(net, in, t); this.createFlowRelationship(net, t, out); } protected void connectTwoTransitions(PetriNet net, Node in, Node out, String id) { Place p = this.pnfactory.createPlace(); p.setId(id); net.getPlaces().add(p); this.createFlowRelationship(net, in, p); this.createFlowRelationship(net, p, out); } /** * Handles a connector of the EPC. * * @param net * @param controlflow * @param conversion context capturing the relation between Petri net and EPC elements */ protected void handleConnector(PetriNet net, Connector connector, ConversionContext c) { if (connector.isXOR()) { Place p = this.pnfactory.createPlace(); p.setId(connector.getId() + " place"); net.getPlaces().add(p); c.setAllConversionMaps(connector, p); } else if (connector.isAND()) { Transition t = this.pnfactory.createSilentTransition(); t.setId(connector.getId() + " transition"); net.getTransitions().add(t); c.setAllConversionMaps(connector, t); } } /** * Converts the EPC hold as a private member into a Petri net. * * @return the Petri net that corresponds to the EPC */ public PetriNet convert() { if (epc == null) return null; PetriNet net = pnfactory.createPetriNet(); ConversionContext c = new ConversionContext(); for(IFlowObject o : this.epc.getFlowObjects()) { if (o instanceof Function) { handleFunction(net, (Function) o, c); } else if (o instanceof Event) { handleEvent(net, (Event) o, c); } else if (o instanceof Connector) { // OR joins cannot be mapped at all!!! assert(!((Connector) o).isOR()); handleConnector(net, (Connector) o, c); } } for(ControlFlow f : this.epc.getControlFlow()) { handleControlFlow(net, f, c); } return net; } }
true
true
protected void handleControlFlow(PetriNet net, ControlFlow f, ConversionContext c) { Node source = c.getConversionMapOut().get(f.getSource()); Node target = c.getConversionMapIn().get(f.getTarget()); /* * In certain cases the straight-forward mapping of a flow arc * between an XOR split (a place) and an AND join (a transition) * might result in non-free choice constructs, which are not semantically * correct and therefore have to be avoided. */ if (f.getSource() instanceof Connector && f.getTarget() instanceof Connector) { Connector src1 = (Connector) f.getSource(); Connector tar1 = (Connector) f.getTarget(); if (src1.isXOR() && tar1.isAND()) { Transition t = this.pnfactory.createSilentTransition(); t.setId("xor/and helper " + c.getId()); net.getTransitions().add(t); this.createFlowRelationship(net, source, t); connectTwoTransitions(net, t, target, "xor/and helper " + c.getId()); return; } } if ((source instanceof Place && target instanceof Transition) || (source instanceof Transition && target instanceof Place)) { FlowRelationship flow = this.pnfactory.createFlowRelationship(); flow.setSource(source); flow.setTarget(target); } else if ((source instanceof Place && target instanceof Place)) { connectTwoPlaces(net, source, target, "helper transition " + c.getId() + f.toString()); } else if ((source instanceof Transition && target instanceof Transition)) { connectTwoTransitions(net, source, target, "helper place " + c.getId()); } }
protected void handleControlFlow(PetriNet net, ControlFlow f, ConversionContext c) { Node source = c.getConversionMapOut().get(f.getSource()); Node target = c.getConversionMapIn().get(f.getTarget()); /* * In certain cases the straight-forward mapping of a flow arc * between an XOR split (a place) and an AND join (a transition) * might result in non-free choice constructs, which are not semantically * correct and therefore have to be avoided. */ if (f.getSource() instanceof Connector && f.getTarget() instanceof Connector) { Connector src1 = (Connector) f.getSource(); Connector tar1 = (Connector) f.getTarget(); if (src1.isXOR() && tar1.isAND()) { Transition t = this.pnfactory.createSilentTransition(); t.setId("xor/and helper " + c.getId()); net.getTransitions().add(t); this.createFlowRelationship(net, source, t); connectTwoTransitions(net, t, target, "xor/and helper " + c.getId()); return; } } if ((source instanceof Place && target instanceof Transition) || (source instanceof Transition && target instanceof Place)) { createFlowRelationship(net, source, target); } else if ((source instanceof Place && target instanceof Place)) { connectTwoPlaces(net, source, target, "helper transition " + c.getId() + f.toString()); } else if ((source instanceof Transition && target instanceof Transition)) { connectTwoTransitions(net, source, target, "helper place " + c.getId()); } }
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/config/EjbModule.java b/container/openejb-core/src/main/java/org/apache/openejb/config/EjbModule.java index 998b459181..5a5f95124c 100644 --- a/container/openejb-core/src/main/java/org/apache/openejb/config/EjbModule.java +++ b/container/openejb-core/src/main/java/org/apache/openejb/config/EjbModule.java @@ -1,150 +1,153 @@ /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.config; import org.apache.openejb.jee.EjbJar; import org.apache.openejb.jee.Webservices; import org.apache.openejb.jee.oejb3.OpenejbJar; import java.io.File; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.TreeSet; /** * Class is to remain "dumb" and should not have deployment logic added to it. * Class is intentionally not an interface as that would encourage "smart" implementations * @version $Revision$ $Date$ */ public class EjbModule implements WsModule { private final ValidationContext validation; private ClassLoader classLoader; private String jarLocation; private EjbJar ejbJar; private OpenejbJar openejbJar; private Webservices webservices; private String moduleId; private final Map<String,Object> altDDs = new HashMap<String,Object>(); private final Set<String> watchedResources = new TreeSet<String>(); public EjbModule(EjbJar ejbJar){ this(Thread.currentThread().getContextClassLoader(), null, ejbJar, null); } public EjbModule(EjbJar ejbJar, OpenejbJar openejbJar){ this(Thread.currentThread().getContextClassLoader(), null, ejbJar, openejbJar); } public EjbModule(ClassLoader classLoader, String moduleId, String jarURI, EjbJar ejbJar, OpenejbJar openejbJar) { if (classLoader == null) { throw new NullPointerException("classLoader is null"); } this.classLoader = classLoader; this.ejbJar = ejbJar; this.openejbJar = openejbJar; if (jarURI == null){ if (moduleId != null){ jarURI = moduleId; - } else if (ejbJar.getId() != null){ + } else if (ejbJar.getId() != null && !ejbJar.getId().equals("")){ jarURI = ejbJar.getId(); } else { jarURI = ejbJar.toString(); } } this.jarLocation = jarURI; if (moduleId == null){ - if (ejbJar != null && ejbJar.getId() != null){ + if (ejbJar != null && ejbJar.getId() != null && !ejbJar.getId().equals("")){ moduleId = ejbJar.getId(); } else { File file = new File(jarURI); moduleId = file.getName(); + if (moduleId == null){ + moduleId = jarURI; + } } } this.moduleId = moduleId; validation = new ValidationContext(EjbModule.class, jarLocation); } public EjbModule(ClassLoader classLoader, String jarURI, EjbJar ejbJar, OpenejbJar openejbJar) { this(classLoader, null, jarURI, ejbJar, openejbJar); } public ValidationContext getValidation() { return validation; } public Map<String, Object> getAltDDs() { return altDDs; } public ClassLoader getClassLoader() { return classLoader; } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } public EjbJar getEjbJar() { return ejbJar; } public void setEjbJar(EjbJar ejbJar) { this.ejbJar = ejbJar; } public String getJarLocation() { return jarLocation; } public void setJarLocation(String jarLocation) { this.jarLocation = jarLocation; } public String getModuleId() { return moduleId; } public void setModuleId(String moduleId) { this.moduleId = moduleId; } public OpenejbJar getOpenejbJar() { return openejbJar; } public void setOpenejbJar(OpenejbJar openejbJar) { this.openejbJar = openejbJar; } public Webservices getWebservices() { return webservices; } public void setWebservices(Webservices webservices) { this.webservices = webservices; } public Set<String> getWatchedResources() { return watchedResources; } }
false
true
public EjbModule(ClassLoader classLoader, String moduleId, String jarURI, EjbJar ejbJar, OpenejbJar openejbJar) { if (classLoader == null) { throw new NullPointerException("classLoader is null"); } this.classLoader = classLoader; this.ejbJar = ejbJar; this.openejbJar = openejbJar; if (jarURI == null){ if (moduleId != null){ jarURI = moduleId; } else if (ejbJar.getId() != null){ jarURI = ejbJar.getId(); } else { jarURI = ejbJar.toString(); } } this.jarLocation = jarURI; if (moduleId == null){ if (ejbJar != null && ejbJar.getId() != null){ moduleId = ejbJar.getId(); } else { File file = new File(jarURI); moduleId = file.getName(); } } this.moduleId = moduleId; validation = new ValidationContext(EjbModule.class, jarLocation); }
public EjbModule(ClassLoader classLoader, String moduleId, String jarURI, EjbJar ejbJar, OpenejbJar openejbJar) { if (classLoader == null) { throw new NullPointerException("classLoader is null"); } this.classLoader = classLoader; this.ejbJar = ejbJar; this.openejbJar = openejbJar; if (jarURI == null){ if (moduleId != null){ jarURI = moduleId; } else if (ejbJar.getId() != null && !ejbJar.getId().equals("")){ jarURI = ejbJar.getId(); } else { jarURI = ejbJar.toString(); } } this.jarLocation = jarURI; if (moduleId == null){ if (ejbJar != null && ejbJar.getId() != null && !ejbJar.getId().equals("")){ moduleId = ejbJar.getId(); } else { File file = new File(jarURI); moduleId = file.getName(); if (moduleId == null){ moduleId = jarURI; } } } this.moduleId = moduleId; validation = new ValidationContext(EjbModule.class, jarLocation); }
diff --git a/src/com/jidesoft/plaf/LookAndFeelFactory.java b/src/com/jidesoft/plaf/LookAndFeelFactory.java index c171c27b..ae54f64c 100644 --- a/src/com/jidesoft/plaf/LookAndFeelFactory.java +++ b/src/com/jidesoft/plaf/LookAndFeelFactory.java @@ -1,1698 +1,1699 @@ /* * @(#)LookAndFeelFactory.java 5/28/2005 * * Copyright 2002 - 2005 JIDE Software Inc. All rights reserved. */ package com.jidesoft.plaf; import com.jidesoft.icons.IconsFactory; import com.jidesoft.plaf.basic.BasicPainter; import com.jidesoft.plaf.basic.Painter; import com.jidesoft.plaf.eclipse.Eclipse3xMetalUtils; import com.jidesoft.plaf.eclipse.Eclipse3xWindowsUtils; import com.jidesoft.plaf.eclipse.EclipseMetalUtils; import com.jidesoft.plaf.eclipse.EclipseWindowsUtils; import com.jidesoft.plaf.office2003.Office2003Painter; import com.jidesoft.plaf.office2003.Office2003WindowsUtils; import com.jidesoft.plaf.office2007.Office2007WindowsUtils; import com.jidesoft.plaf.vsnet.VsnetMetalUtils; import com.jidesoft.plaf.vsnet.VsnetWindowsUtils; import com.jidesoft.plaf.xerto.XertoMetalUtils; import com.jidesoft.plaf.xerto.XertoWindowsUtils; import com.jidesoft.swing.JideButton; import com.jidesoft.swing.JideSwingUtilities; import com.jidesoft.swing.JideTabbedPane; import com.jidesoft.utils.ProductNames; import com.jidesoft.utils.SecurityUtils; import com.jidesoft.utils.SystemInfo; import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; import sun.swing.SwingLazyValue; import javax.swing.*; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.InsetsUIResource; import javax.swing.plaf.metal.MetalLookAndFeel; import java.awt.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; /** * JIDE Software created many new components that need their own ComponentUI classes and additional UIDefaults in * UIDefaults table. LookAndFeelFactory can take the UIDefaults from any existing look and feel and add the extra * UIDefaults JIDE components need. * <p/> * Before using any JIDE components, please make you call one of the two LookAndFeelFactory.installJideExtension(...) * methods. Basically, you set L&F using UIManager first just like before, then call installJideExtension. See code * below for an example. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions * on this call. * LookAndFeelFactory.installJideExtension(); * </pre></code> * LookAndFeelFactory.installJideExtension() method will check what kind of L&F you set and what operating system you * are on and decide which style of JIDE extension it will install. Here is the rule. <ul> <li> OS: Windows XP with XP * theme on, L&F: Windows L&F => OFFICE2003_STYLE <li> OS: any Windows, L&F: Windows L&F => VSNET_STYLE <li> OS: Linux, * L&F: any L&F based on Metal L&F => VSNET_STYLE <li> OS: Mac OS X, L&F: Aqua L&F => AQUA_STYLE <li> OS: any OS, L&F: * Quaqua L&F => AQUA_STYLE <li> Otherwise => VSNET_STYLE </ul> There is also another installJideExtension which takes * an int style parameter. You can pass in {@link #VSNET_STYLE}, {@link #ECLIPSE_STYLE}, {@link #ECLIPSE3X_STYLE}, * {@link #OFFICE2003_STYLE}, or {@link #XERTO_STYLE}. In the other word, you will make the choice of style instead of * letting LookAndFeelFactory to decide one for you. Please note, there is no constant defined for AQUA_STYLE. The only * way to use it is when you are using Aqua L&F or Quaqua L&F and you call installJideExtension() method, the one * without parameter. * <p/> * LookAndFeelFactory supports a number of known L&Fs. You can see those L&Fs as constants whose names are something * like "_LNF" such as WINDOWS_LNF. * <p/> * If you are using a 3rd party L&F we are not officially supporting, we might need to customize it. Here are two * classes you can use. The first one is {@link UIDefaultsCustomizer}. You can add a number of customizers to * LookAndFeelFactory. After LookAndFeelFactory installJideExtension method is called, we will call customize() method * on each UIDefaultsCustomizer to add additional UIDefaults you specified. You can use UIDefaultsCustomizer to do * things like small tweaks to UIDefaults without the hassle of creating a new style. * <p/> * Most likely, we will not need to use {@link UIDefaultsInitializer} if you are use L&Fs such as WindowsLookAndFeel, * any L&Fs based on MetalLookAndFeel, or AquaLookAndFeel etc. The only exception is Synth L&F and any L&Fs based on it. * The reason is we calculate all colors we will use in JIDE components from existing well-known UIDefaults. For * example, we will use UIManagerLookup.getColor("activeCaption") to calculate a color that we can use in dockable * frame's title pane. We will use UIManagerLookup.getColor("control") to calculate a color that we can use as * background of JIDE component. Most L&Fs will fill those UIDefaults. However in Synth L&F, those UIDefaults may or may * not have a valid value. You will end up with NPE later in the code when you call installJideExtension. In this case, * you can add those extra UIDefaults in UIDefaultsInitializer. We will call it before installJideExtension is called so * that those UIDefaults are there ready for us to use. This is how added support to GTK L&F and Synthetica L&F. * <p/> * {@link #installJideExtension()} method will only add the additional UIDefaults to current ClassLoader. If you have * several class loaders in your system, you probably should tell the UIManager to use the class loader that called * <code>installJideExtension</code>. Otherwise, you might some unexpected errors. Here is how to specify the class * loaders. * <code><pre> * UIManager.put("ClassLoader", currentClass.getClassLoader()); // currentClass is the class where * the code is. * LookAndFeelFactory.installDefaultLookAndFeelAndExtension(); // or installJideExtension() * </pre></code> */ public class LookAndFeelFactory implements ProductNames { /** * Class name of Windows L&F provided in Sun JDK. */ public static final String WINDOWS_LNF = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; /** * Class name of Metal L&F provided in Sun JDK. */ public static final String METAL_LNF = "javax.swing.plaf.metal.MetalLookAndFeel"; /** * Class name of Aqua L&F provided in Apple Mac OS X JDK. */ public static final String AQUA_LNF = "apple.laf.AquaLookAndFeel"; /** * Class name of Aqua L&F provided in Apple Mac OS X JDK. This is the new package since Java Update 6. */ public static final String AQUA_LNF_6 = "com.apple.laf.AquaLookAndFeel"; /** * Class name of Quaqua L&F. */ public static final String QUAQUA_LNF = "ch.randelshofer.quaqua.QuaquaLookAndFeel"; /** * Class name of Quaqua Alloy L&F. */ public static final String ALLOY_LNF = "com.incors.plaf.alloy.AlloyLookAndFeel"; /** * Class name of Synthetica L&F. */ public static final String SYNTHETICA_LNF = "de.javasoft.plaf.synthetica.SyntheticaLookAndFeel"; public static final String SYNTHETICA_LNF_PREFIX = "de.javasoft.plaf.synthetica.Synthetica"; /** * Class name of Plastic3D L&F before JGoodies Look 1.3 release. */ public static final String PLASTIC3D_LNF = "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel"; /** * Class name of Plastic3D L&F after JGoodies Look 1.3 release. */ public static final String PLASTIC3D_LNF_1_3 = "com.jgoodies.looks.plastic.Plastic3DLookAndFeel"; /** * Class name of PlasticXP L&F. */ public static final String PLASTICXP_LNF = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel"; /** * Class name of Tonic L&F. */ public static final String TONIC_LNF = "com.digitprop.tonic.TonicLookAndFeel"; /** * Class name of A03 L&F. */ public static final String A03_LNF = "a03.swing.plaf.A03LookAndFeel"; /** * Class name of Pgs L&F. */ public static final String PGS_LNF = "com.pagosoft.plaf.PgsLookAndFeel"; /* * Class name of Substance L&F. */ // public static final String SUBSTANCE_LNF = "org.jvnet.substance.SubstanceLookAndFeel"; // private static final String SUBSTANCE_LNF_PREFIX = "org.jvnet.substance.skin"; /** * Class name of GTK L&F provided by Sun JDK. */ public static final String GTK_LNF = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; /** * The name of Nimbus L&F. We didn't create a constant for Nimbus is because the package name will be changed in * JDK7 release */ public static final String NIMBUS_LNF_NAME = "NimbusLookAndFeel"; /** * A style that you can use with {@link #installJideExtension(int)} method. This style is the same as VSNET_STYLE * except it doesn't have menu related UIDefaults. You can only use this style if you didn't use any component from * JIDE Action Framework. * <p/> * * @see #VSNET_STYLE */ public static final int VSNET_STYLE_WITHOUT_MENU = 0; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Microsoft Visual Studio .NET for the toolbars, menus and dockable windows. * <p/> * Vsnet style is a very simple style with no gradient. Although it works on almost all L&Fs in any operating * systems, it looks the best on Windows 2000 or 98, or on Windows XP when XP theme is not on. If XP theme is on, we * suggest you use Office2003 style or Xerto style. Since the style is so simple, it works with a lot of the 3rd * party L&F such as Tonic, Pgs, Alloy etc without causing too much noise. That's why this is also the default style * for any L&Fs we don't recognize when you call {@link #installJideExtension()}, the one with out style parameter. * If you would like another style to be used as the default style, you can call {@link #setDefaultStyle(int)} * method. * <p/> * Here is the code to set to Windows L&F with Vsnet style extension. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.VSNET_STYLE); * </pre></code> * There is a special system property "shading theme" you can use. If you turn it on using the code below, you will * see a gradient on dockable frame's title pane and rounded corner and gradient on the tabs of JideTabbedPane. So * if the L&F you are using uses gradient, you can set this property to true to match with your L&F. For example, if * you use Plastic3D L&F, turning this property on will look better. * <code><pre> * System.setProperty("shadingtheme", "true"); * </pre></code> */ public static final int VSNET_STYLE = 1; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Eclipse 2.x for the toolbars, menus and dockable windows. * <p/> * Eclipse style works for almost all L&Fs and on any operating systems, although it looks the best on Windows. For * any other operating systems we suggest you to use XERTO_STYLE or VSNET_STYLE. * <p/> * Here is the code to set to any L&F with Eclipse style extension. * <code><pre> * UIManager.setLookAndFeel(AnyLookAndFeel.class.getName()); // you need to catch the * exceptions * on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.ECLIPSE_STYLE); * </pre></code> */ public static final int ECLIPSE_STYLE = 2; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Microsoft Office2003 for the toolbars, menus and dockable windows. * <p/> * Office2003 style looks great on Windows XP when Windows or Windows XP L&F from Sun JDK is used. It replicated the * exact same style as Microsoft Office 2003, to give your end user a familiar visual style. * <p/> * Here is the code to set to Windows L&F with Office2003 style extension. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE); * </pre></code> * It works either on any other Windows such asWindows 2000, Windows 98 etc. If you are on Windows XP, Office2003 * style will change theme based on the theme setting in Windows Display Property. But if you are not on XP, * Office2003 style will use the default gray theme only. You can force to change it using {@link * Office2003Painter#setColorName(String)} method, but it won't look good as other non-JIDE components won't have * the matching theme. * <p/> * Office2003 style doesn't work on any operating systems other than Windows mainly because the design of Office2003 * style is so centric to Windows that it doesn't look good on other operating systems. */ public static final int OFFICE2003_STYLE = 3; /** * A style that you can use with {@link #installJideExtension(int)} method. This style is created by Xerto * (http://www.xerto.com) which is used in their Imagery product. * <p/> * Xerto style looks great on Windows XP when Windows XP L&F from Sun JDK is used. * <p/> * Here is the code to set to Windows L&F with Xerto style extension. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE); * </pre></code> * Although it looks the best on Windows, Xerto style also supports Linux or Solaris if you use any L&Fs based on * Metal L&F or Synth L&F. For example, we recommend you to use Xerto style as default if you use SyntheticaL&F, a * L&F based on Synth. To use it, you basically replace WindowsLookAndFeel to the L&F you want to use in * setLookAndFeel line above. */ public static final int XERTO_STYLE = 4; /** * A style that you can use with {@link #installJideExtension(int)} method. This style is the same as XERTO_STYLE * except it doesn't have menu related UIDefaults. You can only use this style if you didn't use any component from * JIDE Action Framework. Please note, we only use menu extension for Xerto style when the underlying L&F is Windows * L&F. If you are using L&F such as Metal or other 3rd party L&F based on Metal, XERTO_STYLE_WITHOUT_MENU will be * used even you use XERTO_STYLE when calling to installJideExtension(). * <p/> * * @see #XERTO_STYLE */ public static final int XERTO_STYLE_WITHOUT_MENU = 6; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Eclipse 3.x for the toolbars, menus and dockable windows. * <p/> * Eclipse 3x style works for almost all L&Fs and on any operating systems, although it looks the best on Windows. * For any other OS's we suggest you to use XERTO_STYLE or VSNET_STYLE. * <code><pre> * UIManager.setLookAndFeel(AnyLookAndFeel.class.getName()); // you need to catch the * exceptions * on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.ECLIPSE3X_STYLE); * </pre></code> */ public static final int ECLIPSE3X_STYLE = 5; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Microsoft Office2007 for the toolbars, menus and dockable windows. * <p/> * Office2007 style looks great on Windows Vista when Windows L&F from Sun JDK is used. It replicated the exact same * style as Microsoft Office 2007, to give your end user a familiar visual style. * <p/> * Here is the code to set to Windows L&F with Office2007 style extension. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2007_STYLE); * </pre></code> * <p/> * Office2007 style doesn't work on any operating systems other than Windows mainly because the design of Office2003 * style is so centric to Windows that it doesn't look good on other operating systems. * <p/> * Because we use some painting code that is only available in JDK6, Office 2007 style only runs if you are using * JDK6 and above. */ public static final int OFFICE2007_STYLE = 7; private static int _style = -1; private static int _defaultStyle = -1; private static LookAndFeel _lookAndFeel; /** * If installJideExtension is called, it will put an entry on UIDefaults table. * UIManagerLookup.getBoolean(JIDE_EXTENSION_INSTALLLED) will return true. You can also use {@link * #isJideExtensionInstalled()} to check the value instead of using UIManagerLookup.getBoolean(JIDE_EXTENSION_INSTALLLED). */ public static final String JIDE_EXTENSION_INSTALLLED = "jidesoft.extendsionInstalled"; /** * If installJideExtension is called, a JIDE style will be installed on UIDefaults table. If so, * UIManagerLookup.getInt(JIDE_STYLE_INSTALLED) will return you the style that is installed. For example, if the * value is 1, it means VSNET_STYLE is installed because 1 is the value of VSNET_STYLE. */ public static final String JIDE_STYLE_INSTALLED = "jidesoft.extendsionStyle"; /** * An interface to make the customization of UIDefaults easier. This customizer will be called after * installJideExtension() is called. So if you want to further customize UIDefault, you can use this customizer to * do it. */ public static interface UIDefaultsCustomizer { void customize(UIDefaults defaults); } /** * An interface to make the initialization of UIDefaults easier. This initializer will be called before * installJideExtension() is called. So if you want to initialize UIDefault before installJideExtension is called, * you can use this initializer to do it. */ public static interface UIDefaultsInitializer { void initialize(UIDefaults defaults); } private static List<UIDefaultsCustomizer> _uiDefaultsCustomizers = new Vector<UIDefaultsCustomizer>(); private static List<UIDefaultsInitializer> _uiDefaultsInitializers = new Vector<UIDefaultsInitializer>(); private static Map<String, String> _installedLookAndFeels = new HashMap<String, String>(); public static final String LAF_INSTALLED = "installed"; public static final String LAF_NOT_INSTALLED = "not installed"; protected LookAndFeelFactory() { } /** * Gets the default style. If you never set default style before, it will return OFFICE2003_STYLE if you are on * Windows XP, L&F is instance of Windows L&F and XP theme is on. Otherwise, it will return VSNET_STYLE. If you set * default style before, it will return whatever style you set. * * @return the default style. */ public static int getDefaultStyle() { if (_defaultStyle == -1) { String defaultStyle = SecurityUtils.getProperty("jide.defaultStyle", "-1"); try { _defaultStyle = Integer.parseInt(defaultStyle); } catch (NumberFormatException e) { // ignore } if (_defaultStyle == -1) { int suggestedStyle; try { if (SystemInfo.isWindowsVistaAbove() && UIManager.getLookAndFeel() instanceof WindowsLookAndFeel && SystemInfo.isJdk6Above()) { suggestedStyle = OFFICE2007_STYLE; } else if (XPUtils.isXPStyleOn() && UIManager.getLookAndFeel() instanceof WindowsLookAndFeel) { suggestedStyle = OFFICE2003_STYLE; } else { suggestedStyle = ((LookAndFeelFactory.getProductsUsed() & PRODUCT_ACTION) == 0) ? VSNET_STYLE_WITHOUT_MENU : VSNET_STYLE; } } catch (UnsupportedOperationException e) { suggestedStyle = ((LookAndFeelFactory.getProductsUsed() & PRODUCT_ACTION) == 0) ? VSNET_STYLE_WITHOUT_MENU : VSNET_STYLE; } return suggestedStyle; } } return _defaultStyle; } /** * Sets the default style. If you call this method to set a default style, {@link #installJideExtension()} will use * it as the default style. * * @param defaultStyle the default style. */ public static void setDefaultStyle(int defaultStyle) { _defaultStyle = defaultStyle; } /** * Adds additional UIDefaults JIDE needed to UIDefault table. You must call this method every time switching look * and feel. And callupdateComponentTreeUI() in corresponding DockingManager or DockableBarManager after this call. * <pre><code> * try { * UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); * } * catch (ClassNotFoundException e) { * e.printStackTrace(); * } * catch (InstantiationException e) { * e.printStackTrace(); * } * catch (IllegalAccessException e) { * e.printStackTrace(); * } * catch (UnsupportedLookAndFeelException e) { * e.printStackTrace(); * } * <p/> * // to additional UIDefault for JIDE components * LookAndFeelFactory.installJideExtension(); // use default style VSNET_STYLE. You can change * to a different style * using setDefaultStyle(int style) and then call this method. Or simply call * installJideExtension(style). * <p/> * // call updateComponentTreeUI * frame.getDockableBarManager().updateComponentTreeUI(); * frame.getDockingManager().updateComponentTreeUI(); * </code></pre> */ public static void installJideExtension() { installJideExtension(getDefaultStyle()); } /** * Add additional UIDefaults JIDE needed to UIDefaults table. You must call this method every time switching look * and feel. And call updateComponentTreeUI() in corresponding DockingManager or DockableBarManager after this * call. * <pre><code> * try { * UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); * } * catch (ClassNotFoundException e) { * e.printStackTrace(); * } * catch (InstantiationException e) { * e.printStackTrace(); * } * catch (IllegalAccessException e) { * e.printStackTrace(); * } * catch (UnsupportedLookAndFeelException e) { * e.printStackTrace(); * } * <p/> * // to add additional UIDefault for JIDE components * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE); * <p/> * // call updateComponentTreeUI * frame.getDockableBarManager().updateComponentTreeUI(); * frame.getDockingManager().updateComponentTreeUI(); * </code></pre> * * @param style the style of the extension. */ public static void installJideExtension(int style) { installJideExtension(UIManager.getLookAndFeelDefaults(), UIManager.getLookAndFeel(), style); } /** * Checks if JIDE extension is installed. Please note, UIManager.setLookAndFeel() method will overwrite the whole * UIDefaults table. So even you called {@link #installJideExtension()} method before, UIManager.setLookAndFeel() * method make isJideExtensionInstalled returning false. * * @return true if installed. */ public static boolean isJideExtensionInstalled() { return UIDefaultsLookup.getBoolean(JIDE_EXTENSION_INSTALLLED); } /** * Installs the UIDefault needed by JIDE component to the uiDefaults table passed in. * * @param uiDefaults the UIDefault tables where JIDE UIDefaults will be installed. * @param lnf the LookAndFeel. This may have an effect on which set of JIDE UIDefaults we will install. * @param style the style of the JIDE UIDefaults. */ public static void installJideExtension(UIDefaults uiDefaults, LookAndFeel lnf, int style) { if (isJideExtensionInstalled() && _style == style && _lookAndFeel == lnf) { return; } _style = style; uiDefaults.put(JIDE_STYLE_INSTALLED, _style); _lookAndFeel = lnf; UIDefaultsInitializer[] initializers = getUIDefaultsInitializers(); for (UIDefaultsInitializer initializer : initializers) { if (initializer != null) { initializer.initialize(uiDefaults); } } // For Alloy /* if (lnf.getClass().getName().equals(ALLOY_LNF) && isAlloyLnfInstalled()) { Object progressBarUI = uiDefaults.get("ProgressBarUI"); VsnetMetalUtils.initClassDefaults(uiDefaults); VsnetMetalUtils.initComponentDefaults(uiDefaults); uiDefaults.put("ProgressBarUI", progressBarUI); uiDefaults.put("DockableFrameUI", "com.jidesoft.plaf.vsnet.VsnetDockableFrameUI"); uiDefaults.put("DockableFrameTitlePane.hideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 0, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.unfloatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.floatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 2 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.autohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 3 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.stopAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 4 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.hideAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 5 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.maximizeIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 6 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.restoreIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 7 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.buttonGap", new Integer(4)); // gap between buttons } else */ if ((lnf.getClass().getName().equals(ALLOY_LNF) && isAlloyLnfInstalled()) || (lnf.getClass().getName().equals(PLASTIC3D_LNF) && isPlastic3DLnfInstalled()) || (lnf.getClass().getName().equals(PLASTIC3D_LNF_1_3) && isPlastic3D13LnfInstalled()) || (lnf.getClass().getName().equals(PLASTICXP_LNF) && isPlasticXPLnfInstalled()) || (lnf.getClass().getName().equals(PGS_LNF) && isPgsLnfInstalled()) || (lnf.getClass().getName().equals(TONIC_LNF) && isTonicLnfInstalled())) { switch (style) { case OFFICE2007_STYLE: VsnetWindowsUtils.initComponentDefaults(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); Office2007WindowsUtils.initComponentDefaults(uiDefaults); Office2007WindowsUtils.initClassDefaults(uiDefaults, false); break; case OFFICE2003_STYLE: VsnetWindowsUtils.initComponentDefaults(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); Office2003WindowsUtils.initClassDefaults(uiDefaults, false); break; case VSNET_STYLE: case VSNET_STYLE_WITHOUT_MENU: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); Painter gripperPainter = new Painter() { public void paint(JComponent c, Graphics g, Rectangle rect, int orientation, int state) { Office2003Painter.getInstance().paintGripper(c, g, rect, orientation, state); } }; // set all grippers to Office2003 style gripper uiDefaults.put("Gripper.painter", gripperPainter); uiDefaults.put("JideTabbedPane.gripperPainter", gripperPainter); uiDefaults.put("JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_OFFICE2003); uiDefaults.put("JideTabbedPane.selectedTabTextForeground", UIDefaultsLookup.getColor("controlText")); uiDefaults.put("JideTabbedPane.unselectedTabTextForeground", UIDefaultsLookup.getColor("controlText")); uiDefaults.put("JideTabbedPane.foreground", UIDefaultsLookup.getColor("controlText")); uiDefaults.put("JideTabbedPane.light", UIDefaultsLookup.getColor("control")); uiDefaults.put("JideSplitPaneDivider.gripperPainter", gripperPainter); int products = LookAndFeelFactory.getProductsUsed(); if ((products & PRODUCT_DOCK) != 0) { ImageIcon titleButtonImage = IconsFactory.getImageIcon(VsnetWindowsUtils.class, "icons/title_buttons_windows.gif"); // 10 x 10 x 8 final int titleButtonSize = 10; uiDefaults.put("DockableFrameUI", "com.jidesoft.plaf.vsnet.VsnetDockableFrameUI"); uiDefaults.put("DockableFrameTitlePane.hideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 0, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.unfloatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.floatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 2 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.autohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 3 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.stopAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 4 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.hideAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 5 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.maximizeIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 6 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.restoreIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 7 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.buttonGap", 4); // gap between buttons uiDefaults.put("DockableFrame.titleBorder", new BorderUIResource(BorderFactory.createEmptyBorder(1, 0, 2, 0))); uiDefaults.put("DockableFrame.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 0, 0, 0))); uiDefaults.put("DockableFrameTitlePane.gripperPainter", gripperPainter); } break; case ECLIPSE_STYLE: EclipseMetalUtils.initComponentDefaults(uiDefaults); EclipseMetalUtils.initClassDefaults(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); Eclipse3xMetalUtils.initClassDefaults(uiDefaults); break; case XERTO_STYLE: case XERTO_STYLE_WITHOUT_MENU: XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); break; } uiDefaults.put("Theme.painter", BasicPainter.getInstance()); } else if (lnf.getClass().getName().equals(MetalLookAndFeel.class.getName())) { switch (style) { case OFFICE2007_STYLE: case OFFICE2003_STYLE: case VSNET_STYLE: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaultsWithMenu(uiDefaults); break; case ECLIPSE_STYLE: EclipseMetalUtils.initComponentDefaults(uiDefaults); EclipseMetalUtils.initClassDefaults(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); Eclipse3xMetalUtils.initClassDefaults(uiDefaults); break; case VSNET_STYLE_WITHOUT_MENU: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); break; case XERTO_STYLE: case XERTO_STYLE_WITHOUT_MENU: XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); break; default: } } else if (lnf instanceof MetalLookAndFeel) { switch (style) { case OFFICE2007_STYLE: case OFFICE2003_STYLE: case VSNET_STYLE: case VSNET_STYLE_WITHOUT_MENU: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); break; case ECLIPSE_STYLE: EclipseMetalUtils.initClassDefaults(uiDefaults); EclipseMetalUtils.initComponentDefaults(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xMetalUtils.initClassDefaults(uiDefaults); Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); break; case XERTO_STYLE: case XERTO_STYLE_WITHOUT_MENU: XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); break; } } else if (lnf instanceof WindowsLookAndFeel) { switch (style) { case OFFICE2007_STYLE: VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); VsnetWindowsUtils.initClassDefaultsWithMenu(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); Office2007WindowsUtils.initComponentDefaults(uiDefaults); Office2007WindowsUtils.initClassDefaults(uiDefaults); break; case OFFICE2003_STYLE: VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); VsnetWindowsUtils.initClassDefaultsWithMenu(uiDefaults); Office2003WindowsUtils.initClassDefaults(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); break; case ECLIPSE_STYLE: EclipseWindowsUtils.initClassDefaultsWithMenu(uiDefaults); EclipseWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xWindowsUtils.initClassDefaultsWithMenu(uiDefaults); Eclipse3xWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); break; case VSNET_STYLE: VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); VsnetWindowsUtils.initClassDefaultsWithMenu(uiDefaults); break; case VSNET_STYLE_WITHOUT_MENU: VsnetWindowsUtils.initComponentDefaults(uiDefaults); VsnetWindowsUtils.initClassDefaults(uiDefaults); break; case XERTO_STYLE: XertoWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); XertoWindowsUtils.initClassDefaultsWithMenu(uiDefaults); break; case XERTO_STYLE_WITHOUT_MENU: XertoWindowsUtils.initComponentDefaults(uiDefaults); XertoWindowsUtils.initClassDefaults(uiDefaults); break; } } // For Mac only else if (isAquaLnfInstalled() && ((isLnfInUse(AQUA_LNF_6) || isLnfInUse(AQUA_LNF))) || (isQuaquaLnfInstalled() && isLnfInUse(QUAQUA_LNF))) { // use reflection since we don't deliver source code of AquaJideUtils as most users don't compile it on Mac OS X try { Class<?> aquaJideUtils = getUIManagerClassLoader().loadClass("com.jidesoft.plaf.aqua.AquaJideUtils"); aquaJideUtils.getMethod("initComponentDefaults", UIDefaults.class).invoke(null, uiDefaults); aquaJideUtils.getMethod("initClassDefaults", UIDefaults.class).invoke(null, uiDefaults); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { JideSwingUtilities.throwInvocationTargetException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } } else { // built in initializer if (isGTKLnfInstalled() && isLnfInUse(GTK_LNF)) { new GTKInitializer().initialize(uiDefaults); } else if (isSyntheticaLnfInstalled() && (lnf.getClass().getName().startsWith(SYNTHETICA_LNF_PREFIX) || isLnfInUse(SYNTHETICA_LNF))) { new SyntheticaInitializer().initialize(uiDefaults); } else if (isNimbusLnfInstalled() && lnf.getClass().getName().indexOf(NIMBUS_LNF_NAME) != -1) { new NimbusInitializer().initialize(uiDefaults); } switch (style) { case OFFICE2007_STYLE: if (SystemInfo.isWindows()) { VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); Office2007WindowsUtils.initComponentDefaults(uiDefaults); Office2007WindowsUtils.initClassDefaults(uiDefaults); } else { VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); } break; case OFFICE2003_STYLE: if (SystemInfo.isWindows()) { VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); Office2003WindowsUtils.initClassDefaults(uiDefaults); } else { VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); } break; case ECLIPSE_STYLE: if (SystemInfo.isWindows()) { EclipseWindowsUtils.initClassDefaultsWithMenu(uiDefaults); EclipseWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { EclipseMetalUtils.initClassDefaults(uiDefaults); EclipseMetalUtils.initComponentDefaults(uiDefaults); } break; case ECLIPSE3X_STYLE: if (SystemInfo.isWindows()) { Eclipse3xWindowsUtils.initClassDefaultsWithMenu(uiDefaults); Eclipse3xWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { Eclipse3xMetalUtils.initClassDefaults(uiDefaults); Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); } break; case VSNET_STYLE: if (SystemInfo.isWindows()) { VsnetWindowsUtils.initClassDefaultsWithMenu(uiDefaults); VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); } break; case VSNET_STYLE_WITHOUT_MENU: if (SystemInfo.isWindows()) { VsnetWindowsUtils.initClassDefaults(uiDefaults); VsnetWindowsUtils.initComponentDefaults(uiDefaults); } else { VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); } break; case XERTO_STYLE: if (SystemInfo.isWindows()) { XertoWindowsUtils.initClassDefaultsWithMenu(uiDefaults); XertoWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); } break; case XERTO_STYLE_WITHOUT_MENU: if (SystemInfo.isWindows()) { XertoWindowsUtils.initClassDefaults(uiDefaults); XertoWindowsUtils.initComponentDefaults(uiDefaults); } else { XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); } break; } if (isGTKLnfInstalled() && isLnfInUse(GTK_LNF)) { new GTKCustomizer().customize(uiDefaults); } else if (lnf.getClass().getName().startsWith(SYNTHETICA_LNF_PREFIX) || (isLnfInstalled(SYNTHETICA_LNF) && isLnfInUse(SYNTHETICA_LNF))) { new SyntheticaCustomizer().customize(uiDefaults); } } uiDefaults.put(JIDE_EXTENSION_INSTALLLED, Boolean.TRUE); UIDefaultsCustomizer[] customizers = getUIDefaultsCustomizers(); for (UIDefaultsCustomizer customizer : customizers) { if (customizer != null) { customizer.customize(uiDefaults); } } } /** * Returns whether or not the L&F is in classpath. * * @param lnfName the L&F name. * @return <tt>true</tt> if the L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isLnfInstalled(String lnfName) { String installed = _installedLookAndFeels.get(lnfName); if (installed != null) { return LAF_INSTALLED.equals(installed); } return loadLnfClass(lnfName) != null; } public static ClassLoader getUIManagerClassLoader() { Object cl = UIManager.get("ClassLoader"); if (cl instanceof ClassLoader) { return (ClassLoader) cl; } ClassLoader classLoader = LookAndFeelFactory.class.getClassLoader(); if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } return classLoader; } /** * Checks if the L&F is the L&F or a subclass of the L&F. * * @param lnfName the L&F name. * @return true or false. */ public static boolean isLnfInUse(String lnfName) { return !(_installedLookAndFeels.containsKey(lnfName) && (_installedLookAndFeels.get(lnfName) == null || _installedLookAndFeels.get(lnfName).equals(LAF_NOT_INSTALLED))) && isAssignableFrom(lnfName, UIManager.getLookAndFeel().getClass()); } /** * Tells the LookAndFeelFactory whether a L&F is installed. We will try to instantiate the class when {@link * #isLnfInstalled(String)} is called to determine if the class is in the class path. However you can call this * method to tell if the L&F is available without us instantiating the class. * * @param lnfName the L&F name. * @param installed true or false. */ public static void setLnfInstalled(String lnfName, boolean installed) { _installedLookAndFeels.put(lnfName, installed ? LAF_INSTALLED : LAF_NOT_INSTALLED); } private static Class loadLnfClass(String lnfName) { try { Class clazz = getUIManagerClassLoader().loadClass(lnfName); Map<String, String> map = new HashMap<String, String>(_installedLookAndFeels); map.put(lnfName, LAF_INSTALLED); _installedLookAndFeels = map; return clazz; } catch (ClassNotFoundException e) { Map<String, String> map = new HashMap<String, String>(_installedLookAndFeels); map.put(lnfName, LAF_NOT_INSTALLED); _installedLookAndFeels = map; return null; } } private static boolean isAssignableFrom(String lnfName, Class cls) { if (lnfName.equals(cls.getName())) { return true; } Class cl = loadLnfClass(lnfName); return cl != null && cl.isAssignableFrom(cls); } /** * Returns whether or not the Aqua L&F is in classpath. * * @return <tt>true</tt> if aqua L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isAquaLnfInstalled() { return isLnfInstalled(AQUA_LNF_6) || isLnfInstalled(AQUA_LNF); } /** * Returns whether or not the Quaqua L&F is in classpath. * * @return <tt>true</tt> if Quaqua L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isQuaquaLnfInstalled() { return isLnfInstalled(QUAQUA_LNF); } /** * Returns whether alloy L&F is in classpath * * @return <tt>true</tt> alloy L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isAlloyLnfInstalled() { return isLnfInstalled(ALLOY_LNF); } /** * Returns whether GTK L&F is in classpath * * @return <tt>true</tt> GTK L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isGTKLnfInstalled() { return isLnfInstalled(GTK_LNF); } /** * Returns whether Plastic3D L&F is in classpath * * @return <tt>true</tt> Plastic3D L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPlastic3DLnfInstalled() { return isLnfInstalled(PLASTIC3D_LNF); } /** * Returns whether Plastic3D L&F is in classpath * * @return <tt>true</tt> Plastic3D L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPlastic3D13LnfInstalled() { return isLnfInstalled(PLASTIC3D_LNF_1_3); } /** * Returns whether PlasticXP L&F is in classpath * * @return <tt>true</tt> Plastic3D L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPlasticXPLnfInstalled() { return isLnfInstalled(PLASTICXP_LNF); } /** * Returns whether Tonic L&F is in classpath * * @return <tt>true</tt> Tonic L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isTonicLnfInstalled() { return isLnfInstalled(TONIC_LNF); } /** * Returns whether A03 L&F is in classpath * * @return <tt>true</tt> A03 L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isA03LnfInstalled() { return isLnfInstalled(A03_LNF); } /** * Returns whether or not the Pgs L&F is in classpath. * * @return <tt>true</tt> if pgs L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPgsLnfInstalled() { return isLnfInstalled(PGS_LNF); } /* * Returns whether or not the Substance L&F is in classpath. * * @return <tt>true</tt> if Substance L&F is in classpath, <tt>false</tt> otherwise */ // public static boolean isSubstanceLnfInstalled() { // return isLnfInstalled(SUBSTANCE_LNF); // } /** * Returns whether or not the Synthetica L&F is in classpath. * * @return <tt>true</tt> if Synthetica L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isSyntheticaLnfInstalled() { return isLnfInstalled(SYNTHETICA_LNF); } /** * Returns whether or not the Nimbus L&F is in classpath. * * @return <tt>true</tt> if Nimbus L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isNimbusLnfInstalled() { UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo info : infos) { if (info.getClassName().indexOf(NIMBUS_LNF_NAME) != -1) { return true; } } return false; } /** * Install the default L&F. In this method, we will look at system property "swing.defaultlaf" first. If the value * is set and it's not an instance of Synth L&F, we will use it. Otherwise, we will use Metal L&F is OS is Linux or * UNIX and use UIManager.getSystemLookAndFeelClassName() for other OS. In addition, we will add JIDE extension to * it. */ public static void installDefaultLookAndFeelAndExtension() { installDefaultLookAndFeel(); // to add additional UIDefault for JIDE components LookAndFeelFactory.installJideExtension(); } /** * Install the default L&F. In this method, we will look at system property "swing.defaultlaf" first. If the value * is set and it's not an instance of Synth L&F, we will use it. Otherwise, we will use Metal L&F is OS is Linux or * UNIX and use UIManager.getSystemLookAndFeelClassName() for other OS. */ public static void installDefaultLookAndFeel() { try { String lnfName = SecurityUtils.getProperty("swing.defaultlaf", null); if (lnfName == null) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else { UIManager.setLookAndFeel(lnfName); } } catch (Exception e) { e.printStackTrace(); } } /** * Gets current L&F. * * @return the current L&F. */ public static LookAndFeel getLookAndFeel() { return _lookAndFeel; } /** * Gets current style. * * @return the current style. */ public static int getStyle() { return _style; } /** * Gets all UIDefaults customizers. * * @return an array of UIDefaults customizers. */ public static UIDefaultsCustomizer[] getUIDefaultsCustomizers() { return _uiDefaultsCustomizers.toArray(new UIDefaultsCustomizer[_uiDefaultsCustomizers.size()]); } /** * Adds your own UIDefaults customizer. You need to add it before installJideExtension() is called but the actual * customize() code will be called after installJideExtension() is called. * <code><pre> * For example, we use "JideButton.font" as the UIDefault for the JideButton font. If you want * to use another font, you can do * LookAndFeelFactory.addUIDefaultsCustomizer(new LookAndFeelFactory.UIDefaultsCustomizer() { * public void customize(UIDefaults defaults) { * defaults.put("JideButton.font", whateverFont); * } * }); * LookAndFeelFactory.installJideExtension(); * </pre></code> * * @param uiDefaultsCustomizer the UIDefaultsCustomizer */ public static void addUIDefaultsCustomizer(UIDefaultsCustomizer uiDefaultsCustomizer) { if (!_uiDefaultsCustomizers.contains(uiDefaultsCustomizer)) { _uiDefaultsCustomizers.add(uiDefaultsCustomizer); } } /** * Removes an existing UIDefaults customizer you added before. * * @param uiDefaultsCustomizer the UIDefaultsCustomizer */ public static void removeUIDefaultsCustomizer(UIDefaultsCustomizer uiDefaultsCustomizer) { _uiDefaultsCustomizers.remove(uiDefaultsCustomizer); } /** * Gets all UIDefaults initializers. * * @return an array of UIDefaults initializers. */ public static UIDefaultsInitializer[] getUIDefaultsInitializers() { return _uiDefaultsInitializers.toArray(new UIDefaultsInitializer[_uiDefaultsInitializers.size()]); } /** * Adds your own UIDefaults initializer. This initializer will be called before installJideExtension() is called. * <p/> * Here is how you use it. For example, we use the color of UIDefault "activeCaption" to get the active title color * which we will use for active title bar color in JIDE components. If the L&F you are using doesn't set this * UIDefault, we might throw NPE later in the code. To avoid this, you call * <code><pre> * LookAndFeelFactory.addUIDefaultsInitializer(new LookAndFeelFactory.UIDefaultsInitializer() { * public void initialize(UIDefaults defaults) { * defaults.put("activeCaption", whateverColor); * } * }); * UIManager.setLookAndFeel(...); // set whatever L&F * LookAndFeelFactory.installJideExtension(); // install the UIDefaults needed by the JIDE * components * </pre></code> * * @param uiDefaultsInitializer the UIDefaultsInitializer. */ public static void addUIDefaultsInitializer(UIDefaultsInitializer uiDefaultsInitializer) { if (!_uiDefaultsInitializers.contains(uiDefaultsInitializer)) { _uiDefaultsInitializers.add(uiDefaultsInitializer); } } /** * Removes an existing UIDefaults initializer you added before. * * @param uiDefaultsInitializer the UIDefaultsInitializer */ public static void removeUIDefaultsInitializer(UIDefaultsInitializer uiDefaultsInitializer) { _uiDefaultsInitializers.remove(uiDefaultsInitializer); } public static class GTKInitializer implements UIDefaultsInitializer { public void initialize(UIDefaults defaults) { Object[] uiDefaults = { "activeCaption", defaults.getColor("textHighlight"), "activeCaptionText", defaults.getColor("textHighlightText"), "inactiveCaptionBorder", defaults.getColor("controlShadowtextHighlightText"), }; putDefaults(defaults, uiDefaults); } } public static class GTKCustomizer implements UIDefaultsCustomizer { public void customize(UIDefaults defaults) { Object[] uiDefaults = { "RangeSliderUI", "javax.swing.plaf.synth.SynthRangeSliderUI", }; overwriteDefaults(defaults, uiDefaults); } } public static class SyntheticaInitializer implements UIDefaultsInitializer { public void initialize(UIDefaults defaults) { try { Class syntheticaPopupBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaPopupBorder"); Object[] uiDefaults = { "Label.font", UIDefaultsLookup.getFont("Button.font"), "ToolBar.font", UIDefaultsLookup.getFont("Button.font"), "MenuItem.acceleratorFont", UIDefaultsLookup.getFont("Button.font"), "ComboBox.disabledForeground", defaults.get("Synthetica.comboBox.disabled.textColor"), "ComboBox.disabledBackground", defaults.get("Synthetica.comboBox.disabled.backgroundColor"), "Slider.focusInsets", new InsetsUIResource(0, 0, 0, 0), "PopupMenu.border", syntheticaPopupBorder.newInstance(), }; putDefaults(defaults, uiDefaults); } catch (Exception e) { e.printStackTrace(); } } } //TODO: Miss SubstanceCustomizer here public static class SyntheticaCustomizer implements UIDefaultsCustomizer { @SuppressWarnings({"ConstantConditions"}) public void customize(UIDefaults defaults) { try { Class syntheticaClass = Class.forName(SYNTHETICA_LNF); Class syntheticaFrameBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaFrameBorder"); Class syntheticaPopupBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaPopupBorder"); Color toolbarBackground = new JToolBar().getBackground(); int products = LookAndFeelFactory.getProductsUsed(); { Object[] uiDefaults = { "JideTabbedPaneUI", "com.jidesoft.plaf.synthetica.SyntheticaJideTabbedPaneUI", "RangeSliderUI", "javax.swing.plaf.synth.SynthRangeSliderUI", "JideSplitPane.dividerSize", 6, "JideTabbedPane.foreground", UIManager.getColor("TabbedPane.foreground"), "JideTabbedPane.unselectedTabTextForeground", UIManager.getColor("TabbedPane.foreground"), "JideTabbedPane.tabAreaBackground", UIManager.getColor("control"), "JideTabbedPane.background", UIManager.getColor("control"), "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "JideButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "JideSplitButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "Icon.floating", Boolean.FALSE, "ContentContainer.background", toolbarBackground, "PopupMenu.border", syntheticaPopupBorder.newInstance(), "JideLabel.font", UIManager.getFont("Label.font"), "JideLabel.background", UIManager.getColor("Label.background"), "JideLabel.foreground", UIManager.getColor("Label.foreground"), }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_COMPONENTS) != 0) { Object[] uiDefaults = { "CollapsiblePane.background", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.emphasizedBackground", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.foreground", UIDefaultsLookup.getColor("TaskPane.titleForeground"), "CollapsiblePane.emphasizedForeground", UIDefaultsLookup.getColor("TaskPane.specialTitleForeground"), + "CollapsiblePane.contentBackground", UIDefaultsLookup.getColor("Panel.background"), "CollapsiblePane.font", UIDefaultsLookup.getFont("TaskPane.font") != null ? UIDefaultsLookup.getFont("TaskPane.font") : UIDefaultsLookup.getFont("Label.font"), "StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 2, 2, 2)), "StatusBar.childrenOpaque", false, "StatusBar.paintResizableIcon", false, "OutlookTabbedPane.buttonStyle", JideButton.TOOLBAR_STYLE, "FloorTabbedPane.buttonStyle", JideButton.TOOLBAR_STYLE, }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_GRIDS) != 0) { Object[] uiDefaults = { "NestedTableHeaderUI", "com.jidesoft.plaf.synthetica.SyntheticaNestedTableHeaderUI", "EditableTableHeaderUI", "com.jidesoft.plaf.synthetica.SyntheticaEditableTableHeaderUI", "ExComboBoxUI", "com.jidesoft.plaf.synthetica.SyntheticaExComboBoxUI", "List.focusInputMap", new UIDefaults.LazyInputMap(new Object[]{ "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "HOME", "selectFirstRow", "shift HOME", "selectFirstRowExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRowChangeLead", "END", "selectLastRow", "shift END", "selectLastRowExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRowChangeLead", "PAGE_UP", "scrollUp", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDown", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "List.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[]{ "LEFT", "selectNextColumn", "KP_LEFT", "selectNextColumn", "shift LEFT", "selectNextColumnExtendSelection", "shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl shift LEFT", "selectNextColumnExtendSelection", "ctrl shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl LEFT", "selectNextColumnChangeLead", "ctrl KP_LEFT", "selectNextColumnChangeLead", "RIGHT", "selectPreviousColumn", "KP_RIGHT", "selectPreviousColumn", "shift RIGHT", "selectPreviousColumnExtendSelection", "shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl RIGHT", "selectPreviousColumnChangeLead", "ctrl KP_RIGHT", "selectPreviousColumnChangeLead", }), }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_ACTION) != 0) { Object[] uiDefaults = { "CommandBar.background", toolbarBackground, "CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderFloating", syntheticaFrameBorder.newInstance(), "CommandBar.titleBarBackground", UIDefaultsLookup.getColor("InternalFrame.activeTitleBackground"), "CommandBar.titleBarForeground", UIDefaultsLookup.getColor("InternalFrame.activeTitleForeground"), "CommandBarContainer.verticalGap", 0, }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_DOCK) != 0) { Object[] uiDefaults = { "Workspace.background", UIManager.getColor("control"), "DockableFrame.inactiveTitleForeground", UIDefaultsLookup.getColor("JYDocking.titlebar.foreground"), "DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("JYDocking.titlebar.active.foreground"), "DockableFrame.titleBorder", UIDefaultsLookup.getColor("JYDocking.contentPane.border.color"), "FrameContainer.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "DockableFrameTitlePane.hideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.closeButton.icon")), "DockableFrameTitlePane.hideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.closeButton.icon.hover")), "DockableFrameTitlePane.hideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.closeButton.icon")), "DockableFrameTitlePane.hideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.closeButton.icon.hover")), "DockableFrameTitlePane.floatIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon")), "DockableFrameTitlePane.floatRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.hover")), "DockableFrameTitlePane.floatActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon")), "DockableFrameTitlePane.floatRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.hover")), "DockableFrameTitlePane.unfloatIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.selected")), "DockableFrameTitlePane.unfloatRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.hover.selected")), "DockableFrameTitlePane.unfloatActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.selected")), "DockableFrameTitlePane.unfloatRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.hover.selected")), "DockableFrameTitlePane.autohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon")), "DockableFrameTitlePane.autohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon.hover")), "DockableFrameTitlePane.autohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon")), "DockableFrameTitlePane.autohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon.hover")), "DockableFrameTitlePane.stopAutohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.selected")), "DockableFrameTitlePane.stopAutohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.stopAutohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.selected")), "DockableFrameTitlePane.stopAutohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.hideAutohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon")), "DockableFrameTitlePane.hideAutohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon.hover")), "DockableFrameTitlePane.hideAutohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon")), "DockableFrameTitlePane.hideAutohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon.hover")), "DockableFrameTitlePane.maximizeIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon")), "DockableFrameTitlePane.maximizeRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover")), "DockableFrameTitlePane.maximizeActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon")), "DockableFrameTitlePane.maximizeRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover")), "DockableFrameTitlePane.restoreIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.selected")), "DockableFrameTitlePane.restoreRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.restoreActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.selected")), "DockableFrameTitlePane.restoreRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.use3dButtons", Boolean.FALSE, "DockableFrameTitlePane.contentFilledButtons", Boolean.FALSE, "DockableFrameTitlePane.buttonGap", 0, }; overwriteDefaults(defaults, uiDefaults); } Class<?> painterClass = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaJidePainter"); Method getInstanceMethod = painterClass.getMethod("getInstance"); Object painter = getInstanceMethod.invoke(null); UIDefaultsLookup.put(UIManager.getDefaults(), "Theme.painter", painter); } catch (Exception e) { e.printStackTrace(); } } } private static Icon loadSyntheticaIcon(Class syntheticaClass, String key) { try { Method method = syntheticaClass.getMethod("loadIcon", String.class); return (Icon) method.invoke(null, key); } catch (Exception e) { return IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString(key)); } } public static class NimbusInitializer implements UIDefaultsInitializer { public void initialize(UIDefaults defaults) { Object marginBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders$MarginBorder"); Object[] uiDefaults = { "textHighlight", new ColorUIResource(197, 218, 233), "controlText", new ColorUIResource(Color.BLACK), "activeCaptionText", new ColorUIResource(Color.BLACK), "MenuItem.acceleratorFont", new FontUIResource("Arial", Font.PLAIN, 12), "ComboBox.background", new ColorUIResource(Color.WHITE), "ComboBox.disabledForeground", new ColorUIResource(Color.DARK_GRAY), "ComboBox.disabledBackground", new ColorUIResource(Color.GRAY), "activeCaption", new ColorUIResource(197, 218, 233), "inactiveCaption", new ColorUIResource(Color.DARK_GRAY), "control", new ColorUIResource(220, 223, 228), "controlLtHighlight", new ColorUIResource(Color.WHITE), "controlHighlight", new ColorUIResource(Color.LIGHT_GRAY), "controlShadow", new ColorUIResource(133, 137, 144), "controlDkShadow", new ColorUIResource(Color.BLACK), "MenuItem.background", new ColorUIResource(237, 239, 242), "SplitPane.background", new ColorUIResource(220, 223, 228), "Tree.hash", new ColorUIResource(Color.GRAY), "TextField.foreground", new ColorUIResource(Color.BLACK), "TextField.inactiveForeground", new ColorUIResource(Color.BLACK), "TextField.selectionForeground", new ColorUIResource(Color.WHITE), "TextField.selectionBackground", new ColorUIResource(197, 218, 233), "Table.gridColor", new ColorUIResource(Color.BLACK), "TextField.background", new ColorUIResource(Color.WHITE), "Table.selectionBackground", defaults.getColor("Tree.selectionBackground"), "Table.selectionForeground", defaults.getColor("Tree.selectionForeground"), "Menu.border", marginBorder, "MenuItem.border", marginBorder, "CheckBoxMenuItem.border", marginBorder, "RadioButtonMenuItem.border", marginBorder, }; putDefaults(defaults, uiDefaults); } } @SuppressWarnings({"UseOfSystemOutOrSystemErr"}) public static void verifyDefaults(UIDefaults table, Object[] keyValueList) { for (int i = 0, max = keyValueList.length; i < max; i += 2) { Object value = keyValueList[i + 1]; if (value == null) { System.out.println("The value for " + keyValueList[i] + " is null"); } else { Object oldValue = table.get(keyValueList[i]); if (oldValue != null) { System.out.println("The value for " + keyValueList[i] + " exists which is " + oldValue); } } } } /** * Puts a list of UIDefault to the UIDefaults table. The keyValueList is an array with a key and value in pair. If * the value is null, this method will remove the key from the table. If the table already has a value for the key, * the new value will be ignored. This is the difference from {@link #putDefaults(javax.swing.UIDefaults, Object[])} * method. You should use this method in {@link UIDefaultsInitializer} so that it fills in the UIDefault value only * when it is missing. * * @param table the ui defaults table * @param keyValueArray the key value array. It is in the format of a key followed by a value. */ public static void putDefaults(UIDefaults table, Object[] keyValueArray) { for (int i = 0, max = keyValueArray.length; i < max; i += 2) { Object value = keyValueArray[i + 1]; if (value == null) { table.remove(keyValueArray[i]); } else { if (table.get(keyValueArray[i]) == null) { table.put(keyValueArray[i], value); } } } } /** * Puts a list of UIDefault to the UIDefaults table. The keyValueList is an array with a key and value in pair. If * the value is null, this method will remove the key from the table. Otherwise, it will put the new value in even * if the table already has a value for the key. This is the difference from {@link * #putDefaults(javax.swing.UIDefaults, Object[])} method. You should use this method in {@link * UIDefaultsCustomizer} because you always want to override the existing value using the new value. * * @param table the ui defaults table * @param keyValueArray the key value array. It is in the format of a key followed by a value. */ public static void overwriteDefaults(UIDefaults table, Object[] keyValueArray) { for (int i = 0, max = keyValueArray.length; i < max; i += 2) { Object value = keyValueArray[i + 1]; if (value == null) { table.remove(keyValueArray[i]); } else { table.put(keyValueArray[i], value); } } } private static int _productsUsed = -1; public static int getProductsUsed() { if (_productsUsed == -1) { _productsUsed = 0; try { Class.forName("com.jidesoft.docking.Product"); _productsUsed |= PRODUCT_DOCK; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.action.Product"); _productsUsed |= PRODUCT_ACTION; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.document.Product"); _productsUsed |= PRODUCT_COMPONENTS; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.grid.Product"); _productsUsed |= PRODUCT_GRIDS; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.wizard.Product"); _productsUsed |= PRODUCT_DIALOGS; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.pivot.Product"); _productsUsed |= PRODUCT_PIVOT; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.shortcut.Product"); _productsUsed |= PRODUCT_SHORTCUT; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.editor.Product"); _productsUsed |= PRODUCT_CODE_EDITOR; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.rss.Product"); _productsUsed |= PRODUCT_FEEDREADER; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.treemap.Product"); _productsUsed |= PRODUCT_TREEMAP; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.chart.Product"); _productsUsed |= PRODUCT_CHARTS; } catch (Throwable e) { // } try { Class.forName("com.jidesoft.diff.Product"); _productsUsed |= PRODUCT_DIFF; } catch (Throwable e) { // } } return _productsUsed; } /** * Sets the products you will use. This is needed so that LookAndFeelFactory knows what UIDefault to initialize. For * example, if you use only JIDE Docking Framework and JIDE Grids, you should call * <code>setProductUsed(ProductNames.PRODUCT_DOCK | ProductNames.PRODUCT_GRIDS)</code> so that we don't initialize * UIDefaults needed by any other products. If you use this class as part of JIDE Common Layer open source project, * you should call <code>setProductUsed(ProductNames.PRODUCT_COMMON)</code>. If you want to use all JIDE products, * you should call <code>setProductUsed(ProductNames.PRODUCT_ALL)</code> * * @param productsUsed a bit-wise OR of product values defined in {@link com.jidesoft.utils.ProductNames}. */ public static void setProductsUsed(int productsUsed) { _productsUsed = productsUsed; } /** * Checks if the current L&F uses decorated frames. * * @return true if the current L&F uses decorated frames. Otherwise false. */ public static boolean isCurrentLnfDecorated() { return !isLnfInstalled(SYNTHETICA_LNF) || !isLnfInUse(SYNTHETICA_LNF); } public static void main(String[] args) { // LookAndFeelFactory.setLnfInstalled(AQUA_LNF, false); // System.out.println(LookAndFeelFactory.isLnfInstalled(AQUA_LNF)); } }
true
true
public void customize(UIDefaults defaults) { try { Class syntheticaClass = Class.forName(SYNTHETICA_LNF); Class syntheticaFrameBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaFrameBorder"); Class syntheticaPopupBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaPopupBorder"); Color toolbarBackground = new JToolBar().getBackground(); int products = LookAndFeelFactory.getProductsUsed(); { Object[] uiDefaults = { "JideTabbedPaneUI", "com.jidesoft.plaf.synthetica.SyntheticaJideTabbedPaneUI", "RangeSliderUI", "javax.swing.plaf.synth.SynthRangeSliderUI", "JideSplitPane.dividerSize", 6, "JideTabbedPane.foreground", UIManager.getColor("TabbedPane.foreground"), "JideTabbedPane.unselectedTabTextForeground", UIManager.getColor("TabbedPane.foreground"), "JideTabbedPane.tabAreaBackground", UIManager.getColor("control"), "JideTabbedPane.background", UIManager.getColor("control"), "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "JideButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "JideSplitButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "Icon.floating", Boolean.FALSE, "ContentContainer.background", toolbarBackground, "PopupMenu.border", syntheticaPopupBorder.newInstance(), "JideLabel.font", UIManager.getFont("Label.font"), "JideLabel.background", UIManager.getColor("Label.background"), "JideLabel.foreground", UIManager.getColor("Label.foreground"), }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_COMPONENTS) != 0) { Object[] uiDefaults = { "CollapsiblePane.background", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.emphasizedBackground", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.foreground", UIDefaultsLookup.getColor("TaskPane.titleForeground"), "CollapsiblePane.emphasizedForeground", UIDefaultsLookup.getColor("TaskPane.specialTitleForeground"), "CollapsiblePane.font", UIDefaultsLookup.getFont("TaskPane.font") != null ? UIDefaultsLookup.getFont("TaskPane.font") : UIDefaultsLookup.getFont("Label.font"), "StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 2, 2, 2)), "StatusBar.childrenOpaque", false, "StatusBar.paintResizableIcon", false, "OutlookTabbedPane.buttonStyle", JideButton.TOOLBAR_STYLE, "FloorTabbedPane.buttonStyle", JideButton.TOOLBAR_STYLE, }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_GRIDS) != 0) { Object[] uiDefaults = { "NestedTableHeaderUI", "com.jidesoft.plaf.synthetica.SyntheticaNestedTableHeaderUI", "EditableTableHeaderUI", "com.jidesoft.plaf.synthetica.SyntheticaEditableTableHeaderUI", "ExComboBoxUI", "com.jidesoft.plaf.synthetica.SyntheticaExComboBoxUI", "List.focusInputMap", new UIDefaults.LazyInputMap(new Object[]{ "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "HOME", "selectFirstRow", "shift HOME", "selectFirstRowExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRowChangeLead", "END", "selectLastRow", "shift END", "selectLastRowExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRowChangeLead", "PAGE_UP", "scrollUp", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDown", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "List.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[]{ "LEFT", "selectNextColumn", "KP_LEFT", "selectNextColumn", "shift LEFT", "selectNextColumnExtendSelection", "shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl shift LEFT", "selectNextColumnExtendSelection", "ctrl shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl LEFT", "selectNextColumnChangeLead", "ctrl KP_LEFT", "selectNextColumnChangeLead", "RIGHT", "selectPreviousColumn", "KP_RIGHT", "selectPreviousColumn", "shift RIGHT", "selectPreviousColumnExtendSelection", "shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl RIGHT", "selectPreviousColumnChangeLead", "ctrl KP_RIGHT", "selectPreviousColumnChangeLead", }), }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_ACTION) != 0) { Object[] uiDefaults = { "CommandBar.background", toolbarBackground, "CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderFloating", syntheticaFrameBorder.newInstance(), "CommandBar.titleBarBackground", UIDefaultsLookup.getColor("InternalFrame.activeTitleBackground"), "CommandBar.titleBarForeground", UIDefaultsLookup.getColor("InternalFrame.activeTitleForeground"), "CommandBarContainer.verticalGap", 0, }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_DOCK) != 0) { Object[] uiDefaults = { "Workspace.background", UIManager.getColor("control"), "DockableFrame.inactiveTitleForeground", UIDefaultsLookup.getColor("JYDocking.titlebar.foreground"), "DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("JYDocking.titlebar.active.foreground"), "DockableFrame.titleBorder", UIDefaultsLookup.getColor("JYDocking.contentPane.border.color"), "FrameContainer.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "DockableFrameTitlePane.hideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.closeButton.icon")), "DockableFrameTitlePane.hideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.closeButton.icon.hover")), "DockableFrameTitlePane.hideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.closeButton.icon")), "DockableFrameTitlePane.hideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.closeButton.icon.hover")), "DockableFrameTitlePane.floatIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon")), "DockableFrameTitlePane.floatRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.hover")), "DockableFrameTitlePane.floatActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon")), "DockableFrameTitlePane.floatRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.hover")), "DockableFrameTitlePane.unfloatIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.selected")), "DockableFrameTitlePane.unfloatRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.hover.selected")), "DockableFrameTitlePane.unfloatActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.selected")), "DockableFrameTitlePane.unfloatRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.hover.selected")), "DockableFrameTitlePane.autohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon")), "DockableFrameTitlePane.autohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon.hover")), "DockableFrameTitlePane.autohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon")), "DockableFrameTitlePane.autohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon.hover")), "DockableFrameTitlePane.stopAutohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.selected")), "DockableFrameTitlePane.stopAutohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.stopAutohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.selected")), "DockableFrameTitlePane.stopAutohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.hideAutohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon")), "DockableFrameTitlePane.hideAutohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon.hover")), "DockableFrameTitlePane.hideAutohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon")), "DockableFrameTitlePane.hideAutohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon.hover")), "DockableFrameTitlePane.maximizeIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon")), "DockableFrameTitlePane.maximizeRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover")), "DockableFrameTitlePane.maximizeActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon")), "DockableFrameTitlePane.maximizeRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover")), "DockableFrameTitlePane.restoreIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.selected")), "DockableFrameTitlePane.restoreRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.restoreActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.selected")), "DockableFrameTitlePane.restoreRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.use3dButtons", Boolean.FALSE, "DockableFrameTitlePane.contentFilledButtons", Boolean.FALSE, "DockableFrameTitlePane.buttonGap", 0, }; overwriteDefaults(defaults, uiDefaults); } Class<?> painterClass = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaJidePainter"); Method getInstanceMethod = painterClass.getMethod("getInstance"); Object painter = getInstanceMethod.invoke(null); UIDefaultsLookup.put(UIManager.getDefaults(), "Theme.painter", painter); } catch (Exception e) { e.printStackTrace(); } }
public void customize(UIDefaults defaults) { try { Class syntheticaClass = Class.forName(SYNTHETICA_LNF); Class syntheticaFrameBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaFrameBorder"); Class syntheticaPopupBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaPopupBorder"); Color toolbarBackground = new JToolBar().getBackground(); int products = LookAndFeelFactory.getProductsUsed(); { Object[] uiDefaults = { "JideTabbedPaneUI", "com.jidesoft.plaf.synthetica.SyntheticaJideTabbedPaneUI", "RangeSliderUI", "javax.swing.plaf.synth.SynthRangeSliderUI", "JideSplitPane.dividerSize", 6, "JideTabbedPane.foreground", UIManager.getColor("TabbedPane.foreground"), "JideTabbedPane.unselectedTabTextForeground", UIManager.getColor("TabbedPane.foreground"), "JideTabbedPane.tabAreaBackground", UIManager.getColor("control"), "JideTabbedPane.background", UIManager.getColor("control"), "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "JideButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "JideSplitButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "Icon.floating", Boolean.FALSE, "ContentContainer.background", toolbarBackground, "PopupMenu.border", syntheticaPopupBorder.newInstance(), "JideLabel.font", UIManager.getFont("Label.font"), "JideLabel.background", UIManager.getColor("Label.background"), "JideLabel.foreground", UIManager.getColor("Label.foreground"), }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_COMPONENTS) != 0) { Object[] uiDefaults = { "CollapsiblePane.background", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.emphasizedBackground", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.foreground", UIDefaultsLookup.getColor("TaskPane.titleForeground"), "CollapsiblePane.emphasizedForeground", UIDefaultsLookup.getColor("TaskPane.specialTitleForeground"), "CollapsiblePane.contentBackground", UIDefaultsLookup.getColor("Panel.background"), "CollapsiblePane.font", UIDefaultsLookup.getFont("TaskPane.font") != null ? UIDefaultsLookup.getFont("TaskPane.font") : UIDefaultsLookup.getFont("Label.font"), "StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 2, 2, 2)), "StatusBar.childrenOpaque", false, "StatusBar.paintResizableIcon", false, "OutlookTabbedPane.buttonStyle", JideButton.TOOLBAR_STYLE, "FloorTabbedPane.buttonStyle", JideButton.TOOLBAR_STYLE, }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_GRIDS) != 0) { Object[] uiDefaults = { "NestedTableHeaderUI", "com.jidesoft.plaf.synthetica.SyntheticaNestedTableHeaderUI", "EditableTableHeaderUI", "com.jidesoft.plaf.synthetica.SyntheticaEditableTableHeaderUI", "ExComboBoxUI", "com.jidesoft.plaf.synthetica.SyntheticaExComboBoxUI", "List.focusInputMap", new UIDefaults.LazyInputMap(new Object[]{ "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "HOME", "selectFirstRow", "shift HOME", "selectFirstRowExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRowChangeLead", "END", "selectLastRow", "shift END", "selectLastRowExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRowChangeLead", "PAGE_UP", "scrollUp", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDown", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "List.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[]{ "LEFT", "selectNextColumn", "KP_LEFT", "selectNextColumn", "shift LEFT", "selectNextColumnExtendSelection", "shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl shift LEFT", "selectNextColumnExtendSelection", "ctrl shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl LEFT", "selectNextColumnChangeLead", "ctrl KP_LEFT", "selectNextColumnChangeLead", "RIGHT", "selectPreviousColumn", "KP_RIGHT", "selectPreviousColumn", "shift RIGHT", "selectPreviousColumnExtendSelection", "shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl RIGHT", "selectPreviousColumnChangeLead", "ctrl KP_RIGHT", "selectPreviousColumnChangeLead", }), }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_ACTION) != 0) { Object[] uiDefaults = { "CommandBar.background", toolbarBackground, "CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderFloating", syntheticaFrameBorder.newInstance(), "CommandBar.titleBarBackground", UIDefaultsLookup.getColor("InternalFrame.activeTitleBackground"), "CommandBar.titleBarForeground", UIDefaultsLookup.getColor("InternalFrame.activeTitleForeground"), "CommandBarContainer.verticalGap", 0, }; overwriteDefaults(defaults, uiDefaults); } if ((products & PRODUCT_DOCK) != 0) { Object[] uiDefaults = { "Workspace.background", UIManager.getColor("control"), "DockableFrame.inactiveTitleForeground", UIDefaultsLookup.getColor("JYDocking.titlebar.foreground"), "DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("JYDocking.titlebar.active.foreground"), "DockableFrame.titleBorder", UIDefaultsLookup.getColor("JYDocking.contentPane.border.color"), "FrameContainer.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "DockableFrameTitlePane.hideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.closeButton.icon")), "DockableFrameTitlePane.hideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.closeButton.icon.hover")), "DockableFrameTitlePane.hideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.closeButton.icon")), "DockableFrameTitlePane.hideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.closeButton.icon.hover")), "DockableFrameTitlePane.floatIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon")), "DockableFrameTitlePane.floatRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.hover")), "DockableFrameTitlePane.floatActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon")), "DockableFrameTitlePane.floatRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.hover")), "DockableFrameTitlePane.unfloatIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.selected")), "DockableFrameTitlePane.unfloatRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.floatButton.icon.hover.selected")), "DockableFrameTitlePane.unfloatActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.selected")), "DockableFrameTitlePane.unfloatRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.floatButton.icon.hover.selected")), "DockableFrameTitlePane.autohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon")), "DockableFrameTitlePane.autohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon.hover")), "DockableFrameTitlePane.autohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon")), "DockableFrameTitlePane.autohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon.hover")), "DockableFrameTitlePane.stopAutohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.selected")), "DockableFrameTitlePane.stopAutohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.stopAutohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.selected")), "DockableFrameTitlePane.stopAutohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.hideAutohideIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon")), "DockableFrameTitlePane.hideAutohideRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.minimizeButton.icon.hover")), "DockableFrameTitlePane.hideAutohideActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon")), "DockableFrameTitlePane.hideAutohideRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.minimizeButton.icon.hover")), "DockableFrameTitlePane.maximizeIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon")), "DockableFrameTitlePane.maximizeRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover")), "DockableFrameTitlePane.maximizeActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon")), "DockableFrameTitlePane.maximizeRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover")), "DockableFrameTitlePane.restoreIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.selected")), "DockableFrameTitlePane.restoreRolloverIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.restoreActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.selected")), "DockableFrameTitlePane.restoreRolloverActiveIcon", loadSyntheticaIcon(syntheticaClass, ("JYDocking.titlebar.active.maximizeButton.icon.hover.selected")), "DockableFrameTitlePane.use3dButtons", Boolean.FALSE, "DockableFrameTitlePane.contentFilledButtons", Boolean.FALSE, "DockableFrameTitlePane.buttonGap", 0, }; overwriteDefaults(defaults, uiDefaults); } Class<?> painterClass = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaJidePainter"); Method getInstanceMethod = painterClass.getMethod("getInstance"); Object painter = getInstanceMethod.invoke(null); UIDefaultsLookup.put(UIManager.getDefaults(), "Theme.painter", painter); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/com/authdb/listeners/AuthDBEntityListener.java b/src/com/authdb/listeners/AuthDBEntityListener.java index f8fd9fc..bc5c93a 100644 --- a/src/com/authdb/listeners/AuthDBEntityListener.java +++ b/src/com/authdb/listeners/AuthDBEntityListener.java @@ -1,100 +1,100 @@ /** (C) Copyright 2011 Contex <[email protected]> This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. **/ package com.authdb.listeners; import org.bukkit.entity.Animals; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityListener; import org.bukkit.event.entity.EntityTargetEvent; import com.authdb.AuthDB; import com.authdb.util.Config; import com.authdb.util.Util; public class AuthDBEntityListener extends EntityListener { private final AuthDB plugin; public AuthDBEntityListener(AuthDB instance) { this.plugin = instance; } public void onEntityTarget(EntityTargetEvent event) { if (((event.getEntity() instanceof Monster)) && (event.getTarget() instanceof Player) && AuthDB.isAuthorized(event.getTarget().getEntityId()) == false) { Player p = (Player)event.getTarget(); if (!CheckGuest(p,Config.guests_mobtargeting)) { event.setCancelled(true); } } } public void onEntityDamage(EntityDamageEvent event) { if (event.getEntity() instanceof Player) { if(event.getCause().name().equals("FALL")) { Player p = (Player)event.getEntity(); if (!CheckGuest(p,Config.guests_health)) { event.setCancelled(true); } } else if(event.getCause().name().equals("ENTITY_ATTACK")) { Player p = (Player)event.getEntity(); EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; if ((e.getEntity() instanceof Player)) { Player t = (Player)e.getDamager(); if(!CheckGuest(t,Config.guests_pvp)) { if (!CheckGuest(p,Config.guests_health)) { event.setCancelled(true); } } } } } else if ((event.getEntity() instanceof Animals) || (event.getEntity() instanceof Monster)) { if (!(event instanceof EntityDamageByEntityEvent)) { return; } EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; Player t = (Player)e.getDamager(); - if ((e.getEntity() instanceof Player) && CheckGuest(t,Config.guests_mobdamage) == false) + if ((e.getDamager() instanceof Player) && CheckGuest(t,Config.guests_mobdamage) == false) { event.setCancelled(true); } } } public boolean CheckGuest(Player player,boolean what) { if(what) { if (!this.plugin.isRegistered(player.getName())) { return true; } } return false; } }
true
true
public void onEntityDamage(EntityDamageEvent event) { if (event.getEntity() instanceof Player) { if(event.getCause().name().equals("FALL")) { Player p = (Player)event.getEntity(); if (!CheckGuest(p,Config.guests_health)) { event.setCancelled(true); } } else if(event.getCause().name().equals("ENTITY_ATTACK")) { Player p = (Player)event.getEntity(); EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; if ((e.getEntity() instanceof Player)) { Player t = (Player)e.getDamager(); if(!CheckGuest(t,Config.guests_pvp)) { if (!CheckGuest(p,Config.guests_health)) { event.setCancelled(true); } } } } } else if ((event.getEntity() instanceof Animals) || (event.getEntity() instanceof Monster)) { if (!(event instanceof EntityDamageByEntityEvent)) { return; } EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; Player t = (Player)e.getDamager(); if ((e.getEntity() instanceof Player) && CheckGuest(t,Config.guests_mobdamage) == false) { event.setCancelled(true); } } }
public void onEntityDamage(EntityDamageEvent event) { if (event.getEntity() instanceof Player) { if(event.getCause().name().equals("FALL")) { Player p = (Player)event.getEntity(); if (!CheckGuest(p,Config.guests_health)) { event.setCancelled(true); } } else if(event.getCause().name().equals("ENTITY_ATTACK")) { Player p = (Player)event.getEntity(); EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; if ((e.getEntity() instanceof Player)) { Player t = (Player)e.getDamager(); if(!CheckGuest(t,Config.guests_pvp)) { if (!CheckGuest(p,Config.guests_health)) { event.setCancelled(true); } } } } } else if ((event.getEntity() instanceof Animals) || (event.getEntity() instanceof Monster)) { if (!(event instanceof EntityDamageByEntityEvent)) { return; } EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; Player t = (Player)e.getDamager(); if ((e.getDamager() instanceof Player) && CheckGuest(t,Config.guests_mobdamage) == false) { event.setCancelled(true); } } }
diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java index 00a669a080..903dc9756f 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java +++ b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java @@ -1,253 +1,253 @@ /** * Copyright Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.windowsazure.serviceruntime; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import org.junit.Test; /** * */ public class Protocol1RuntimeGoalStateClientTests { private final List<GoalState> goalStates = new LinkedList<GoalState>(); @Test public void addGoalStateChangedListenerAddsListener() { Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { @Override public RoleEnvironmentData deserialize(InputStream stream) { return null; } }; InputChannel inputChannel = new MockInputChannel(new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>1</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>2</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>" }); Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); client.addGoalStateChangedListener(new GoalStateChangedListener() { @Override public void goalStateChanged(GoalState newGoalState) { goalStates.add(newGoalState); } }); goalStates.clear(); try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(goalStates.size(), is(1)); assertThat(goalStates.get(0).getIncarnation().intValue(), is(2)); } @Test public void goalStateClientRestartsThread() { Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); GoalStateDeserializer goalStateDeserializer = new GoalStateDeserializer() { private final ChunkedGoalStateDeserializer deserializer = new ChunkedGoalStateDeserializer(); @Override public void initialize(InputStream inputStream) { deserializer.initialize(inputStream); } @Override public GoalState deserialize() { GoalState goalState = deserializer.deserialize(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } goalStates.add(goalState); return goalState; } }; RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { @Override public RoleEnvironmentData deserialize(InputStream stream) { return null; } }; InputChannel inputChannel = new MockInputChannel(new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>1</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>" }); Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); goalStates.clear(); try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { - Thread.sleep(1000); + Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(goalStates.size(), is(3)); } @Test public void getRoleEnvironmentDataReturnsDeserializedData() { Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); final RoleEnvironmentData data = new RoleEnvironmentData(null, null, null, null, null, false); RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { @Override public RoleEnvironmentData deserialize(InputStream stream) { return data; } }; InputChannel inputChannel = new MockInputChannel(new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>1</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>" }); Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); try { assertThat(client.getRoleEnvironmentData(), is(data)); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void removeGoalStateChangedListenerRemovesListener() { Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { @Override public RoleEnvironmentData deserialize(InputStream stream) { return null; } }; InputChannel inputChannel = new MockInputChannel(new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>1</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>2</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>" }); Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); GoalStateChangedListener listener = new GoalStateChangedListener() { @Override public void goalStateChanged(GoalState newGoalState) { goalStates.add(newGoalState); } }; client.addGoalStateChangedListener(listener); client.removeGoalStateChangedListener(listener); goalStates.clear(); try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(goalStates.size(), is(0)); } }
true
true
public void goalStateClientRestartsThread() { Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); GoalStateDeserializer goalStateDeserializer = new GoalStateDeserializer() { private final ChunkedGoalStateDeserializer deserializer = new ChunkedGoalStateDeserializer(); @Override public void initialize(InputStream inputStream) { deserializer.initialize(inputStream); } @Override public GoalState deserialize() { GoalState goalState = deserializer.deserialize(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } goalStates.add(goalState); return goalState; } }; RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { @Override public RoleEnvironmentData deserialize(InputStream stream) { return null; } }; InputChannel inputChannel = new MockInputChannel(new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>1</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>" }); Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); goalStates.clear(); try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(goalStates.size(), is(3)); }
public void goalStateClientRestartsThread() { Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); GoalStateDeserializer goalStateDeserializer = new GoalStateDeserializer() { private final ChunkedGoalStateDeserializer deserializer = new ChunkedGoalStateDeserializer(); @Override public void initialize(InputStream inputStream) { deserializer.initialize(inputStream); } @Override public GoalState deserialize() { GoalState goalState = deserializer.deserialize(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } goalStates.add(goalState); return goalState; } }; RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { @Override public RoleEnvironmentData deserialize(InputStream stream) { return null; } }; InputChannel inputChannel = new MockInputChannel(new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<GoalState>" + "<Incarnation>1</Incarnation>" + "<ExpectedState>Started</ExpectedState>" + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + "</GoalState>" }); Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); goalStates.clear(); try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } try { client.getCurrentGoalState(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(goalStates.size(), is(3)); }
diff --git a/MyParser.java b/MyParser.java index cb62ff8..2542228 100755 --- a/MyParser.java +++ b/MyParser.java @@ -1,794 +1,796 @@ //--------------------------------------------------------------------- // //--------------------------------------------------------------------- import java_cup.runtime.*; import java.util.Vector; class MyParser extends parser { //---------------------------------------------------------------- // Instance variables //---------------------------------------------------------------- private Lexer m_lexer; private ErrorPrinter m_errors; private int m_nNumErrors; private String m_strLastLexeme; private boolean m_bSyntaxError = true; private int m_nSavedLineNum; private SymbolTable m_symtab; //---------------------------------------------------------------- // //---------------------------------------------------------------- public MyParser(Lexer lexer, ErrorPrinter errors) { m_lexer = lexer; m_symtab = new SymbolTable(); m_errors = errors; m_nNumErrors = 0; } //---------------------------------------------------------------- // //---------------------------------------------------------------- public boolean Ok() { return (m_nNumErrors == 0); } //---------------------------------------------------------------- // //---------------------------------------------------------------- public Symbol scan() { Token t = m_lexer.GetToken(); // We'll save the last token read for error messages. // Sometimes, the token is lost reading for the next // token which can be null. m_strLastLexeme = t.GetLexeme(); switch(t.GetCode()) { case sym.T_ID: case sym.T_ID_U: case sym.T_STR_LITERAL: case sym.T_FLOAT_LITERAL: case sym.T_INT_LITERAL: case sym.T_CHAR_LITERAL: return (new Symbol(t.GetCode(), t.GetLexeme())); default: return (new Symbol(t.GetCode())); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void syntax_error(Symbol s) { } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void report_fatal_error(Symbol s) { m_nNumErrors++; if(m_bSyntaxError) { m_nNumErrors++; // It is possible that the error was detected // at the end of a line - in which case, s will // be null. Instead, we saved the last token // read in to give a more meaningful error // message. m_errors.print(Formatter.toString(ErrorMsg.syntax_error, m_strLastLexeme)); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void unrecovered_syntax_error(Symbol s) { report_fatal_error(s); } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void DisableSyntaxError() { m_bSyntaxError = false; } public void EnableSyntaxError() { m_bSyntaxError = true; } //---------------------------------------------------------------- // //---------------------------------------------------------------- public String GetFile() { return (m_lexer.getEPFilename()); } public int GetLineNum() { return (m_lexer.getLineNumber()); } public void SaveLineNum() { m_nSavedLineNum = m_lexer.getLineNumber(); } public int GetSavedLineNum() { return (m_nSavedLineNum); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoProgramStart() { // Opens the global scope. m_symtab.openScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoProgramEnd() { m_symtab.closeScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoVarDecl(Type type, Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } VarSTO sto = new VarSTO(id, type); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoExternDecl(Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } VarSTO sto = new VarSTO(id); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoConstDecl(Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } ConstSTO sto = new ConstSTO(id); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoTypedefDecl(Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } TypedefSTO sto = new TypedefSTO(id); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoStructdefDecl(String id) { if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } TypedefSTO sto = new TypedefSTO(id); m_symtab.insert(sto); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoFuncDecl_1(Type returnType, String id) { if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } FuncSTO sto = new FuncSTO(id); // Set return type sto.setReturnType(returnType); m_symtab.insert(sto); m_symtab.openScope(); m_symtab.setFunc(sto); // Set the function's level sto.setLevel(m_symtab.getLevel()); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoFuncDecl_2() { // Check #6c - no return statement for non-void type function FuncSTO stoFunc; if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoFuncDecl_2 says no proc!"); return; } if(!stoFunc.getReturnType().isVoid()) { if(!stoFunc.getHasReturnStatement()) { m_nNumErrors++; m_errors.print(ErrorMsg.error6c_Return_missing); } } m_symtab.closeScope(); m_symtab.setFunc(null); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoFormalParams(Vector<ParamSTO> params) { FuncSTO stoFunc; if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoFormalParams says no proc!"); return; } // Insert parameters stoFunc.setParameters(params); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoBlockOpen() { // Open a scope. m_symtab.openScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoBlockClose() { m_symtab.closeScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoAssignExpr(STO stoDes, STO stoValue) { // Check for previous errors in line and short circuit if(stoDes.isError()) { return stoDes; } if(stoValue.isError()) { return stoValue; } // Check #3a - illegal assignment - not modifiable L-value if(!stoDes.isModLValue()) { m_nNumErrors++; m_errors.print(ErrorMsg.error3a_Assign); return (new ErrorSTO("DoAssignExpr Error - not mod-L-Value")); } if(!stoValue.getType().isAssignable(stoDes.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error3b_Assign, stoValue.getType().getName(), stoDes.getType().getName())); return (new ErrorSTO("DoAssignExpr Error - bad types")); } return stoDes; } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoFuncCall(STO sto, Vector<ExprSTO> args) { if(!sto.isFunc()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName())); return (new ErrorSTO(sto.getName())); } // We know it's a function, do function call checks FuncSTO stoFunc =(FuncSTO)sto; // Check #5 // Check #5a - # args = # params if((stoFunc.getNumOfParams() != args.size())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams())); return (new ErrorSTO("DoFuncCall - # args")); } // Now we check each arg individually, accepting one error per arg boolean error_flag = false; for(int i = 0; i < args.size(); i++) { // For readability and shorter lines ParamSTO thisParam = stoFunc.getParameters().elementAt(i); ExprSTO thisArg = args.elementAt(i); // Check #5b - non-assignable arg for pass-by-value param if(!thisParam.isPassByReference()) { if(!thisArg.getType().isAssignable(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5c - arg type not equivalent to pass-by-ref param type else if(thisParam.isPassByReference()) { if(!thisArg.getType().isEquivalent(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5d - arg not modifiable l-value for pass by ref param else if(thisParam.isPassByReference()) { if(!thisArg.isModLValue()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName())); error_flag = true; } } } if(error_flag) { // Error occured in at least one arg, return error return (new ErrorSTO("DoFuncCall - Check 5")); } else + { // Func call legal, return function return type return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType())); + } } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator2_Dot(STO sto, String strID) { // Good place to do the struct checks return sto; } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator2_Array(STO sto) { // Good place to do the array checks return sto; } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator3_GlobalID(String strID) { STO sto; if((sto = m_symtab.accessGlobal(strID)) == null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error0g_Scope, strID)); sto = new ErrorSTO(strID); } return (sto); } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator3_ID(String strID) { STO sto; if((sto = m_symtab.access(strID)) == null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID)); sto = new ErrorSTO(strID); } return (sto); } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoQualIdent(String strID) { STO sto; if((sto = m_symtab.access(strID)) == null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID)); return (new ErrorSTO(strID)); } if(!sto.isTypedef()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_type, sto.getName())); return (new ErrorSTO(sto.getName())); } return (sto); } //---------------------------------------------------------------- // DoBinaryOp //---------------------------------------------------------------- STO DoBinaryOp(BinaryOp op, STO operand1, STO operand2) { // Check for previous errors in line and short circuit if(operand1.isError()) { return operand1; } if(operand2.isError()) { return operand2; } // Use BinaryOp.checkOperands() to perform error checks STO resultSTO = op.checkOperands(operand1, operand2); // Process/Print errors if(resultSTO.isError()) { m_nNumErrors++; m_errors.print(resultSTO.getName()); } return resultSTO; } //---------------------------------------------------------------- // DoUnaryOp //---------------------------------------------------------------- STO DoUnaryOp(UnaryOp op, STO operand) { // Check for previous errors in line and short circuit if(operand.isError()) { return operand; } // Use UnaryOp.checkOperand() to perform error checks STO resultSTO = op.checkOperand(operand); // Process/Print errors if(resultSTO.isError()) { m_nNumErrors++; m_errors.print(resultSTO.getName()); } return resultSTO; } //---------------------------------------------------------------- // DoWhileExpr //---------------------------------------------------------------- STO DoWhileExpr(STO stoExpr) { // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } // Check #4 - while expr - int or bool if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName())); return (new ErrorSTO("DoWhile error")); } return stoExpr; } //---------------------------------------------------------------- // DoIfExpr //---------------------------------------------------------------- STO DoIfExpr(STO stoExpr) { // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } // Check #4 - if expr - int or bool if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName())); return (new ErrorSTO("DoIf error")); } return stoExpr; } //---------------------------------------------------------------- // DoReturnStmt_1 //---------------------------------------------------------------- STO DoReturnStmt_1() { FuncSTO stoFunc; if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoReturnStmt_1 says no proc!"); return (new ErrorSTO("DoReturnStmt_1 Error")); } // Check #6a - no expr on non-void rtn if(!stoFunc.getReturnType().isVoid()) { m_nNumErrors++; m_errors.print(ErrorMsg.error6a_Return_expr); return (new ErrorSTO("DoReturnStmt_1 Error")); } // valid return statement, set func.hasReturnStatement stoFunc.setHasReturnStatement(true); return (new ExprSTO(stoFunc.getName() + " Return", new VoidType())); } //---------------------------------------------------------------- // DoReturnStmt_2 //---------------------------------------------------------------- STO DoReturnStmt_2(STO stoExpr) { FuncSTO stoFunc; // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoReturnStmt_2 says no proc!"); return (new ErrorSTO("DoReturnStmt_2 Error")); } // Check #6b - 1st bullet - rtn by val - rtn expr type not assignable to return if(!stoFunc.getReturnByRef()) { if(!stoExpr.getType().isAssignable(stoFunc.getReturnType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg. error6a_Return_type, stoExpr.getType().getName(), stoFunc.getReturnType().getName())); return (new ErrorSTO("DoReturnStmt_2 Error")); } } else { // Check #6b - 2nd bullet - rtn by ref - rtn expr type not equivalent to return type if(!stoExpr.getType().isEquivalent(stoFunc.getReturnType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error6b_Return_equiv, stoExpr.getType().getName(), stoFunc.getReturnType().getName())); return (new ErrorSTO("DoReturnStmt_2 Error")); } // Check #6b - 3rd bullet - rtn by ref - rtn expr not modLValue if(!stoExpr.isModLValue()) { m_nNumErrors++; m_errors.print(ErrorMsg.error6b_Return_modlval); return (new ErrorSTO("DoReturnStmt_2 Error")); } } // valid return statement, set func.hasReturnStatement stoFunc.setHasReturnStatement(true); return stoExpr; } //---------------------------------------------------------------- // DoExitStmt //---------------------------------------------------------------- STO DoExitStmt(STO stoExpr) { // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } // Check #7 - exit value assignable to int if(!stoExpr.getType().isAssignable(new IntType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error7_Exit, stoExpr.getType().getName())); } return stoExpr; } }
false
true
STO DoFuncCall(STO sto, Vector<ExprSTO> args) { if(!sto.isFunc()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName())); return (new ErrorSTO(sto.getName())); } // We know it's a function, do function call checks FuncSTO stoFunc =(FuncSTO)sto; // Check #5 // Check #5a - # args = # params if((stoFunc.getNumOfParams() != args.size())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams())); return (new ErrorSTO("DoFuncCall - # args")); } // Now we check each arg individually, accepting one error per arg boolean error_flag = false; for(int i = 0; i < args.size(); i++) { // For readability and shorter lines ParamSTO thisParam = stoFunc.getParameters().elementAt(i); ExprSTO thisArg = args.elementAt(i); // Check #5b - non-assignable arg for pass-by-value param if(!thisParam.isPassByReference()) { if(!thisArg.getType().isAssignable(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5c - arg type not equivalent to pass-by-ref param type else if(thisParam.isPassByReference()) { if(!thisArg.getType().isEquivalent(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5d - arg not modifiable l-value for pass by ref param else if(thisParam.isPassByReference()) { if(!thisArg.isModLValue()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName())); error_flag = true; } } } if(error_flag) { // Error occured in at least one arg, return error return (new ErrorSTO("DoFuncCall - Check 5")); } else // Func call legal, return function return type return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType())); }
STO DoFuncCall(STO sto, Vector<ExprSTO> args) { if(!sto.isFunc()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName())); return (new ErrorSTO(sto.getName())); } // We know it's a function, do function call checks FuncSTO stoFunc =(FuncSTO)sto; // Check #5 // Check #5a - # args = # params if((stoFunc.getNumOfParams() != args.size())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams())); return (new ErrorSTO("DoFuncCall - # args")); } // Now we check each arg individually, accepting one error per arg boolean error_flag = false; for(int i = 0; i < args.size(); i++) { // For readability and shorter lines ParamSTO thisParam = stoFunc.getParameters().elementAt(i); ExprSTO thisArg = args.elementAt(i); // Check #5b - non-assignable arg for pass-by-value param if(!thisParam.isPassByReference()) { if(!thisArg.getType().isAssignable(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5c - arg type not equivalent to pass-by-ref param type else if(thisParam.isPassByReference()) { if(!thisArg.getType().isEquivalent(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5d - arg not modifiable l-value for pass by ref param else if(thisParam.isPassByReference()) { if(!thisArg.isModLValue()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName())); error_flag = true; } } } if(error_flag) { // Error occured in at least one arg, return error return (new ErrorSTO("DoFuncCall - Check 5")); } else { // Func call legal, return function return type return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType())); } }
diff --git a/Sweng2012QuizAppTest/src/epfl/sweng/test/QuizQuestionTest.java b/Sweng2012QuizAppTest/src/epfl/sweng/test/QuizQuestionTest.java index 92a5b38..886e6c5 100644 --- a/Sweng2012QuizAppTest/src/epfl/sweng/test/QuizQuestionTest.java +++ b/Sweng2012QuizAppTest/src/epfl/sweng/test/QuizQuestionTest.java @@ -1,77 +1,78 @@ package epfl.sweng.test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.json.JSONException; import epfl.sweng.quizquestions.QuizQuestion; import epfl.sweng.servercomm.SwengHttpClientFactory; import epfl.sweng.tasks.IQuizServerCallback; import epfl.sweng.tasks.LoadRandomQuestion; import junit.framework.TestCase; /** * Unit test for JSON methods in QuizQuestion */ public class QuizQuestionTest extends TestCase { public static final String VALID_QUESTION_JSON = "{" + "question: 'What is the answer to life, the universe and everything?', " + "answers: ['42', '27']," + "solutionIndex: 0," + "tags : ['h2g2', 'trivia']," + "owner : 'anonymous'," + "id : '123'" + "}"; public void testQuestionOK() throws JSONException { String json = VALID_QUESTION_JSON; QuizQuestion result = new QuizQuestion(json); assertNotNull(result); String q = "The Question..."; List<String> answers = new ArrayList<String>(); answers.add("Answer 0"); Set<String> tags = new HashSet<String>(); tags.add("Tag"); final int id=13; final int rightAnswer=3; String owner = "Anonymous"; QuizQuestion result2 = new QuizQuestion(q, answers, rightAnswer, tags, id, owner); result2.addAnswerAtIndex("Answer 1", rightAnswer-2); result2.addAnswerAtIndex("Answer 2", rightAnswer-1); result2.addAnswerAtIndex("Answer 3", rightAnswer); result2.addAnswerAtIndex("Answer 4", rightAnswer+1); result2.addAnswerAtIndex("Answer 5", rightAnswer+2); String newAnswer = "Modififed Answer"; result2.addAnswerAtIndex(newAnswer, 2); assertEquals(newAnswer, result2.getAnswers()[2]); assertEquals(owner, result2.getOwner()); result2.removeAnswerAtIndex(rightAnswer); assertEquals(result2.getSolutionIndex(), -1); result2.setSolutionIndex(2); result2.removeAnswerAtIndex(answers.size()-1); result2.removeAnswerAtIndex(0); assertEquals(result2.getSolutionIndex(), 1); int currentSize = result2.getAnswers().length; - int newLastIndex = currentSize+3; + final int nbrOfNewAnswers = 3; + int newLastIndex = currentSize+nbrOfNewAnswers; result2.addAnswerAtIndex(newAnswer, currentSize+2); assertEquals(newLastIndex, result2.getAnswers().length); SwengHttpClientFactory.setInstance(null); new LoadRandomQuestion(new IQuizServerCallback() { public void onSuccess(QuizQuestion question) { } public void onError(Exception except) { } }).execute(); } }
true
true
public void testQuestionOK() throws JSONException { String json = VALID_QUESTION_JSON; QuizQuestion result = new QuizQuestion(json); assertNotNull(result); String q = "The Question..."; List<String> answers = new ArrayList<String>(); answers.add("Answer 0"); Set<String> tags = new HashSet<String>(); tags.add("Tag"); final int id=13; final int rightAnswer=3; String owner = "Anonymous"; QuizQuestion result2 = new QuizQuestion(q, answers, rightAnswer, tags, id, owner); result2.addAnswerAtIndex("Answer 1", rightAnswer-2); result2.addAnswerAtIndex("Answer 2", rightAnswer-1); result2.addAnswerAtIndex("Answer 3", rightAnswer); result2.addAnswerAtIndex("Answer 4", rightAnswer+1); result2.addAnswerAtIndex("Answer 5", rightAnswer+2); String newAnswer = "Modififed Answer"; result2.addAnswerAtIndex(newAnswer, 2); assertEquals(newAnswer, result2.getAnswers()[2]); assertEquals(owner, result2.getOwner()); result2.removeAnswerAtIndex(rightAnswer); assertEquals(result2.getSolutionIndex(), -1); result2.setSolutionIndex(2); result2.removeAnswerAtIndex(answers.size()-1); result2.removeAnswerAtIndex(0); assertEquals(result2.getSolutionIndex(), 1); int currentSize = result2.getAnswers().length; int newLastIndex = currentSize+3; result2.addAnswerAtIndex(newAnswer, currentSize+2); assertEquals(newLastIndex, result2.getAnswers().length); SwengHttpClientFactory.setInstance(null); new LoadRandomQuestion(new IQuizServerCallback() { public void onSuccess(QuizQuestion question) { } public void onError(Exception except) { } }).execute(); }
public void testQuestionOK() throws JSONException { String json = VALID_QUESTION_JSON; QuizQuestion result = new QuizQuestion(json); assertNotNull(result); String q = "The Question..."; List<String> answers = new ArrayList<String>(); answers.add("Answer 0"); Set<String> tags = new HashSet<String>(); tags.add("Tag"); final int id=13; final int rightAnswer=3; String owner = "Anonymous"; QuizQuestion result2 = new QuizQuestion(q, answers, rightAnswer, tags, id, owner); result2.addAnswerAtIndex("Answer 1", rightAnswer-2); result2.addAnswerAtIndex("Answer 2", rightAnswer-1); result2.addAnswerAtIndex("Answer 3", rightAnswer); result2.addAnswerAtIndex("Answer 4", rightAnswer+1); result2.addAnswerAtIndex("Answer 5", rightAnswer+2); String newAnswer = "Modififed Answer"; result2.addAnswerAtIndex(newAnswer, 2); assertEquals(newAnswer, result2.getAnswers()[2]); assertEquals(owner, result2.getOwner()); result2.removeAnswerAtIndex(rightAnswer); assertEquals(result2.getSolutionIndex(), -1); result2.setSolutionIndex(2); result2.removeAnswerAtIndex(answers.size()-1); result2.removeAnswerAtIndex(0); assertEquals(result2.getSolutionIndex(), 1); int currentSize = result2.getAnswers().length; final int nbrOfNewAnswers = 3; int newLastIndex = currentSize+nbrOfNewAnswers; result2.addAnswerAtIndex(newAnswer, currentSize+2); assertEquals(newLastIndex, result2.getAnswers().length); SwengHttpClientFactory.setInstance(null); new LoadRandomQuestion(new IQuizServerCallback() { public void onSuccess(QuizQuestion question) { } public void onError(Exception except) { } }).execute(); }
diff --git a/src/markehme/factionsplus/Cmds/CmdWarp.java b/src/markehme/factionsplus/Cmds/CmdWarp.java index c923a8f..364c161 100644 --- a/src/markehme/factionsplus/Cmds/CmdWarp.java +++ b/src/markehme/factionsplus/Cmds/CmdWarp.java @@ -1,205 +1,205 @@ package markehme.factionsplus.Cmds; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import markehme.factionsplus.FactionsPlus; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import com.massivecraft.factions.Board; import com.massivecraft.factions.Conf; import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; import com.massivecraft.factions.cmd.FCommand; import com.massivecraft.factions.integration.EssentialsFeatures; import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.zcore.util.SmokeUtil; public class CmdWarp extends FCommand { public CmdWarp() { this.aliases.add("warp"); this.requiredArgs.add("name"); this.optionalArgs.put("password", "string"); this.optionalArgs.put("faction", "string"); this.permission = Permission.HELP.node; this.disableOnLock = false; this.errorOnToManyArgs = false; senderMustBePlayer = true; senderMustBeMember = false; this.setHelpShort("warps to a specific warp"); } public void perform() { String warpname = this.argAsString(0); String setPassword = null; if(this.argAsString(1) != null) { setPassword = this.argAsString(1); } else { setPassword = "nullvalue"; } if(!FactionsPlus.permission.has(sender, "factionsplus.warp")) { sender.sendMessage(ChatColor.RED + "No permission!"); return; } Player player = (Player)sender; FPlayer fplayer = FPlayers.i.get(sender.getName()); Faction currentFaction = fplayer.getFaction(); File currentWarpFile = new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator + currentFaction.getId()); World world; // Check if player can teleport from enemy territory if(!Conf.homesTeleportAllowedFromEnemyTerritory && fplayer.isInEnemyTerritory() ){ - fplayer.msg("<b>You cannot teleport to your faction home while in the territory of an enemy faction."); + fplayer.msg("<b>You cannot teleport to your faction warp while in the territory of an enemy faction."); return; } // Check if player can teleport from different world /* * Move inside the try catch * * if(!Conf.homesTeleportAllowedFromDifferentWorld && player.getWorld().getUID() != world){ * fme.msg("<b>You cannot teleport to your faction home while in a different world."); * return; * } */ // Check for enemies nearby // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby Location loc = player.getLocation().clone(); if ( Conf.homesTeleportAllowedEnemyDistance > 0 && ! Board.getFactionAt(new FLocation(loc)).isSafeZone() && ( ! fplayer.isInOwnTerritory() || ( fplayer.isInOwnTerritory() && ! Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory))){ World w = loc.getWorld(); double x = loc.getX(); double y = loc.getY(); double z = loc.getZ(); for (Player p : me.getServer().getOnlinePlayers()) { if (p == null || !p.isOnline() || p.isDead() || p == fme || p.getWorld() != w) continue; FPlayer fp = FPlayers.i.get(p); if (fplayer.getRelationTo(fp) != Relation.ENEMY) continue; Location l = p.getLocation(); double dx = Math.abs(x - l.getX()); double dy = Math.abs(y - l.getY()); double dz = Math.abs(z - l.getZ()); double max = Conf.homesTeleportAllowedEnemyDistance; // box-shaped distance check if (dx > max || dy > max || dz > max) continue; fplayer.msg("<b>You cannot teleport to your faction warp while an enemy is within " + Conf.homesTeleportAllowedEnemyDistance + " blocks of you."); return; } } if (!currentWarpFile.exists()) { sender.sendMessage(ChatColor.RED + "Your faction has no warps!"); return; } try { FileInputStream fstream = new FileInputStream(currentWarpFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { //sender.sendMessage(strLine); String[] warp_data = strLine.split(":"); if(warp_data[0].equalsIgnoreCase(warpname)) { //sender.sendMessage("warp found: " + warp_data[0]); double x = Double.parseDouble(warp_data[1]); double y = Double.parseDouble(warp_data[2]); // y axis double z = Double.parseDouble(warp_data[3]); float Y = Float.parseFloat(warp_data[4]); // yaw float p = Float.parseFloat(warp_data[5]); world = (World) Bukkit.getServer().getWorld(warp_data[6]); if(warp_data.length == 8) { if(warp_data[7] != "nullvalue") { if(!setPassword.trim().equals(warp_data[7].trim())) { sender.sendMessage("Incorrect password, please use /f warp [warp] <password>"); return; } } } if(FactionsPlus.config.getInt("economy_costToWarp") > 0) { if (!payForCommand(FactionsPlus.config.getInt("economy_costToWarp"), "to teleport to this warp", "for teleporting to your faction home")) { return; } } player.sendMessage(ChatColor.RED + "Warped to " + ChatColor.WHITE + warpname); Location newTel = new Location(world, x, y, z, Y, p); if (EssentialsFeatures.handleTeleport(player, newTel)) return; // Create a smoke effect if (FactionsPlus.config.getBoolean("smokeEffectOnWarp")) { List<Location> smokeLocations = new ArrayList<Location>(); smokeLocations.add(player.getLocation()); smokeLocations.add(player.getLocation().add(0, 1, 0)); smokeLocations.add(newTel); smokeLocations.add(newTel.clone().add(0, 1, 0)); SmokeUtil.spawnCloudRandom(smokeLocations, 3f); } player.teleport(new Location(world, x, y, z, Y, p)); in.close(); return; } } player.sendMessage("Could not find the warp " + warpname); in.close(); } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "An internal error occured (02)"); } } }
true
true
public void perform() { String warpname = this.argAsString(0); String setPassword = null; if(this.argAsString(1) != null) { setPassword = this.argAsString(1); } else { setPassword = "nullvalue"; } if(!FactionsPlus.permission.has(sender, "factionsplus.warp")) { sender.sendMessage(ChatColor.RED + "No permission!"); return; } Player player = (Player)sender; FPlayer fplayer = FPlayers.i.get(sender.getName()); Faction currentFaction = fplayer.getFaction(); File currentWarpFile = new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator + currentFaction.getId()); World world; // Check if player can teleport from enemy territory if(!Conf.homesTeleportAllowedFromEnemyTerritory && fplayer.isInEnemyTerritory() ){ fplayer.msg("<b>You cannot teleport to your faction home while in the territory of an enemy faction."); return; } // Check if player can teleport from different world /* * Move inside the try catch * * if(!Conf.homesTeleportAllowedFromDifferentWorld && player.getWorld().getUID() != world){ * fme.msg("<b>You cannot teleport to your faction home while in a different world."); * return; * } */ // Check for enemies nearby // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby Location loc = player.getLocation().clone(); if ( Conf.homesTeleportAllowedEnemyDistance > 0 && ! Board.getFactionAt(new FLocation(loc)).isSafeZone() && ( ! fplayer.isInOwnTerritory() || ( fplayer.isInOwnTerritory() && ! Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory))){ World w = loc.getWorld(); double x = loc.getX(); double y = loc.getY(); double z = loc.getZ(); for (Player p : me.getServer().getOnlinePlayers()) { if (p == null || !p.isOnline() || p.isDead() || p == fme || p.getWorld() != w) continue; FPlayer fp = FPlayers.i.get(p); if (fplayer.getRelationTo(fp) != Relation.ENEMY) continue; Location l = p.getLocation(); double dx = Math.abs(x - l.getX()); double dy = Math.abs(y - l.getY()); double dz = Math.abs(z - l.getZ()); double max = Conf.homesTeleportAllowedEnemyDistance; // box-shaped distance check if (dx > max || dy > max || dz > max) continue; fplayer.msg("<b>You cannot teleport to your faction warp while an enemy is within " + Conf.homesTeleportAllowedEnemyDistance + " blocks of you."); return; } } if (!currentWarpFile.exists()) { sender.sendMessage(ChatColor.RED + "Your faction has no warps!"); return; } try { FileInputStream fstream = new FileInputStream(currentWarpFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { //sender.sendMessage(strLine); String[] warp_data = strLine.split(":"); if(warp_data[0].equalsIgnoreCase(warpname)) { //sender.sendMessage("warp found: " + warp_data[0]); double x = Double.parseDouble(warp_data[1]); double y = Double.parseDouble(warp_data[2]); // y axis double z = Double.parseDouble(warp_data[3]); float Y = Float.parseFloat(warp_data[4]); // yaw float p = Float.parseFloat(warp_data[5]); world = (World) Bukkit.getServer().getWorld(warp_data[6]); if(warp_data.length == 8) { if(warp_data[7] != "nullvalue") { if(!setPassword.trim().equals(warp_data[7].trim())) { sender.sendMessage("Incorrect password, please use /f warp [warp] <password>"); return; } } } if(FactionsPlus.config.getInt("economy_costToWarp") > 0) { if (!payForCommand(FactionsPlus.config.getInt("economy_costToWarp"), "to teleport to this warp", "for teleporting to your faction home")) { return; } } player.sendMessage(ChatColor.RED + "Warped to " + ChatColor.WHITE + warpname); Location newTel = new Location(world, x, y, z, Y, p); if (EssentialsFeatures.handleTeleport(player, newTel)) return; // Create a smoke effect if (FactionsPlus.config.getBoolean("smokeEffectOnWarp")) { List<Location> smokeLocations = new ArrayList<Location>(); smokeLocations.add(player.getLocation()); smokeLocations.add(player.getLocation().add(0, 1, 0)); smokeLocations.add(newTel); smokeLocations.add(newTel.clone().add(0, 1, 0)); SmokeUtil.spawnCloudRandom(smokeLocations, 3f); } player.teleport(new Location(world, x, y, z, Y, p)); in.close(); return; } } player.sendMessage("Could not find the warp " + warpname); in.close(); } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "An internal error occured (02)"); } }
public void perform() { String warpname = this.argAsString(0); String setPassword = null; if(this.argAsString(1) != null) { setPassword = this.argAsString(1); } else { setPassword = "nullvalue"; } if(!FactionsPlus.permission.has(sender, "factionsplus.warp")) { sender.sendMessage(ChatColor.RED + "No permission!"); return; } Player player = (Player)sender; FPlayer fplayer = FPlayers.i.get(sender.getName()); Faction currentFaction = fplayer.getFaction(); File currentWarpFile = new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator + currentFaction.getId()); World world; // Check if player can teleport from enemy territory if(!Conf.homesTeleportAllowedFromEnemyTerritory && fplayer.isInEnemyTerritory() ){ fplayer.msg("<b>You cannot teleport to your faction warp while in the territory of an enemy faction."); return; } // Check if player can teleport from different world /* * Move inside the try catch * * if(!Conf.homesTeleportAllowedFromDifferentWorld && player.getWorld().getUID() != world){ * fme.msg("<b>You cannot teleport to your faction home while in a different world."); * return; * } */ // Check for enemies nearby // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby Location loc = player.getLocation().clone(); if ( Conf.homesTeleportAllowedEnemyDistance > 0 && ! Board.getFactionAt(new FLocation(loc)).isSafeZone() && ( ! fplayer.isInOwnTerritory() || ( fplayer.isInOwnTerritory() && ! Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory))){ World w = loc.getWorld(); double x = loc.getX(); double y = loc.getY(); double z = loc.getZ(); for (Player p : me.getServer().getOnlinePlayers()) { if (p == null || !p.isOnline() || p.isDead() || p == fme || p.getWorld() != w) continue; FPlayer fp = FPlayers.i.get(p); if (fplayer.getRelationTo(fp) != Relation.ENEMY) continue; Location l = p.getLocation(); double dx = Math.abs(x - l.getX()); double dy = Math.abs(y - l.getY()); double dz = Math.abs(z - l.getZ()); double max = Conf.homesTeleportAllowedEnemyDistance; // box-shaped distance check if (dx > max || dy > max || dz > max) continue; fplayer.msg("<b>You cannot teleport to your faction warp while an enemy is within " + Conf.homesTeleportAllowedEnemyDistance + " blocks of you."); return; } } if (!currentWarpFile.exists()) { sender.sendMessage(ChatColor.RED + "Your faction has no warps!"); return; } try { FileInputStream fstream = new FileInputStream(currentWarpFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { //sender.sendMessage(strLine); String[] warp_data = strLine.split(":"); if(warp_data[0].equalsIgnoreCase(warpname)) { //sender.sendMessage("warp found: " + warp_data[0]); double x = Double.parseDouble(warp_data[1]); double y = Double.parseDouble(warp_data[2]); // y axis double z = Double.parseDouble(warp_data[3]); float Y = Float.parseFloat(warp_data[4]); // yaw float p = Float.parseFloat(warp_data[5]); world = (World) Bukkit.getServer().getWorld(warp_data[6]); if(warp_data.length == 8) { if(warp_data[7] != "nullvalue") { if(!setPassword.trim().equals(warp_data[7].trim())) { sender.sendMessage("Incorrect password, please use /f warp [warp] <password>"); return; } } } if(FactionsPlus.config.getInt("economy_costToWarp") > 0) { if (!payForCommand(FactionsPlus.config.getInt("economy_costToWarp"), "to teleport to this warp", "for teleporting to your faction home")) { return; } } player.sendMessage(ChatColor.RED + "Warped to " + ChatColor.WHITE + warpname); Location newTel = new Location(world, x, y, z, Y, p); if (EssentialsFeatures.handleTeleport(player, newTel)) return; // Create a smoke effect if (FactionsPlus.config.getBoolean("smokeEffectOnWarp")) { List<Location> smokeLocations = new ArrayList<Location>(); smokeLocations.add(player.getLocation()); smokeLocations.add(player.getLocation().add(0, 1, 0)); smokeLocations.add(newTel); smokeLocations.add(newTel.clone().add(0, 1, 0)); SmokeUtil.spawnCloudRandom(smokeLocations, 3f); } player.teleport(new Location(world, x, y, z, Y, p)); in.close(); return; } } player.sendMessage("Could not find the warp " + warpname); in.close(); } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "An internal error occured (02)"); } }
diff --git a/FRC2013/src/edu/wpi/first/wpilibj/templates/Think.java b/FRC2013/src/edu/wpi/first/wpilibj/templates/Think.java index 3e6df0b..0601d0c 100644 --- a/FRC2013/src/edu/wpi/first/wpilibj/templates/Think.java +++ b/FRC2013/src/edu/wpi/first/wpilibj/templates/Think.java @@ -1,88 +1,88 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; /** * * @author first1 */ public class Think { public static double newJoystickLeft; public static double newJoystickRight; public static boolean bShooterOn; public static double dShooterPower; public static boolean bClimb1; public static boolean bClimb2; public static double[] aimAdjust(double right, double left, CameraData cd){ return new double[]{left, right}; } /* * Converts the joystick values to usable values. * @param rawRight the value of the right joystick. * @param rawLeft the value of the left joystick. * @returns usable values as an array. The left value is at index 0 * The right is at index 1 */ public static double[] processJoystick(double rawRight, double rawLeft){ double[] retVal = new double[2]; if(rawLeft>0){ retVal[0]= rawLeft * rawLeft; } else{ retVal[0]= (-1) * (rawLeft * rawLeft); } if(rawRight>0){ retVal[1]= rawRight * rawRight; } else{ retVal[1]= (-1) * (rawRight * rawRight); } retVal[1] *= (-1); return retVal; } public static void robotThink(){ double[] temp = new double[2]; temp= processJoystick(Input.rightY, Input.leftY); newJoystickLeft= temp[0]; newJoystickRight= temp[1]; bShooterOn = Input.bTriggerDown; if (Input.bSlowSpeedRight||Input.bSlowSpeedLeft){ newJoystickLeft *= .75; newJoystickRight *= .75; } if (Input.bClimb1Left||Input.bClimb1Right){ bClimb1= true; } if (Input.bClimb2Left||Input.bClimb2Right){ bClimb2= true; } if (Input.bAim){ - temp = aimAdjust(newJoystickLeft, newJoystickRight, Input.cd); + // temp = aimAdjust(newJoystickLeft, newJoystickRight, Input.cd); newJoystickLeft= temp[0]; newJoystickRight= temp[1]; } if (bShooterOn== false){ dShooterPower = 0; } // Test Commit else { dShooterPower = 1.0; } } }
true
true
public static void robotThink(){ double[] temp = new double[2]; temp= processJoystick(Input.rightY, Input.leftY); newJoystickLeft= temp[0]; newJoystickRight= temp[1]; bShooterOn = Input.bTriggerDown; if (Input.bSlowSpeedRight||Input.bSlowSpeedLeft){ newJoystickLeft *= .75; newJoystickRight *= .75; } if (Input.bClimb1Left||Input.bClimb1Right){ bClimb1= true; } if (Input.bClimb2Left||Input.bClimb2Right){ bClimb2= true; } if (Input.bAim){ temp = aimAdjust(newJoystickLeft, newJoystickRight, Input.cd); newJoystickLeft= temp[0]; newJoystickRight= temp[1]; } if (bShooterOn== false){ dShooterPower = 0; } // Test Commit else { dShooterPower = 1.0; } }
public static void robotThink(){ double[] temp = new double[2]; temp= processJoystick(Input.rightY, Input.leftY); newJoystickLeft= temp[0]; newJoystickRight= temp[1]; bShooterOn = Input.bTriggerDown; if (Input.bSlowSpeedRight||Input.bSlowSpeedLeft){ newJoystickLeft *= .75; newJoystickRight *= .75; } if (Input.bClimb1Left||Input.bClimb1Right){ bClimb1= true; } if (Input.bClimb2Left||Input.bClimb2Right){ bClimb2= true; } if (Input.bAim){ // temp = aimAdjust(newJoystickLeft, newJoystickRight, Input.cd); newJoystickLeft= temp[0]; newJoystickRight= temp[1]; } if (bShooterOn== false){ dShooterPower = 0; } // Test Commit else { dShooterPower = 1.0; } }
diff --git a/chordest/src/test/java/chordest/chord/recognition/TemplateProducerTest.java b/chordest/src/test/java/chordest/chord/recognition/TemplateProducerTest.java index 617bcf1..fec9966 100644 --- a/chordest/src/test/java/chordest/chord/recognition/TemplateProducerTest.java +++ b/chordest/src/test/java/chordest/chord/recognition/TemplateProducerTest.java @@ -1,26 +1,26 @@ package chordest.chord.recognition; import java.util.Arrays; import junit.framework.Assert; import org.junit.Test; import chordest.chord.templates.TemplateProducer; import chordest.model.Chord; import chordest.model.Note; public class TemplateProducerTest { @Test public void testTemplateProducerSmoke() { - TemplateProducer p = new TemplateProducer(Note.A, true); + TemplateProducer p = new TemplateProducer(Note.A); double[] template = p.getTemplateFor(Chord.major(Note.A)); Assert.assertEquals(12, template.length); System.out.println(Arrays.toString(template)); template = p.getTemplateFor(Chord.major(Note.D)); System.out.println(Arrays.toString(template)); } }
true
true
public void testTemplateProducerSmoke() { TemplateProducer p = new TemplateProducer(Note.A, true); double[] template = p.getTemplateFor(Chord.major(Note.A)); Assert.assertEquals(12, template.length); System.out.println(Arrays.toString(template)); template = p.getTemplateFor(Chord.major(Note.D)); System.out.println(Arrays.toString(template)); }
public void testTemplateProducerSmoke() { TemplateProducer p = new TemplateProducer(Note.A); double[] template = p.getTemplateFor(Chord.major(Note.A)); Assert.assertEquals(12, template.length); System.out.println(Arrays.toString(template)); template = p.getTemplateFor(Chord.major(Note.D)); System.out.println(Arrays.toString(template)); }
diff --git a/src/com/github/noxan/aves/demo/AuthServer.java b/src/com/github/noxan/aves/demo/AuthServer.java index 706a5b9..5040ed7 100644 --- a/src/com/github/noxan/aves/demo/AuthServer.java +++ b/src/com/github/noxan/aves/demo/AuthServer.java @@ -1,71 +1,71 @@ /* * Copyright (c) 2012, noxan * See LICENSE for details. */ package com.github.noxan.aves.demo; import java.io.IOException; import com.github.noxan.aves.auth.AuthException; import com.github.noxan.aves.auth.accessor.UsernamePassword; import com.github.noxan.aves.auth.accessor.UsernamePasswordAccessor; import com.github.noxan.aves.auth.session.SessionManager; import com.github.noxan.aves.auth.storage.InMemoryUsernamePasswordStorage; import com.github.noxan.aves.net.Connection; import com.github.noxan.aves.server.Server; import com.github.noxan.aves.server.ServerAdapter; import com.github.noxan.aves.server.SocketServer; public class AuthServer extends ServerAdapter { public static void main(String[] args) { Server server = new SocketServer(new AuthServer()); try { server.start(); } catch(IOException e) { e.printStackTrace(); } } private InMemoryUsernamePasswordStorage userStorage; private SessionManager manager; public AuthServer() { userStorage = new InMemoryUsernamePasswordStorage(); userStorage.addUser("noxan", "123"); manager = new SessionManager(userStorage); } @Override public void readData(Connection connection, Object data) { String parts[] = ((String)data).trim().split(" "); String message = parts[0].toUpperCase(); String[] args = new String[parts.length - 1]; System.arraycopy(parts, 1, args, 0, args.length); try { switch(message) { - case "LOGIN": - if(args.length > 1) { - UsernamePasswordAccessor accessor = new UsernamePassword(args[0], args[1]); - try { - if(manager.requestSession(accessor, connection)) { - connection.write("Welcome to your session"); - } else { - connection.write("LOGIN ERROR: Session"); + case "LOGIN": + if(args.length > 1) { + UsernamePasswordAccessor accessor = new UsernamePassword(args[0], args[1]); + try { + if(manager.requestSession(accessor, connection)) { + connection.write("Welcome to your session"); + } else { + connection.write("LOGIN ERROR: Session"); + } + } catch(AuthException e) { + connection.write("LOGIN ERROR: " + e.getMessage()); } - } catch(AuthException e) { - connection.write("LOGIN ERROR: " + e.getMessage()); + } else { + connection.write("LOGIN ERROR: Invalid parameter(s)"); } - } else { - connection.write("LOGIN ERROR: Invalid parameter(s)"); - } - break; - case "LOGOUT": - connection.write("Not implemented yet!"); - break; + break; + case "LOGOUT": + connection.write("Not implemented yet!"); + break; } } catch(IOException e) { e.printStackTrace(); } } }
false
true
public void readData(Connection connection, Object data) { String parts[] = ((String)data).trim().split(" "); String message = parts[0].toUpperCase(); String[] args = new String[parts.length - 1]; System.arraycopy(parts, 1, args, 0, args.length); try { switch(message) { case "LOGIN": if(args.length > 1) { UsernamePasswordAccessor accessor = new UsernamePassword(args[0], args[1]); try { if(manager.requestSession(accessor, connection)) { connection.write("Welcome to your session"); } else { connection.write("LOGIN ERROR: Session"); } } catch(AuthException e) { connection.write("LOGIN ERROR: " + e.getMessage()); } } else { connection.write("LOGIN ERROR: Invalid parameter(s)"); } break; case "LOGOUT": connection.write("Not implemented yet!"); break; } } catch(IOException e) { e.printStackTrace(); } }
public void readData(Connection connection, Object data) { String parts[] = ((String)data).trim().split(" "); String message = parts[0].toUpperCase(); String[] args = new String[parts.length - 1]; System.arraycopy(parts, 1, args, 0, args.length); try { switch(message) { case "LOGIN": if(args.length > 1) { UsernamePasswordAccessor accessor = new UsernamePassword(args[0], args[1]); try { if(manager.requestSession(accessor, connection)) { connection.write("Welcome to your session"); } else { connection.write("LOGIN ERROR: Session"); } } catch(AuthException e) { connection.write("LOGIN ERROR: " + e.getMessage()); } } else { connection.write("LOGIN ERROR: Invalid parameter(s)"); } break; case "LOGOUT": connection.write("Not implemented yet!"); break; } } catch(IOException e) { e.printStackTrace(); } }
diff --git a/src/main/java/com/ngdb/entities/Market.java b/src/main/java/com/ngdb/entities/Market.java index 1eec4e2..5bbfac5 100644 --- a/src/main/java/com/ngdb/entities/Market.java +++ b/src/main/java/com/ngdb/entities/Market.java @@ -1,220 +1,220 @@ package com.ngdb.entities; import com.google.common.base.Predicate; import com.ngdb.entities.article.Article; import com.ngdb.entities.reference.Platform; import com.ngdb.entities.shop.ShopItem; import com.ngdb.entities.user.User; import com.ngdb.web.services.MailService; import com.ngdb.web.services.infrastructure.CurrentUser; import com.ngdb.web.services.infrastructure.UnavailableRatingException; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.apache.commons.lang.math.RandomUtils; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.ioc.annotations.Symbol; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.math.BigInteger; import java.util.*; import static com.google.common.collect.Collections2.filter; import static org.hibernate.criterion.Projections.count; import static org.hibernate.criterion.Restrictions.eq; public class Market { @Inject private Session session; @Inject private MailService mailService; @Inject @Symbol("host.url") private String hostUrl; @Inject private CurrentUser currentUser; private static Cache cache; private static final Logger LOG = LoggerFactory.getLogger(Market.class); static { CacheManager create = CacheManager.create(); cache = create.getCache("index.random.shopitem"); } public List<ShopItem> findRandomForSaleItems(int count) { List<ShopItem> forSaleItems = new ArrayList<ShopItem>(getShopItemsWithCover()); List<ShopItem> randomItems = new ArrayList<ShopItem>(); Set<Integer> ids = new HashSet<Integer>(); if(currentUser.isLogged()) { User user = currentUser.getUserFromDb(); forSaleItems.removeAll(user.getBasket().all()); forSaleItems.removeAll(user.getShop().all()); } if(count > forSaleItems.size()) { count = forSaleItems.size(); } while (ids.size() < count) { int randomIdx = RandomUtils.nextInt(forSaleItems.size()); if (ids.add(randomIdx)) { ShopItem shopItem = forSaleItems.get(randomIdx); - //shopItem = (ShopItem) session.load(ShopItem.class, shopItem.getId()); + shopItem = (ShopItem) session.load(ShopItem.class, shopItem.getId()); randomItems.add(shopItem); } } return randomItems; } private Collection<ShopItem> getShopItemsWithCover() { if (getCache() == null) { List<ShopItem> items = session.createQuery("SELECT si FROM ShopItem si WHERE si.sold = false").list(); items = new ArrayList<ShopItem>(filter(items, new Predicate<ShopItem>() { @Override public boolean apply(@Nullable ShopItem input) { return input.hasCover(); } })); cache.put(new Element("all", Collections.unmodifiableCollection(items))); } return (Collection<ShopItem>) getCache().getValue(); } private Element getCache() { return cache.get("all"); } public Long getNumForSaleItems() { return (Long) session.createCriteria(ShopItem.class).setProjection(count("id")).add(eq("sold", false)).setCacheable(true).setCacheRegion("cacheCount").uniqueResult(); } public Long getNumSoldItems() { return (Long) session.createCriteria(ShopItem.class).setProjection(count("id")).add(eq("sold", true)).setCacheable(true).setCacheRegion("cacheCount").uniqueResult(); } public void potentialBuyer(ShopItem shopItem, User potentialBuyer) { shopItem.addPotentialBuyer(potentialBuyer); } public void removeFromBasket(User potentialBuyer, ShopItem shopItem) { shopItem.removePotentialBuyer(potentialBuyer); } public void remove(ShopItem shopItem) { session.delete(shopItem); } public String getPriceForCurrentUser(ShopItem shopItem) { if(currentUser.isAnonymous()) { return shopItem.getPriceInCustomCurrency() + " "+shopItem.getCustomCurrencyAsSymbol(); } String preferredCurrency = currentUser.getPreferedCurrency(); try { return shopItem.getPriceIn(preferredCurrency) + " "+ currentUser.getPreferedCurrencyAsSymbol(); }catch(UnavailableRatingException e) { LOG.warn(e.getMessage()); return shopItem.getPriceInCustomCurrency() + " "+shopItem.getCustomCurrencyAsSymbol(); } } public long getNumGamesForSale() { return getNumAll("Game"); } public long getNumGamesForSale(Platform platform) { String platformeName = platform.getShortName(); String gameQuery = "SELECT id FROM Game WHERE platform_short_name = '"+ platformeName +"'"; String sqlQuery = "SELECT COUNT(id) FROM ShopItem WHERE sold = 0 AND article_id IN ("+gameQuery+")"; return ((BigInteger) session.createSQLQuery(sqlQuery).uniqueResult()).longValue(); } public long getNumGamesSold(Platform platform) { String platformeName = platform.getShortName(); String gameQuery = "SELECT id FROM Game WHERE platform_short_name = '"+ platformeName +"'"; String sqlQuery = "SELECT COUNT(id) FROM ShopItem WHERE sold = 1 AND article_id IN ("+gameQuery+")"; return ((BigInteger) session.createSQLQuery(sqlQuery).uniqueResult()).longValue(); } public long getNumHardwaresForSale() { return getNumAll("Hardware"); } public long getNumAccessoriesForSale() { return getNumAll("Accessory"); } public long getNumHardwaresForSaleBy(User user) { return getNum(user, "Hardware"); } public long getNumAccessoriesForSaleBy(User user) { return getNum(user, "Accessory"); } public long getNumGamesForSaleBy(User user) { return getNum(user, "Game"); } public void sell(ShopItem shopItem) { shopItem.sold(); session.merge(shopItem); cache.flush(); } private long getNumAll(String tableName) { return ((BigInteger) session.createSQLQuery("SELECT COUNT(id) FROM ShopItem WHERE sold = 0 AND article_id IN (SELECT id FROM "+tableName+")").uniqueResult()).longValue(); } private long getNum(User user, String tableName) { return ((BigInteger) session.createSQLQuery("SELECT COUNT(id) FROM ShopItem WHERE sold = 0 AND seller_id = "+user.getId()+" AND article_id IN (SELECT id FROM "+tableName+")").uniqueResult()).longValue(); } public void refresh() { cache.remove("all"); } public void tellWishers(final ShopItem shopItem) { Collection<User> wishers = shopItem.getWishers(); for (User wisher:wishers) { sendEmailToWisher(shopItem, wisher); } } private void sendEmailToWisher(final ShopItem shopItem, final User wisher) { Map<String, String> params = new HashMap<String, String>() {{ Article article = shopItem.getArticle(); User user = shopItem.getSeller(); String origin = article.getOriginTitle(); String platform = article.getPlatformShortName(); put("username", wisher.getLogin()); put("seller", user.getLogin()); put("articleTitle", shopItem.getTitle()); put("articleOrigin", origin); put("articlePlatform", platform); put("description", shopItem.getDetails()); put("price", shopItem.getPriceAsStringIn(wisher.getPreferedCurrency())); put("state", shopItem.getState().getTitle()); put("url", hostUrl + "market/"+user.getId()+"?platform=" + platform + "&origin=" + origin); }}; mailService.sendMail(wisher, "new_shopitem", "Your dream comes true, you could buy "+shopItem.getTitle(), params); } public ShopItem getLastShopItemForSaleOf(Long articleId) { String sql = "SELECT * FROM ShopItem WHERE sold = 0 AND article_id = " + articleId + " ORDER BY modification_date DESC"; SQLQuery query = session.createSQLQuery(sql).addEntity(ShopItem.class); return (ShopItem) query.list().get(0); } }
true
true
public List<ShopItem> findRandomForSaleItems(int count) { List<ShopItem> forSaleItems = new ArrayList<ShopItem>(getShopItemsWithCover()); List<ShopItem> randomItems = new ArrayList<ShopItem>(); Set<Integer> ids = new HashSet<Integer>(); if(currentUser.isLogged()) { User user = currentUser.getUserFromDb(); forSaleItems.removeAll(user.getBasket().all()); forSaleItems.removeAll(user.getShop().all()); } if(count > forSaleItems.size()) { count = forSaleItems.size(); } while (ids.size() < count) { int randomIdx = RandomUtils.nextInt(forSaleItems.size()); if (ids.add(randomIdx)) { ShopItem shopItem = forSaleItems.get(randomIdx); //shopItem = (ShopItem) session.load(ShopItem.class, shopItem.getId()); randomItems.add(shopItem); } } return randomItems; }
public List<ShopItem> findRandomForSaleItems(int count) { List<ShopItem> forSaleItems = new ArrayList<ShopItem>(getShopItemsWithCover()); List<ShopItem> randomItems = new ArrayList<ShopItem>(); Set<Integer> ids = new HashSet<Integer>(); if(currentUser.isLogged()) { User user = currentUser.getUserFromDb(); forSaleItems.removeAll(user.getBasket().all()); forSaleItems.removeAll(user.getShop().all()); } if(count > forSaleItems.size()) { count = forSaleItems.size(); } while (ids.size() < count) { int randomIdx = RandomUtils.nextInt(forSaleItems.size()); if (ids.add(randomIdx)) { ShopItem shopItem = forSaleItems.get(randomIdx); shopItem = (ShopItem) session.load(ShopItem.class, shopItem.getId()); randomItems.add(shopItem); } } return randomItems; }
diff --git a/src/Galaxy/Visitor/GalaxyToLoniConverter.java b/src/Galaxy/Visitor/GalaxyToLoniConverter.java index f27b0e4..405e6ae 100644 --- a/src/Galaxy/Visitor/GalaxyToLoniConverter.java +++ b/src/Galaxy/Visitor/GalaxyToLoniConverter.java @@ -1,156 +1,159 @@ package Galaxy.Visitor; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import Core.Pair; import Galaxy.Tree.Tool.Command; import Galaxy.Tree.Tool.Inputs; import Galaxy.Tree.Tool.Parameter; import Galaxy.Tree.Tool.Tool; import Galaxy.Tree.Workflow.ExternalInput; import Galaxy.Tree.Workflow.ExternalOutput; import Galaxy.Tree.Workflow.InputConnection; import Galaxy.Tree.Workflow.Position; import Galaxy.Tree.Workflow.Step; import Galaxy.Tree.Workflow.Workflow; import LONI.tree.Connection; import LONI.tree.Pipeline; import LONI.tree.GraphObject.Module; import LONI.tree.GraphObject.ModuleGroup; import Specification.GalaxySpecification; public class GalaxyToLoniConverter extends DFSVisitor { private static int MGROUP_COUNT=0; public String getModuleGroup(){ String s = "mgrp" + MGROUP_COUNT; MGROUP_COUNT++; return s; } public Object visit(Workflow workflow) { Pipeline pipeline; ModuleGroup mgroup; String annotation = workflow.getAnnotation(); String version = workflow.getFormatVersion(); String name = workflow.getName(); mgroup = new ModuleGroup(getModuleGroup(), name, "package", "version", annotation, "icon", 0, 0,0, false); for(Step s : workflow.getSteps()){ Pair<Module, List<Connection>> dat; dat = (Pair<Module, List<Connection>>) stepVisitor.visit(s); mgroup.getConnections().addConnections(dat.getElem2()); mgroup.getModules().add(dat.getElem1()); } pipeline = new Pipeline(version, mgroup); return pipeline; } { stepVisitor = new StepVisitor() { public Pair<Module, List<Connection>> visit(Step step){ Module genModule; List<Connection> genConnection = new LinkedList<Connection>(); Tool details = GalaxySpecification.getDatabase().getTool(step.getToolId()); String description; int posX; int posY; String id; String name; String package_; String executableVersion; String version; String location; int rotation; String icon; String advancedOptions; posX = step.getPosition().getFromLeft(); posY = step.getPosition().getFromTop(); - description = "Annotation: " + step.getAnnotation() + " " + "Tool Description: " + details.getDescription(); + description = "Annotation: " + step.getAnnotation() + " " + "Tool Description: " + ((details == null) ? "" : details.getDescription()); id = step.getToolId(); name = step.getName(); package_ = "package"; version = step.getToolVersion(); - executableVersion = details.getVersion(); + executableVersion = ((details == null) ? "" : details.getVersion()); location = "pipeline://localhost/"; rotation = 0; icon = "icon"; advancedOptions = ""; genModule = new Module(posX, posY, id, name, package_, version, executableVersion, description , location, rotation, icon, advancedOptions, false, false, false, false, "sourceCode", false, false, "mPIParallelEnv", "mPINumSlots", false); + List<LONI.tree.Parameter> inputs = null; + if (details != null) { + inputs = (List<LONI.tree.Parameter>) visit(details.getToolInputs()); + genModule.addInputs(inputs); + } - List<LONI.tree.Parameter> inputs = (List<LONI.tree.Parameter>) visit(details.getToolInputs()); - genModule.addInputs(inputs); for(String sink : step.getConnectionSinks()){ InputConnection src = step.getConnectionSource(sink); genConnection.add(new Connection( src.getSourceId()+"_"+src.getSourceName(), sink)); } return new Pair(genModule, genConnection); } public Object visit(Command command){ command.getInterpereter(); command.getCommand(); return null; } public Object visit(Inputs inputs){ inputs.getNginxUpload(); List<LONI.tree.Parameter> parameters = new ArrayList<LONI.tree.Parameter>(); for(Parameter input : inputs.getInputList()){ parameters.add((LONI.tree.Parameter) visit(input)); } return parameters; } public Object visit(Parameter parameter){ LONI.tree.Parameter loniParameter; parameter.getHelp(); parameter.getType(); String id = parameter.getName(); String name = parameter.getName(); String description = parameter.getLabel(); boolean enabled = true; boolean required = true; boolean predefined = false; boolean isMetadata = false; boolean isListFile = false; boolean isHideData = false; boolean includeTransformedParameter = false; int order = 0; String prefix = ""; boolean prefixSpaced = false; boolean prefixAllArgs = false; loniParameter = new LONI.tree.Parameter(id, name, description, enabled, required, predefined, isMetadata, isListFile, isHideData, includeTransformedParameter, order, prefix, prefixSpaced, prefixAllArgs); return loniParameter; } }; } }
false
true
public Pair<Module, List<Connection>> visit(Step step){ Module genModule; List<Connection> genConnection = new LinkedList<Connection>(); Tool details = GalaxySpecification.getDatabase().getTool(step.getToolId()); String description; int posX; int posY; String id; String name; String package_; String executableVersion; String version; String location; int rotation; String icon; String advancedOptions; posX = step.getPosition().getFromLeft(); posY = step.getPosition().getFromTop(); description = "Annotation: " + step.getAnnotation() + " " + "Tool Description: " + details.getDescription(); id = step.getToolId(); name = step.getName(); package_ = "package"; version = step.getToolVersion(); executableVersion = details.getVersion(); location = "pipeline://localhost/"; rotation = 0; icon = "icon"; advancedOptions = ""; genModule = new Module(posX, posY, id, name, package_, version, executableVersion, description , location, rotation, icon, advancedOptions, false, false, false, false, "sourceCode", false, false, "mPIParallelEnv", "mPINumSlots", false); List<LONI.tree.Parameter> inputs = (List<LONI.tree.Parameter>) visit(details.getToolInputs()); genModule.addInputs(inputs); for(String sink : step.getConnectionSinks()){ InputConnection src = step.getConnectionSource(sink); genConnection.add(new Connection( src.getSourceId()+"_"+src.getSourceName(), sink)); } return new Pair(genModule, genConnection); }
public Pair<Module, List<Connection>> visit(Step step){ Module genModule; List<Connection> genConnection = new LinkedList<Connection>(); Tool details = GalaxySpecification.getDatabase().getTool(step.getToolId()); String description; int posX; int posY; String id; String name; String package_; String executableVersion; String version; String location; int rotation; String icon; String advancedOptions; posX = step.getPosition().getFromLeft(); posY = step.getPosition().getFromTop(); description = "Annotation: " + step.getAnnotation() + " " + "Tool Description: " + ((details == null) ? "" : details.getDescription()); id = step.getToolId(); name = step.getName(); package_ = "package"; version = step.getToolVersion(); executableVersion = ((details == null) ? "" : details.getVersion()); location = "pipeline://localhost/"; rotation = 0; icon = "icon"; advancedOptions = ""; genModule = new Module(posX, posY, id, name, package_, version, executableVersion, description , location, rotation, icon, advancedOptions, false, false, false, false, "sourceCode", false, false, "mPIParallelEnv", "mPINumSlots", false); List<LONI.tree.Parameter> inputs = null; if (details != null) { inputs = (List<LONI.tree.Parameter>) visit(details.getToolInputs()); genModule.addInputs(inputs); } for(String sink : step.getConnectionSinks()){ InputConnection src = step.getConnectionSource(sink); genConnection.add(new Connection( src.getSourceId()+"_"+src.getSourceName(), sink)); } return new Pair(genModule, genConnection); }
diff --git a/trunk/org.mwc.asset.legacy/src/ASSET/Models/Movement/OnTopWaypoint.java b/trunk/org.mwc.asset.legacy/src/ASSET/Models/Movement/OnTopWaypoint.java index 9a1d19c5d..e6acb7fb4 100644 --- a/trunk/org.mwc.asset.legacy/src/ASSET/Models/Movement/OnTopWaypoint.java +++ b/trunk/org.mwc.asset.legacy/src/ASSET/Models/Movement/OnTopWaypoint.java @@ -1,990 +1,990 @@ package ASSET.Models.Movement; import ASSET.Models.Decision.Movement.TransitWaypoint; import ASSET.Models.Vessels.Helo; import ASSET.Participants.Category; import ASSET.Participants.CoreParticipant; import ASSET.Participants.Status; import ASSET.Scenario.CoreScenario; import ASSET.Util.SupportTesting; import MWC.Algorithms.EarthModels.CompletelyFlatEarth; import MWC.GenericData.*; import java.awt.geom.Point2D; /** * ASSET from PlanetMayo Ltd * User: Ian.Mayo * Date: 19-Aug-2003 * Time: 14:50:21 * Log: * $log: $ */ public class OnTopWaypoint extends WaypointVisitor { //////////////////////////////////////////////////////////// // member variables //////////////////////////////////////////////////////////// static final String _myType = "OnTop"; /** * the calculated distance to run and course change necessary to get to the next waypoint */ protected OnTopSolution _currentSolution = null; private static final double TINY_VALUE = 1e-14; //////////////////////////////////////////////////////////// // member methods //////////////////////////////////////////////////////////// public String getType() { return _myType; } /** * produce a simple demanded status from the complex path * * @param highLevelDemStatus * @param current * @param newTime * @param moves * @return the new status */ public Status step(HighLevelDemandedStatus highLevelDemStatus, Status current, long newTime, MovementCharacteristics moves, TurnAlgorithm turner) { // ok, loop through the available time while (current.getTime() < newTime) { // do we know where we're going? if (_currentSolution == null) { WorldLocation nextW = null; // have we been interrupted? if (super._interruptedLocation != null) { // yes, head back to it before we resume route nextW = _interruptedLocation; } else { // no, just continue through the points nextW = highLevelDemStatus.getCurrentTarget(); } // ok. do calc. if (nextW != null) { // nope - we've no idea where we're going _currentSolution = getSolution(nextW, current, moves, newTime, highLevelDemStatus.getSpeed()); } // ok, we continue in steady state if we don't have a next waypoint, or if we can't calculate a solution // to the next waypoint if ((nextW == null) || (_currentSolution == null)) { // hey, we're done! // check if we're dead close and can't make it - in which case we mark it as reached if (_currentSolution == null && (nextW != null)) { double rangeError = current.getLocation().subtract(nextW).getRange(); rangeError = MWC.Algorithms.Conversions.Degs2m(rangeError); if (rangeError < 10) { // are we resuming after interruption? if (_interruptedLocation != null) { // yes we were. We're ok now, get back on proper route _interruptedLocation = null; } else { // and mark that this point is reached highLevelDemStatus.nextWaypointVisited(); } } } // Carry on in steady state to complete the time step SimpleDemandedStatus sds = new SimpleDemandedStatus(newTime, current); // carry on doing the speed update if we haven't already if (highLevelDemStatus.getSpeed() != null) sds.setSpeed(highLevelDemStatus.getSpeed()); // and do the turn current = turner.doTurn(current, sds, moves, newTime); } } else { // yup - keep heading towards the next waypoint if (_currentSolution.demandedCourseChange != null) { // get the turn required double demandedTurn = _currentSolution.demandedCourseChange.doubleValue(); // remember the old course - so we can update the change required double oldCourse = current.getCourse(); // no, get turning current = doThisPartOfTheTurn(demandedTurn, moves, current, newTime, turner, -current.getLocation().getDepth()); // are we now on the correct course // so, still got some way to go... double amountTurned = current.getCourse() - oldCourse; double amountRemaining = demandedTurn - amountTurned; // trim the amount remaining to a realistic figure, silly. - if (amountRemaining < -360) + if (amountRemaining <= -360) amountRemaining += 360; - if (amountRemaining > 360) + if (amountRemaining >= 360) amountRemaining -= 360; // ok, update the amount of course change remaining if (Math.abs(amountRemaining) < 0.4) { _currentSolution.demandedCourseChange = null; } else { _currentSolution.demandedCourseChange = new Double(amountRemaining); } } else { if (_currentSolution.distanceToRun != null) { // ok carry on travelling along the straight section Double distance = _currentSolution.distanceToRun; // remember where we are WorldLocation origin = new WorldLocation(current.getLocation()); // ok, move forward as far on the straight course as we can current = processStraightCourse(distance, current, newTime, highLevelDemStatus, turner, moves); // ok, see how far we have to go... WorldVector travelled = current.getLocation().subtract(origin); double rngDegs = travelled.getRange(); double rngM = MWC.Algorithms.Conversions.Degs2m(rngDegs); // hmm, how far is left? double remainingDistance = distance.doubleValue() - rngM; // ok - are we practically there? if (remainingDistance < 0.1) { // hey - we're done! _currentSolution.distanceToRun = null; _currentSolution = null; // and mark that this point is reached // are we returning after interruption? if (_interruptedLocation != null) { // yes. get back onto our proper course _interruptedLocation = null; } else { // no, just continue onto the next waypoint. highLevelDemStatus.nextWaypointVisited(); } } else { _currentSolution.distanceToRun = new Double(remainingDistance); } } else { // hey, all done! Clear the solution _currentSolution = null; } } } } return current; } /** * note that our parent behaviour has been interrupted. If we have a calculated the time/distance * to the next waypoint these calculations may become invalid - we need to clear them in order that they * be re-calculated next time we actually get called. */ public void forgetCalculatedRoute() { // _currentSolution = null; } /** * calculate a viable solution to get OnTop of the target location * * @param nextW the location we're heading for * @param current our current status * @param moves our movement characteristics * @param newTime the finish time * @return the solution to this manoeuvre */ protected OnTopSolution getSolution(WorldLocation nextW, Status current, MovementCharacteristics moves, long newTime, WorldSpeed demSpeed) { OnTopSolution res = null; // ok. sort out the results data // double r = moves.getTurningCircleDiameter(current.getSpeed().getValueIn(WorldSpeed.M_sec)); // now the initial position // where's the center of the area? WorldArea coverage = new WorldArea(current.getLocation(), nextW); WorldLocation centre = coverage.getCentre(); // and create the corners WorldVector thisOffset = current.getLocation().subtract(centre); double dx = MWC.Algorithms.Conversions.Degs2m(thisOffset.getRange()) * Math.sin(thisOffset.getBearing()); double dy = MWC.Algorithms.Conversions.Degs2m(thisOffset.getRange()) * Math.cos(thisOffset.getBearing()); Point2D startPoint = new Point2D.Double(dx, dy); thisOffset = nextW.subtract(centre); dx = MWC.Algorithms.Conversions.Degs2m(thisOffset.getRange()) * Math.sin(thisOffset.getBearing()); dy = MWC.Algorithms.Conversions.Degs2m(thisOffset.getRange()) * Math.cos(thisOffset.getBearing()); Point2D endPoint = new Point2D.Double(dx, dy); double course1Rads = Math.toRadians(current.getCourse()); if (course1Rads < 0) course1Rads += Math.PI * 2; double speed1 = current.getSpeed().getValueIn(WorldSpeed.M_sec); double speed2; if (demSpeed != null) speed2 = demSpeed.getValueIn(WorldSpeed.M_sec); else speed2 = current.getSpeed().getValueIn(WorldSpeed.M_sec); double spd1_rate = getTurnRateFor(moves, speed1); double rad1 = speed1 / spd1_rate; // ok. now do the permutations //////////////////////////////////////////////////////////// // CASE 1 //////////////////////////////////////////////////////////// CaseSolver firstCase = new CaseSolver() { public Point2D firstOrigin(Point2D point, double radius, double courseRads) { double xVal = point.getX() - radius * Math.cos(courseRads); double yVal = point.getY() + radius * Math.sin(courseRads); return new Point2D.Double(xVal, yVal); } public double alpha1(double hyp, double rad1a, double hDelta, double kDelta) { return Math.asin(rad1a / hyp) + Math.atan2(hDelta, -kDelta); } public double zLength(double hDelta, double alpha1, double rad1a) { return Math.abs((hDelta + rad1a * Math.cos(alpha1)) / Math.sin(alpha1)); } public double theta1(double alpha1, double p1) { return alpha1 - p1; } public OnTopSolution populateResults(double initialTurnDegs, double zLen, boolean isPossible, double totalTime) { return new OnTopSolution(-initialTurnDegs, zLen, isPossible, totalTime); } }; //////////////////////////////////////////////////////////// // CASE 2 //////////////////////////////////////////////////////////// CaseSolver secondCase = new CaseSolver() { public Point2D firstOrigin(Point2D point, double radius, double courseRads) { double xVal = point.getX() + radius * Math.cos(courseRads); double yVal = point.getY() - radius * Math.sin(courseRads); return new Point2D.Double(xVal, yVal); } // public Point2D secondOrigin(Point2D point, // double radius, // double courseRads) // { // double xVal = point.getX() - radius * Math.cos(courseRads); // double yVal = point.getY() + radius * Math.sin(courseRads); // return new Point2D.Double(xVal, yVal); // } public double alpha1(double hyp, double rad1a, double hDelta, double kDelta) { return Math.asin(-rad1a / hyp) - Math.atan2(hDelta, kDelta); } public double zLength(double hDelta, double alpha1, double rad1a) { return Math.abs((-hDelta - rad1a * Math.cos(alpha1)) / Math.sin(alpha1)); } public double theta1(double alpha1, double p1) { return p1 - alpha1; } public OnTopSolution populateResults(double initialTurnDegs, double zLen, boolean isPossible, double totalTime) { return new OnTopSolution(initialTurnDegs, zLen, isPossible, totalTime); } }; // ok - get going OnTopSolution firstSol = calcCombination(startPoint, endPoint, firstCase, course1Rads, rad1, speed1, speed2, moves); OnTopSolution secondSol = calcCombination(startPoint, endPoint, secondCase, course1Rads, rad1, speed1, speed2, moves); if (firstSol.isPossible) res = firstSol; if (secondSol.isPossible) { if (secondSol.timeTaken < firstSol.timeTaken) res = secondSol; } return res; } public static OnTopSolution calcCombination(Point2D startPoint, Point2D endPoint, CaseSolver thisCase, double course1Rads, double rad1, double speed1, double speed2, MovementCharacteristics moves) { OnTopSolution res = null; // 2. ok, first do the origins Point2D firstOrigin = thisCase.firstOrigin(startPoint, rad1, course1Rads); // 2a. now the h delta double hDelta = firstOrigin.getX() - endPoint.getX(); // and the k delta double kDelta = firstOrigin.getY() - endPoint.getY(); // 3. do we need to overcome the div/0 error? // NOPE // 4. check for overlapping circles double h2 = Math.pow(hDelta, 2); double k2 = Math.pow(kDelta, 2); double hyp = Math.sqrt(h2 + k2); if (hyp < rad1) { res = new OnTopSolution(false, OnTopSolution.NO_ROOM_FOR_TURN); return res; } // 5. Calc start & end turn points double p1 = Math.atan2(startPoint.getY() - firstOrigin.getY(), startPoint.getX() - firstOrigin.getX()); // and trim away if (p1 < 0) p1 += Math.PI * 2; // 6. Now get the tan points double alpha1 = thisCase.alpha1(hyp, rad1, hDelta, kDelta); // and trim them if (alpha1 < 0) alpha1 += Math.PI * 2; // 7. now the leg length // pad out the alpha if it's zero if (alpha1 == 0) alpha1 += TINY_VALUE; double initialTurn = thisCase.theta1(alpha1, p1); double zLen; if (Math.abs(initialTurn) <= TINY_VALUE) { double xDelta = endPoint.getX() - startPoint.getX(); double yDelta = endPoint.getY() - startPoint.getY(); zLen = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)); } else { zLen = thisCase.zLength(hDelta, alpha1, rad1); } // 8. and the accel rates double accelRate; if (speed2 > 1) accelRate = moves.getAccelRate().getValueIn(WorldAcceleration.M_sec_sec); else accelRate = moves.getDecelRate().getValueIn(WorldAcceleration.M_sec_sec); double accelTime = (speed2 - speed1) / accelRate; double len = speed1 * accelTime + accelRate * Math.pow(accelTime, 2) / 2; // is it possible? if (len > zLen) { res = new OnTopSolution(false, OnTopSolution.NO_ROOM_FOR_ACCELERATION); return res; } // 9. calc the straight time double straightTime = (zLen - len) / speed2 + accelTime; // 10. and the turn angles // and do some trimming if (initialTurn < 0) initialTurn += Math.PI * 2; // 11. now the overall time double firstTurnRate = moves.calculateTurnRate(speed1); double time1 = initialTurn / (firstTurnRate / 180 * Math.PI); double totalTime = time1 + straightTime; double initialTurnDegs = MWC.Algorithms.Conversions.Rads2Degs(initialTurn); res = thisCase.populateResults(initialTurnDegs, zLen, true, totalTime); return res; } /** * interface for set of algorithms solving single turn permutation */ private static interface CaseSolver { /** * calculate the centre of the first turn * * @param point * @param radius * @param courseRads * @return */ public Point2D firstOrigin(Point2D point, double radius, double courseRads); /** * what's the exit angle of the first turn * * @param hyp * @param rad1 * @param hDelta * @param kDelta * @return */ public double alpha1(double hyp, double rad1, double hDelta, double kDelta); /** * how far do we travel in a straight line? * * @param hDelta * @param alpha1 * @param rad1 * @return */ public double zLength(double hDelta, double alpha1, double rad1); /** * what's the total angle travelled for the first turn? * * @param alpha1 * @param p1 * @return */ double theta1(double alpha1, double p1); /** * populate the final results object (including setting the direction of the turns * * @param initialTurnDegs the initial turn we have to make * @param zLen how far to travel in a straight line * @param isPossible whether the turn is possible * @param totalTime the total time for this combination * @return */ OnTopSolution populateResults(double initialTurnDegs, double zLen, boolean isPossible, double totalTime); } //////////////////////////////////////////////////////////// // model support //////////////////////////////////////////////////////////// /** * get the version details for this model. * <pre> * $Log: OnTopWaypoint.java,v $ * Revision 1.1 2006/08/08 14:21:50 Ian.Mayo * Second import * * Revision 1.1 2006/08/07 12:25:58 Ian.Mayo * First versions * * Revision 1.32 2005/04/15 14:11:59 Ian.Mayo * Update tests to reflect new scenario step cycle * * Revision 1.31 2004/08/31 09:36:48 Ian.Mayo * Rename inner static tests to match signature **Test to make automated testing more consistent * <p/> * Revision 1.30 2004/08/25 11:21:01 Ian.Mayo * Remove main methods which just run junit tests * <p/> * Revision 1.29 2004/08/20 13:32:44 Ian.Mayo * Implement inspection recommendations to overcome hidden parent objects, let CoreDecision handle the activity bits. * <p/> * Revision 1.28 2004/08/16 09:16:19 Ian.Mayo * Respect changed processing of tester recording to file (it needed a valid scenario object) * <p/> * Revision 1.27 2004/08/09 15:50:42 Ian.Mayo * Refactor category types into Force, Environment, Type sub-classes * <p/> * Revision 1.26 2004/08/06 12:56:25 Ian.Mayo * Include current status when firing interruption * <p/> * Revision 1.25 2004/08/06 11:14:39 Ian.Mayo * Introduce interruptable behaviours, and recalc waypoint route after interruption * <p/> * Revision 1.24 2004/08/06 10:21:24 Ian.Mayo * Manage investigate height * <p/> * Revision 1.23 2004/05/24 15:09:08 Ian.Mayo * Commit changes conducted at home * <p/> * Revision 1.1.1.1 2004/03/04 20:30:53 ian * no message * <p/> * Revision 1.22 2004/02/16 13:38:55 Ian.Mayo * General improvements * <p/> * Revision 1.20 2003/12/10 16:16:14 Ian.Mayo * Minor tidying * <p/> * Revision 1.19 2003/12/08 13:17:05 Ian.Mayo * Implement OnTop alg * <p/> * <p/> * </pre> */ public String getVersion() { return "$Date$"; } //////////////////////////////////////////////////////////// // class to hold the demanded course to head to //////////////////////////////////////////////////////////// protected static class OnTopSolution { /** * the course change we need to make (-ve means turn to port) */ protected Double demandedCourseChange = null; /** * the distance to travel once we're on course */ protected Double distanceToRun = null; /** * whether this solution is possible */ protected boolean isPossible = false; /** * and the total time taken (secs) */ protected double timeTaken; /** * reason for failure */ protected String failureReason = null; /** * we can't fit in the turn (too close) */ private static final String NO_ROOM_FOR_ACCELERATION = "NO ROOM FOR ACCELERATION"; /** * we can't fit in the acceleration (straight not long enough) */ private static final String NO_ROOM_FOR_TURN = "NO ROOM FOR TURN"; /** * constructor = setup data * * @param initialCourse * @param zLen * @param possible * @param totalTime */ public OnTopSolution(double initialCourse, double zLen, boolean possible, double totalTime) { demandedCourseChange = new Double(initialCourse); distanceToRun = new Double(zLen); isPossible = possible; timeTaken = totalTime; } /** * quick constructor for when the f*cker isn't possible anyway * * @param possible * @param reason - why we failed */ public OnTopSolution(boolean possible, String reason) { isPossible = possible; failureReason = reason; } } ////////////////////////////////////////////////////////////////////////////////////////////////// // testing for this class ////////////////////////////////////////////////////////////////////////////////////////////////// static public class OnTopWaypointTest extends SupportTesting { static public final String TEST_ALL_TEST_TYPE = "UNIT"; public OnTopWaypointTest(final String val) { super(val); } public void testOnTopRoute() { WorldLocation.setModel(new CompletelyFlatEarth()); // setup ownship Status startStat = new Status(12, 10); WorldLocation origin = SupportTesting.createLocation(0, 0); origin.setDepth(-300); startStat.setLocation(origin); startStat.setCourse(0); startStat.setSpeed(new WorldSpeed(12, WorldSpeed.M_sec)); Helo helo = new Helo(12); helo.setName("Merlin_Test"); // and now the movement chars MovementCharacteristics moves = new ASSET.Models.Movement.HeloMovementCharacteristics("merlin", new WorldAcceleration(Math.PI / 40, WorldAcceleration.M_sec_sec), new WorldAcceleration(Math.PI / 40, WorldAcceleration.M_sec_sec), 0, new WorldSpeed(200, WorldSpeed.Kts), new WorldSpeed(20, WorldSpeed.Kts), new WorldSpeed(20, WorldSpeed.Kts), new WorldSpeed(20, WorldSpeed.Kts), new WorldDistance(3000, WorldDistance.YARDS), new WorldDistance(30, WorldDistance.YARDS), 3, new WorldSpeed(20, WorldSpeed.Kts), new WorldSpeed(60, WorldSpeed.Kts)); helo.setMovementChars(moves); helo.setStatus(startStat); helo.setCategory(new Category(Category.Force.BLUE, Category.Environment.AIRBORNE, Category.Type.HELO)); // and create the behaviour WorldLocation loc1 = SupportTesting.createLocation(2099, 1099); loc1.setDepth(-300); WorldLocation loc2 = SupportTesting.createLocation(2330, -2694); loc2.setDepth(-300); WorldLocation loc3 = SupportTesting.createLocation(3120, -123); loc3.setDepth(-100); WorldLocation loc4 = SupportTesting.createLocation(4310, 1326); loc4.setDepth(-300); WorldLocation loc5 = SupportTesting.createLocation(1310, 2326); loc5.setDepth(-300); WorldLocation loc6 = SupportTesting.createLocation(2310, 326); loc6.setDepth(-1300); WorldLocation loc7 = SupportTesting.createLocation(3310, 2326); loc7.setDepth(-300); WorldLocation loc8 = SupportTesting.createLocation(4310, 3326); loc8.setDepth(-300); WorldPath destinations = new WorldPath(); destinations.addPoint(loc1); destinations.addPoint(loc2); destinations.addPoint(loc3); destinations.addPoint(loc4); destinations.addPoint(loc5); destinations.addPoint(loc6); destinations.addPoint(loc7); destinations.addPoint(loc8); ASSET.Models.Decision.Movement.TransitWaypoint transit = new TransitWaypoint(destinations, new WorldSpeed(12, WorldSpeed.M_sec), false, WaypointVisitor.createVisitor(OnTopWaypoint._myType)); helo.setDecisionModel(transit); CoreScenario cs = new CoreScenario(); cs.setScenarioStepTime(3000); cs.addParticipant(12, helo); //////////////////////////////////////////////////////////// // add in our various listeners //////////////////////////////////////////////////////////// boolean recordData = true; super.startListeningTo(helo, "on_top", recordData, recordData, recordData, cs); long stepLimit = 800; for (int i = 0; i < stepLimit; i++) { cs.step(); } super.endRecording(cs); // also output the series of locations to replay file super.outputTheseToRep("on_top_points.rep", destinations); // check we're on the correct final course assertEquals("on correct course", 46, helo.getStatus().getCourse(), 1); // check we're at the correct finish point WorldLocation endPoint = new WorldLocation(0.0776899319,0.089914902, 0); double rng = helo.getStatus().getLocation().subtract(endPoint).getRange(); rng = MWC.Algorithms.Conversions.Degs2m(rng); assertEquals("at correct end point:" + helo.getStatus().getLocation().getLat() + "," + helo.getStatus().getLocation().getLong(), 0, rng, 1); // also output the series of locations to replay file super.outputTheseToRep("on_top_points.rep", destinations); } public void testCases() { // and now the movement chars MovementCharacteristics moves = new ASSET.Models.Movement.HeloMovementCharacteristics("merlin", new WorldAcceleration(Math.PI / 40, WorldAcceleration.M_sec_sec), new WorldAcceleration(Math.PI / 40, WorldAcceleration.M_sec_sec), 0, new WorldSpeed(200, WorldSpeed.Kts), new WorldSpeed(20, WorldSpeed.Kts), new WorldSpeed(20, WorldSpeed.Kts), new WorldSpeed(20, WorldSpeed.Kts), new WorldDistance(3000, WorldDistance.YARDS), new WorldDistance(30, WorldDistance.YARDS), 3, new WorldSpeed(20, WorldSpeed.Kts), new WorldSpeed(60, WorldSpeed.Kts)); //////////////////////////////////////////////////////////// // CASE 1 //////////////////////////////////////////////////////////// CaseSolver firstCase = new CaseSolver() { public Point2D firstOrigin(Point2D point, double radius, double courseRads) { double xVal = point.getX() - radius * Math.cos(courseRads); double yVal = point.getY() + radius * Math.sin(courseRads); return new Point2D.Double(xVal, yVal); } public double alpha1(double hyp, double rad1, double hDelta, double kDelta) { return Math.asin(rad1 / hyp) + Math.atan2(hDelta, -kDelta); } public double zLength(double hDelta, double alpha1, double rad1) { return Math.abs((hDelta + rad1 * Math.cos(alpha1)) / Math.sin(alpha1)); } public double theta1(double alpha1, double p1) { return alpha1 - p1; } public OnTopSolution populateResults(double initialTurnDegs, double zLen, boolean isPossible, double totalTime) { return new OnTopSolution(-initialTurnDegs, zLen, isPossible, totalTime); } }; //////////////////////////////////////////////////////////// // CASE 2 //////////////////////////////////////////////////////////// CaseSolver secondCase = new CaseSolver() { public Point2D firstOrigin(Point2D point, double radius, double courseRads) { double xVal = point.getX() + radius * Math.cos(courseRads); double yVal = point.getY() - radius * Math.sin(courseRads); return new Point2D.Double(xVal, yVal); } // public Point2D secondOrigin(Point2D point, // double radius, // double courseRads) // { // double xVal = point.getX() - radius * Math.cos(courseRads); // double yVal = point.getY() + radius * Math.sin(courseRads); // return new Point2D.Double(xVal, yVal); // } public double alpha1(double hyp, double rad1, double hDelta, double kDelta) { return Math.asin(-rad1 / hyp) - Math.atan2(hDelta, kDelta); } public double zLength(double hDelta, double alpha1, double rad1) { return Math.abs((-hDelta - rad1 * Math.cos(alpha1)) / Math.sin(alpha1)); } public double theta1(double alpha1, double p1) { return p1 - alpha1; } public OnTopSolution populateResults(double initialTurnDegs, double zLen, boolean isPossible, double totalTime) { return new OnTopSolution(initialTurnDegs, zLen, isPossible, totalTime); } }; Point2D p1 = new Point2D.Double(-15, 5); Point2D p2 = new Point2D.Double(20, 5); double c1r = 0; double spd1 = Math.PI / 12; double spd2 = spd1; // double rt = 3; double r1 = 5; OnTopSolution testOne = OnTopWaypoint.calcCombination(p1, p2, firstCase, c1r, r1, spd1, spd2, moves); assertNotNull("found a solution", testOne); assertEquals("correct demanded turn", -277.1807, testOne.demandedCourseChange.doubleValue(), 0.01); assertEquals("correct distance", 39.686, testOne.distanceToRun.doubleValue(), 0.01); OnTopSolution testTwo = OnTopWaypoint.calcCombination(p1, p2, secondCase, c1r, r1, spd1, spd2, moves); assertNotNull("found a solution", testTwo); assertEquals("correct demanded turn", 99.59, testTwo.demandedCourseChange.doubleValue(), 0.01); assertEquals("correct distance", 29.58, testTwo.distanceToRun.doubleValue(), 0.01); } } // private static WorldLocation offset(WorldLocation origin, // double rng_m, // double brg_degs) // { // WorldLocation res = origin.add(new WorldVector(MWC.Algorithms.Conversions.Degs2Rads(brg_degs), // MWC.Algorithms.Conversions.m2Degs(rng_m), 0)); // return res; // } public static CoreParticipant createTestHelo() { CoreParticipant res = new Helo(122); res.setName("test_helo"); res.setCategory(new Category(Category.Force.BLUE, Category.Environment.AIRBORNE, Category.Type.HELO)); return res; } public static WorldLocation offsetLocation(WorldLocation host, double bearing_degs, double y_m) { WorldVector vector = new WorldVector(MWC.Algorithms.Conversions.Degs2Rads(bearing_degs), MWC.Algorithms.Conversions.m2Degs(y_m), 0); return host.add(vector); } }
false
true
public Status step(HighLevelDemandedStatus highLevelDemStatus, Status current, long newTime, MovementCharacteristics moves, TurnAlgorithm turner) { // ok, loop through the available time while (current.getTime() < newTime) { // do we know where we're going? if (_currentSolution == null) { WorldLocation nextW = null; // have we been interrupted? if (super._interruptedLocation != null) { // yes, head back to it before we resume route nextW = _interruptedLocation; } else { // no, just continue through the points nextW = highLevelDemStatus.getCurrentTarget(); } // ok. do calc. if (nextW != null) { // nope - we've no idea where we're going _currentSolution = getSolution(nextW, current, moves, newTime, highLevelDemStatus.getSpeed()); } // ok, we continue in steady state if we don't have a next waypoint, or if we can't calculate a solution // to the next waypoint if ((nextW == null) || (_currentSolution == null)) { // hey, we're done! // check if we're dead close and can't make it - in which case we mark it as reached if (_currentSolution == null && (nextW != null)) { double rangeError = current.getLocation().subtract(nextW).getRange(); rangeError = MWC.Algorithms.Conversions.Degs2m(rangeError); if (rangeError < 10) { // are we resuming after interruption? if (_interruptedLocation != null) { // yes we were. We're ok now, get back on proper route _interruptedLocation = null; } else { // and mark that this point is reached highLevelDemStatus.nextWaypointVisited(); } } } // Carry on in steady state to complete the time step SimpleDemandedStatus sds = new SimpleDemandedStatus(newTime, current); // carry on doing the speed update if we haven't already if (highLevelDemStatus.getSpeed() != null) sds.setSpeed(highLevelDemStatus.getSpeed()); // and do the turn current = turner.doTurn(current, sds, moves, newTime); } } else { // yup - keep heading towards the next waypoint if (_currentSolution.demandedCourseChange != null) { // get the turn required double demandedTurn = _currentSolution.demandedCourseChange.doubleValue(); // remember the old course - so we can update the change required double oldCourse = current.getCourse(); // no, get turning current = doThisPartOfTheTurn(demandedTurn, moves, current, newTime, turner, -current.getLocation().getDepth()); // are we now on the correct course // so, still got some way to go... double amountTurned = current.getCourse() - oldCourse; double amountRemaining = demandedTurn - amountTurned; // trim the amount remaining to a realistic figure, silly. if (amountRemaining < -360) amountRemaining += 360; if (amountRemaining > 360) amountRemaining -= 360; // ok, update the amount of course change remaining if (Math.abs(amountRemaining) < 0.4) { _currentSolution.demandedCourseChange = null; } else { _currentSolution.demandedCourseChange = new Double(amountRemaining); } } else { if (_currentSolution.distanceToRun != null) { // ok carry on travelling along the straight section Double distance = _currentSolution.distanceToRun; // remember where we are WorldLocation origin = new WorldLocation(current.getLocation()); // ok, move forward as far on the straight course as we can current = processStraightCourse(distance, current, newTime, highLevelDemStatus, turner, moves); // ok, see how far we have to go... WorldVector travelled = current.getLocation().subtract(origin); double rngDegs = travelled.getRange(); double rngM = MWC.Algorithms.Conversions.Degs2m(rngDegs); // hmm, how far is left? double remainingDistance = distance.doubleValue() - rngM; // ok - are we practically there? if (remainingDistance < 0.1) { // hey - we're done! _currentSolution.distanceToRun = null; _currentSolution = null; // and mark that this point is reached // are we returning after interruption? if (_interruptedLocation != null) { // yes. get back onto our proper course _interruptedLocation = null; } else { // no, just continue onto the next waypoint. highLevelDemStatus.nextWaypointVisited(); } } else { _currentSolution.distanceToRun = new Double(remainingDistance); } } else { // hey, all done! Clear the solution _currentSolution = null; } } } } return current; }
public Status step(HighLevelDemandedStatus highLevelDemStatus, Status current, long newTime, MovementCharacteristics moves, TurnAlgorithm turner) { // ok, loop through the available time while (current.getTime() < newTime) { // do we know where we're going? if (_currentSolution == null) { WorldLocation nextW = null; // have we been interrupted? if (super._interruptedLocation != null) { // yes, head back to it before we resume route nextW = _interruptedLocation; } else { // no, just continue through the points nextW = highLevelDemStatus.getCurrentTarget(); } // ok. do calc. if (nextW != null) { // nope - we've no idea where we're going _currentSolution = getSolution(nextW, current, moves, newTime, highLevelDemStatus.getSpeed()); } // ok, we continue in steady state if we don't have a next waypoint, or if we can't calculate a solution // to the next waypoint if ((nextW == null) || (_currentSolution == null)) { // hey, we're done! // check if we're dead close and can't make it - in which case we mark it as reached if (_currentSolution == null && (nextW != null)) { double rangeError = current.getLocation().subtract(nextW).getRange(); rangeError = MWC.Algorithms.Conversions.Degs2m(rangeError); if (rangeError < 10) { // are we resuming after interruption? if (_interruptedLocation != null) { // yes we were. We're ok now, get back on proper route _interruptedLocation = null; } else { // and mark that this point is reached highLevelDemStatus.nextWaypointVisited(); } } } // Carry on in steady state to complete the time step SimpleDemandedStatus sds = new SimpleDemandedStatus(newTime, current); // carry on doing the speed update if we haven't already if (highLevelDemStatus.getSpeed() != null) sds.setSpeed(highLevelDemStatus.getSpeed()); // and do the turn current = turner.doTurn(current, sds, moves, newTime); } } else { // yup - keep heading towards the next waypoint if (_currentSolution.demandedCourseChange != null) { // get the turn required double demandedTurn = _currentSolution.demandedCourseChange.doubleValue(); // remember the old course - so we can update the change required double oldCourse = current.getCourse(); // no, get turning current = doThisPartOfTheTurn(demandedTurn, moves, current, newTime, turner, -current.getLocation().getDepth()); // are we now on the correct course // so, still got some way to go... double amountTurned = current.getCourse() - oldCourse; double amountRemaining = demandedTurn - amountTurned; // trim the amount remaining to a realistic figure, silly. if (amountRemaining <= -360) amountRemaining += 360; if (amountRemaining >= 360) amountRemaining -= 360; // ok, update the amount of course change remaining if (Math.abs(amountRemaining) < 0.4) { _currentSolution.demandedCourseChange = null; } else { _currentSolution.demandedCourseChange = new Double(amountRemaining); } } else { if (_currentSolution.distanceToRun != null) { // ok carry on travelling along the straight section Double distance = _currentSolution.distanceToRun; // remember where we are WorldLocation origin = new WorldLocation(current.getLocation()); // ok, move forward as far on the straight course as we can current = processStraightCourse(distance, current, newTime, highLevelDemStatus, turner, moves); // ok, see how far we have to go... WorldVector travelled = current.getLocation().subtract(origin); double rngDegs = travelled.getRange(); double rngM = MWC.Algorithms.Conversions.Degs2m(rngDegs); // hmm, how far is left? double remainingDistance = distance.doubleValue() - rngM; // ok - are we practically there? if (remainingDistance < 0.1) { // hey - we're done! _currentSolution.distanceToRun = null; _currentSolution = null; // and mark that this point is reached // are we returning after interruption? if (_interruptedLocation != null) { // yes. get back onto our proper course _interruptedLocation = null; } else { // no, just continue onto the next waypoint. highLevelDemStatus.nextWaypointVisited(); } } else { _currentSolution.distanceToRun = new Double(remainingDistance); } } else { // hey, all done! Clear the solution _currentSolution = null; } } } } return current; }
diff --git a/src/test/org/apache/commons/codec/language/SoundexTest.java b/src/test/org/apache/commons/codec/language/SoundexTest.java index 33c8bb7d..426732d2 100755 --- a/src/test/org/apache/commons/codec/language/SoundexTest.java +++ b/src/test/org/apache/commons/codec/language/SoundexTest.java @@ -1,382 +1,390 @@ /* * Copyright 2001-2006 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // (FYI: Formatted and sorted with Eclipse) package org.apache.commons.codec.language; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder; import org.apache.commons.codec.StringEncoderAbstractTest; /** * Tests {@link Soundex} * * @author Apache Software Foundation * @version $Id$ */ public class SoundexTest extends StringEncoderAbstractTest { public static Test suite() { return new TestSuite(SoundexTest.class); } private Soundex encoder = null; public SoundexTest(String name) { super(name); } void encodeAll(String[] strings, String expectedEncoding) { for (int i = 0; i < strings.length; i++) { assertEquals(expectedEncoding, this.getEncoder().encode(strings[i])); } } /** * @return Returns the _encoder. */ public Soundex getEncoder() { return this.encoder; } protected StringEncoder makeEncoder() { return new Soundex(); } /** * @param encoder * The encoder to set. */ public void setEncoder(Soundex encoder) { this.encoder = encoder; } public void setUp() throws Exception { super.setUp(); this.setEncoder(new Soundex()); } public void tearDown() throws Exception { super.tearDown(); this.setEncoder(null); } public void testB650() { this.encodeAll( new String[] { "BARHAM", "BARONE", "BARRON", "BERNA", "BIRNEY", "BIRNIE", "BOOROM", "BOREN", "BORN", "BOURN", "BOURNE", "BOWRON", "BRAIN", "BRAME", "BRANN", "BRAUN", "BREEN", "BRIEN", "BRIM", "BRIMM", "BRINN", "BRION", "BROOM", "BROOME", "BROWN", "BROWNE", "BRUEN", "BRUHN", "BRUIN", "BRUMM", "BRUN", "BRUNO", "BRYAN", "BURIAN", "BURN", "BURNEY", "BYRAM", "BYRNE", "BYRON", "BYRUM" }, "B650"); } public void testDifference() throws EncoderException { // Edge cases assertEquals(0, this.getEncoder().difference(null, null)); assertEquals(0, this.getEncoder().difference("", "")); assertEquals(0, this.getEncoder().difference(" ", " ")); // Normal cases assertEquals(4, this.getEncoder().difference("Smith", "Smythe")); assertEquals(2, this.getEncoder().difference("Ann", "Andrew")); assertEquals(1, this.getEncoder().difference("Margaret", "Andrew")); assertEquals(0, this.getEncoder().difference("Janet", "Margaret")); // Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp assertEquals(4, this.getEncoder().difference("Green", "Greene")); assertEquals(0, this.getEncoder().difference("Blotchet-Halls", "Greene")); // Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp assertEquals(4, this.getEncoder().difference("Smith", "Smythe")); assertEquals(4, this.getEncoder().difference("Smithers", "Smythers")); assertEquals(2, this.getEncoder().difference("Anothers", "Brothers")); } public void testEncodeBasic() { assertEquals("T235", this.getEncoder().encode("testing")); assertEquals("T000", this.getEncoder().encode("The")); assertEquals("Q200", this.getEncoder().encode("quick")); assertEquals("B650", this.getEncoder().encode("brown")); assertEquals("F200", this.getEncoder().encode("fox")); assertEquals("J513", this.getEncoder().encode("jumped")); assertEquals("O160", this.getEncoder().encode("over")); assertEquals("T000", this.getEncoder().encode("the")); assertEquals("L200", this.getEncoder().encode("lazy")); assertEquals("D200", this.getEncoder().encode("dogs")); } /** * Examples from * http://www.bradandkathy.com/genealogy/overviewofsoundex.html */ public void testEncodeBatch2() { assertEquals("A462", this.getEncoder().encode("Allricht")); assertEquals("E166", this.getEncoder().encode("Eberhard")); assertEquals("E521", this.getEncoder().encode("Engebrethson")); assertEquals("H512", this.getEncoder().encode("Heimbach")); assertEquals("H524", this.getEncoder().encode("Hanselmann")); assertEquals("H431", this.getEncoder().encode("Hildebrand")); assertEquals("K152", this.getEncoder().encode("Kavanagh")); assertEquals("L530", this.getEncoder().encode("Lind")); assertEquals("L222", this.getEncoder().encode("Lukaschowsky")); assertEquals("M235", this.getEncoder().encode("McDonnell")); assertEquals("M200", this.getEncoder().encode("McGee")); assertEquals("O155", this.getEncoder().encode("Opnian")); assertEquals("O155", this.getEncoder().encode("Oppenheimer")); assertEquals("R355", this.getEncoder().encode("Riedemanas")); assertEquals("Z300", this.getEncoder().encode("Zita")); assertEquals("Z325", this.getEncoder().encode("Zitzmeinn")); } /** * Examples from * http://www.archives.gov/research_room/genealogy/census/soundex.html */ public void testEncodeBatch3() { assertEquals("W252", this.getEncoder().encode("Washington")); assertEquals("L000", this.getEncoder().encode("Lee")); assertEquals("G362", this.getEncoder().encode("Gutierrez")); assertEquals("P236", this.getEncoder().encode("Pfister")); assertEquals("J250", this.getEncoder().encode("Jackson")); assertEquals("T522", this.getEncoder().encode("Tymczak")); // For VanDeusen: D-250 (D, 2 for the S, 5 for the N, 0 added) is also // possible. assertEquals("V532", this.getEncoder().encode("VanDeusen")); } /** * Examples from: http://www.myatt.demon.co.uk/sxalg.htm */ public void testEncodeBatch4() { assertEquals("H452", this.getEncoder().encode("HOLMES")); assertEquals("A355", this.getEncoder().encode("ADOMOMI")); assertEquals("V536", this.getEncoder().encode("VONDERLEHR")); assertEquals("B400", this.getEncoder().encode("BALL")); assertEquals("S000", this.getEncoder().encode("SHAW")); assertEquals("J250", this.getEncoder().encode("JACKSON")); assertEquals("S545", this.getEncoder().encode("SCANLON")); assertEquals("S532", this.getEncoder().encode("SAINTJOHN")); } public void testBadCharacters() { assertEquals("H452", this.getEncoder().encode("HOL>MES")); } public void testEncodeIgnoreApostrophes() { this.encodeAll(new String[] { "OBrien", "'OBrien", "O'Brien", "OB'rien", "OBr'ien", "OBri'en", "OBrie'n", "OBrien'" }, "O165"); } /** * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ public void testEncodeIgnoreHyphens() { this.encodeAll( new String[] { "KINGSMITH", "-KINGSMITH", "K-INGSMITH", "KI-NGSMITH", "KIN-GSMITH", "KING-SMITH", "KINGS-MITH", "KINGSM-ITH", "KINGSMI-TH", "KINGSMIT-H", "KINGSMITH-" }, "K525"); } public void testEncodeIgnoreTrimmable() { assertEquals("W252", this.getEncoder().encode(" \t\n\r Washington \t\n\r ")); } /** * Consonants from the same code group separated by W or H are treated as * one. */ public void testHWRuleEx1() { // From // http://www.archives.gov/research_room/genealogy/census/soundex.html: // Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 // for the F). It is not coded A-226. assertEquals("A261", this.getEncoder().encode("Ashcraft")); } /** * Consonants from the same code group separated by W or H are treated as * one. * * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ public void testHWRuleEx2() { assertEquals("B312", this.getEncoder().encode("BOOTHDAVIS")); assertEquals("B312", this.getEncoder().encode("BOOTH-DAVIS")); } /** * Consonants from the same code group separated by W or H are treated as * one. */ public void testHWRuleEx3() { assertEquals("S460", this.getEncoder().encode("Sgler")); assertEquals("S460", this.getEncoder().encode("Swhgler")); // Also S460: this.encodeAll( new String[] { "SAILOR", "SALYER", "SAYLOR", "SCHALLER", "SCHELLER", "SCHILLER", "SCHOOLER", "SCHULER", "SCHUYLER", "SEILER", "SEYLER", "SHOLAR", "SHULER", "SILAR", "SILER", "SILLER" }, "S460"); } public void testMaxLength() throws Exception { Soundex soundex = new Soundex(); soundex.setMaxLength(soundex.getMaxLength()); assertEquals("S460", this.getEncoder().encode("Sgler")); } public void testMaxLengthLessThan3Fix() throws Exception { Soundex soundex = new Soundex(); soundex.setMaxLength(2); assertEquals("S460", soundex.encode("SCHELLER")); } /** * Examples for MS SQLServer from * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp */ public void testMsSqlServer1() { assertEquals("S530", this.getEncoder().encode("Smith")); assertEquals("S530", this.getEncoder().encode("Smythe")); } /** * Examples for MS SQLServer from * http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q100/3/65.asp&NoWebContent=1 */ public void testMsSqlServer2() { this.encodeAll(new String[]{"Erickson", "Erickson", "Erikson", "Ericson", "Ericksen", "Ericsen"}, "E625"); } /** * Examples for MS SQLServer from * http://databases.about.com/library/weekly/aa042901a.htm */ public void testMsSqlServer3() { assertEquals("A500", this.getEncoder().encode("Ann")); assertEquals("A536", this.getEncoder().encode("Andrew")); assertEquals("J530", this.getEncoder().encode("Janet")); assertEquals("M626", this.getEncoder().encode("Margaret")); assertEquals("S315", this.getEncoder().encode("Steven")); assertEquals("M240", this.getEncoder().encode("Michael")); assertEquals("R163", this.getEncoder().encode("Robert")); assertEquals("L600", this.getEncoder().encode("Laura")); assertEquals("A500", this.getEncoder().encode("Anne")); } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ public void testUsMappingOWithDiaeresis() { assertEquals("O000", this.getEncoder().encode("o")); - try { - assertEquals("�000", this.getEncoder().encode("�")); - fail("Expected IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - // expected + if ( Character.isLetter('�') ) { + try { + assertEquals("�000", this.getEncoder().encode("�")); + fail("Expected IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + // expected + } + } else { + assertEquals("", this.getEncoder().encode("�")); } } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ public void testUsMappingEWithAcute() { assertEquals("E000", this.getEncoder().encode("e")); - try { - assertEquals("�000", this.getEncoder().encode("�")); - fail("Expected IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - // expected + if ( Character.isLetter('�') ) { + try { + assertEquals("�000", this.getEncoder().encode("�")); + fail("Expected IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + // expected + } + } else { + assertEquals("", this.getEncoder().encode("�")); } } // This test fails. public void testUsEnglishStatic() { assertEquals( Soundex.US_ENGLISH.soundex( "Williams" ), "W452" ); } // This test succeeds. public void testNewInstance() { assertEquals( new Soundex().soundex( "Williams" ), "W452" ); } }
false
true
public void testEncodeIgnoreApostrophes() { this.encodeAll(new String[] { "OBrien", "'OBrien", "O'Brien", "OB'rien", "OBr'ien", "OBri'en", "OBrie'n", "OBrien'" }, "O165"); } /** * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ public void testEncodeIgnoreHyphens() { this.encodeAll( new String[] { "KINGSMITH", "-KINGSMITH", "K-INGSMITH", "KI-NGSMITH", "KIN-GSMITH", "KING-SMITH", "KINGS-MITH", "KINGSM-ITH", "KINGSMI-TH", "KINGSMIT-H", "KINGSMITH-" }, "K525"); } public void testEncodeIgnoreTrimmable() { assertEquals("W252", this.getEncoder().encode(" \t\n\r Washington \t\n\r ")); } /** * Consonants from the same code group separated by W or H are treated as * one. */ public void testHWRuleEx1() { // From // http://www.archives.gov/research_room/genealogy/census/soundex.html: // Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 // for the F). It is not coded A-226. assertEquals("A261", this.getEncoder().encode("Ashcraft")); } /** * Consonants from the same code group separated by W or H are treated as * one. * * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ public void testHWRuleEx2() { assertEquals("B312", this.getEncoder().encode("BOOTHDAVIS")); assertEquals("B312", this.getEncoder().encode("BOOTH-DAVIS")); } /** * Consonants from the same code group separated by W or H are treated as * one. */ public void testHWRuleEx3() { assertEquals("S460", this.getEncoder().encode("Sgler")); assertEquals("S460", this.getEncoder().encode("Swhgler")); // Also S460: this.encodeAll( new String[] { "SAILOR", "SALYER", "SAYLOR", "SCHALLER", "SCHELLER", "SCHILLER", "SCHOOLER", "SCHULER", "SCHUYLER", "SEILER", "SEYLER", "SHOLAR", "SHULER", "SILAR", "SILER", "SILLER" }, "S460"); } public void testMaxLength() throws Exception { Soundex soundex = new Soundex(); soundex.setMaxLength(soundex.getMaxLength()); assertEquals("S460", this.getEncoder().encode("Sgler")); } public void testMaxLengthLessThan3Fix() throws Exception { Soundex soundex = new Soundex(); soundex.setMaxLength(2); assertEquals("S460", soundex.encode("SCHELLER")); } /** * Examples for MS SQLServer from * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp */ public void testMsSqlServer1() { assertEquals("S530", this.getEncoder().encode("Smith")); assertEquals("S530", this.getEncoder().encode("Smythe")); } /** * Examples for MS SQLServer from * http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q100/3/65.asp&NoWebContent=1 */ public void testMsSqlServer2() { this.encodeAll(new String[]{"Erickson", "Erickson", "Erikson", "Ericson", "Ericksen", "Ericsen"}, "E625"); } /** * Examples for MS SQLServer from * http://databases.about.com/library/weekly/aa042901a.htm */ public void testMsSqlServer3() { assertEquals("A500", this.getEncoder().encode("Ann")); assertEquals("A536", this.getEncoder().encode("Andrew")); assertEquals("J530", this.getEncoder().encode("Janet")); assertEquals("M626", this.getEncoder().encode("Margaret")); assertEquals("S315", this.getEncoder().encode("Steven")); assertEquals("M240", this.getEncoder().encode("Michael")); assertEquals("R163", this.getEncoder().encode("Robert")); assertEquals("L600", this.getEncoder().encode("Laura")); assertEquals("A500", this.getEncoder().encode("Anne")); } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ public void testUsMappingOWithDiaeresis() { assertEquals("O000", this.getEncoder().encode("o")); try { assertEquals("�000", this.getEncoder().encode("�")); fail("Expected IllegalArgumentException not thrown"); } catch (IllegalArgumentException e) { // expected } } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ public void testUsMappingEWithAcute() { assertEquals("E000", this.getEncoder().encode("e")); try { assertEquals("�000", this.getEncoder().encode("�")); fail("Expected IllegalArgumentException not thrown"); } catch (IllegalArgumentException e) { // expected } } // This test fails. public void testUsEnglishStatic() { assertEquals( Soundex.US_ENGLISH.soundex( "Williams" ), "W452" ); } // This test succeeds. public void testNewInstance() { assertEquals( new Soundex().soundex( "Williams" ), "W452" ); } }
public void testEncodeIgnoreApostrophes() { this.encodeAll(new String[] { "OBrien", "'OBrien", "O'Brien", "OB'rien", "OBr'ien", "OBri'en", "OBrie'n", "OBrien'" }, "O165"); } /** * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ public void testEncodeIgnoreHyphens() { this.encodeAll( new String[] { "KINGSMITH", "-KINGSMITH", "K-INGSMITH", "KI-NGSMITH", "KIN-GSMITH", "KING-SMITH", "KINGS-MITH", "KINGSM-ITH", "KINGSMI-TH", "KINGSMIT-H", "KINGSMITH-" }, "K525"); } public void testEncodeIgnoreTrimmable() { assertEquals("W252", this.getEncoder().encode(" \t\n\r Washington \t\n\r ")); } /** * Consonants from the same code group separated by W or H are treated as * one. */ public void testHWRuleEx1() { // From // http://www.archives.gov/research_room/genealogy/census/soundex.html: // Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 // for the F). It is not coded A-226. assertEquals("A261", this.getEncoder().encode("Ashcraft")); } /** * Consonants from the same code group separated by W or H are treated as * one. * * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ public void testHWRuleEx2() { assertEquals("B312", this.getEncoder().encode("BOOTHDAVIS")); assertEquals("B312", this.getEncoder().encode("BOOTH-DAVIS")); } /** * Consonants from the same code group separated by W or H are treated as * one. */ public void testHWRuleEx3() { assertEquals("S460", this.getEncoder().encode("Sgler")); assertEquals("S460", this.getEncoder().encode("Swhgler")); // Also S460: this.encodeAll( new String[] { "SAILOR", "SALYER", "SAYLOR", "SCHALLER", "SCHELLER", "SCHILLER", "SCHOOLER", "SCHULER", "SCHUYLER", "SEILER", "SEYLER", "SHOLAR", "SHULER", "SILAR", "SILER", "SILLER" }, "S460"); } public void testMaxLength() throws Exception { Soundex soundex = new Soundex(); soundex.setMaxLength(soundex.getMaxLength()); assertEquals("S460", this.getEncoder().encode("Sgler")); } public void testMaxLengthLessThan3Fix() throws Exception { Soundex soundex = new Soundex(); soundex.setMaxLength(2); assertEquals("S460", soundex.encode("SCHELLER")); } /** * Examples for MS SQLServer from * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp */ public void testMsSqlServer1() { assertEquals("S530", this.getEncoder().encode("Smith")); assertEquals("S530", this.getEncoder().encode("Smythe")); } /** * Examples for MS SQLServer from * http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q100/3/65.asp&NoWebContent=1 */ public void testMsSqlServer2() { this.encodeAll(new String[]{"Erickson", "Erickson", "Erikson", "Ericson", "Ericksen", "Ericsen"}, "E625"); } /** * Examples for MS SQLServer from * http://databases.about.com/library/weekly/aa042901a.htm */ public void testMsSqlServer3() { assertEquals("A500", this.getEncoder().encode("Ann")); assertEquals("A536", this.getEncoder().encode("Andrew")); assertEquals("J530", this.getEncoder().encode("Janet")); assertEquals("M626", this.getEncoder().encode("Margaret")); assertEquals("S315", this.getEncoder().encode("Steven")); assertEquals("M240", this.getEncoder().encode("Michael")); assertEquals("R163", this.getEncoder().encode("Robert")); assertEquals("L600", this.getEncoder().encode("Laura")); assertEquals("A500", this.getEncoder().encode("Anne")); } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ public void testUsMappingOWithDiaeresis() { assertEquals("O000", this.getEncoder().encode("o")); if ( Character.isLetter('�') ) { try { assertEquals("�000", this.getEncoder().encode("�")); fail("Expected IllegalArgumentException not thrown"); } catch (IllegalArgumentException e) { // expected } } else { assertEquals("", this.getEncoder().encode("�")); } } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ public void testUsMappingEWithAcute() { assertEquals("E000", this.getEncoder().encode("e")); if ( Character.isLetter('�') ) { try { assertEquals("�000", this.getEncoder().encode("�")); fail("Expected IllegalArgumentException not thrown"); } catch (IllegalArgumentException e) { // expected } } else { assertEquals("", this.getEncoder().encode("�")); } } // This test fails. public void testUsEnglishStatic() { assertEquals( Soundex.US_ENGLISH.soundex( "Williams" ), "W452" ); } // This test succeeds. public void testNewInstance() { assertEquals( new Soundex().soundex( "Williams" ), "W452" ); } }
diff --git a/src/main/java/com/github/ucchyocean/et/ExpTimer.java b/src/main/java/com/github/ucchyocean/et/ExpTimer.java index 4d6f643..a7dd0ed 100644 --- a/src/main/java/com/github/ucchyocean/et/ExpTimer.java +++ b/src/main/java/com/github/ucchyocean/et/ExpTimer.java @@ -1,437 +1,446 @@ /* * @author ucchy * @license LGPLv3 * @copyright Copyright ucchy 2013 */ package com.github.ucchyocean.et; import java.io.File; import java.util.HashMap; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; /** * 経験値タイマー * @author ucchy */ public class ExpTimer extends JavaPlugin implements Listener { private static ExpTimer instance; private TimerTask runnable; private BukkitTask task; protected static ETConfigData config; protected static HashMap<String, ETConfigData> configs; private String currentConfigName; private CommandSender currentCommandSender; /** * @see org.bukkit.plugin.java.JavaPlugin#onEnable() */ @Override public void onEnable() { instance = this; // コンフィグのロード reloadConfigData(); // メッセージの初期化 Messages.initialize(null); // イベントの登録 getServer().getPluginManager().registerEvents(this, this); // ColorTeaming のロード if ( getServer().getPluginManager().isPluginEnabled("ColorTeaming") ) { Plugin temp = getServer().getPluginManager().getPlugin("ColorTeaming"); String ctversion = temp.getDescription().getVersion(); if ( Utility.isUpperVersion(ctversion, "2.2.0") ) { getLogger().info("ColorTeaming がロードされました。連携機能を有効にします。"); getServer().getPluginManager().registerEvents( new ColorTeamingListener(this), this); } else { getLogger().warning("ColorTeaming のバージョンが古いため、連携機能は無効になりました。"); getLogger().warning("連携機能を使用するには、ColorTeaming v2.2.0 以上が必要です。"); } } } /** * @see org.bukkit.plugin.java.JavaPlugin#onDisable() */ @Override public void onDisable() { // タスクが残ったままなら、強制終了しておく。 if ( runnable != null ) { getLogger().warning("タイマーが残ったままです。強制終了します。"); cancelTask(); } } /** * @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) */ @Override public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { // 引数がない場合は実行しない if ( args.length <= 0 ) { return false; } if ( args[0].equalsIgnoreCase("start") ) { // タイマーをスタートする if ( runnable == null ) { if ( args.length == 1 ) { + currentConfigName = "default"; config = configs.get("default").clone(); } else if ( args.length >= 2 ) { if ( args[1].matches("^[0-9]+$") ) { + currentConfigName = "default"; config = configs.get("default").clone(); config.seconds = Integer.parseInt(args[1]); if ( args.length >= 3 && args[2].matches("^[0-9]+$")) { config.readySeconds = Integer.parseInt(args[2]); } } else { if ( !configs.containsKey(args[1]) ) { sender.sendMessage(ChatColor.RED + String.format("設定 %s が見つかりません!", args[1])); return true; } + currentConfigName = args[1]; config = configs.get(args[1]).clone(); } } // configからメッセージのリロード Messages.initialize(config.messageFileName); startNewTask(null, sender); sender.sendMessage(ChatColor.GRAY + "タイマーを新規に開始しました。"); return true; } else { if ( runnable.isPaused() ) { runnable.startFromPause(); sender.sendMessage(ChatColor.GRAY + "タイマーを再開しました。"); return true; } else { sender.sendMessage(ChatColor.RED + "タイマーが既に開始されています!"); return true; } } } else if ( args[0].equalsIgnoreCase("pause") ) { // タイマーを一時停止する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } if ( !runnable.isPaused() ) { runnable.pause(); sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。"); return true; } else { sender.sendMessage(ChatColor.RED + "タイマーは既に一時停止状態です!"); return true; } } else if ( args[0].equalsIgnoreCase("end") ) { // タイマーを強制終了する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } endTask(); if ( config.useExpBar ) setExpLevel(0, 1); sender.sendMessage(ChatColor.GRAY + "タイマーを停止しました。"); return true; } else if ( args[0].equalsIgnoreCase("cancel") ) { // タイマーを強制終了する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } cancelTask(); if ( config.useExpBar ) setExpLevel(0, 1); sender.sendMessage(ChatColor.GRAY + "タイマーを強制停止しました。"); return true; } else if ( args[0].equalsIgnoreCase("status") ) { // ステータスを参照する String stat; if ( runnable == null ) { stat = "タイマー停止中"; } else { stat = runnable.getStatusDescription(); } sender.sendMessage(ChatColor.GRAY + "----- ExpTimer information -----"); sender.sendMessage(ChatColor.GRAY + "現在の状況:" + ChatColor.WHITE + stat); sender.sendMessage(ChatColor.GRAY + "現在の設定名:" + currentConfigName); sender.sendMessage(ChatColor.GRAY + "開始時に実行するコマンド:"); for ( String com : config.commandsOnStart ) { sender.sendMessage(ChatColor.WHITE + " " + com); } + for ( String com : config.consoleCommandsOnStart ) { + sender.sendMessage(ChatColor.AQUA + " " + com); + } sender.sendMessage(ChatColor.GRAY + "終了時に実行するコマンド:"); for ( String com : config.commandsOnEnd ) { sender.sendMessage(ChatColor.WHITE + " " + com); } + for ( String com : config.consoleCommandsOnEnd ) { + sender.sendMessage(ChatColor.AQUA + " " + com); + } sender.sendMessage(ChatColor.GRAY + "--------------------------------"); return true; } else if ( args[0].equalsIgnoreCase("list") ) { // コンフィグ一覧を表示する String format = ChatColor.GOLD + "%s " + ChatColor.GRAY + ": " + ChatColor.WHITE + "%d " + ChatColor.GRAY + "+ %d seconds"; sender.sendMessage(ChatColor.GRAY + "----- ExpTimer config list -----"); for ( String key : configs.keySet() ) { int sec = configs.get(key).seconds; int ready = configs.get(key).readySeconds; String message = String.format(format, key, sec, ready); sender.sendMessage(message); } sender.sendMessage(ChatColor.GRAY + "--------------------------------"); return true; } else if ( args[0].equalsIgnoreCase("reload") ) { // config.yml をリロードする if ( runnable != null ) { sender.sendMessage(ChatColor.RED + "実行中のタイマーがあるため、リロードできません!"); sender.sendMessage(ChatColor.RED + "先に /" + label + " cancel を実行して、タイマーを終了してください。"); return true; } reloadConfigData(); sender.sendMessage(ChatColor.GRAY + "config.yml をリロードしました。"); return true; } return false; } /** * config.yml を再読み込みする */ protected void reloadConfigData() { saveDefaultConfig(); reloadConfig(); FileConfiguration config = getConfig(); ExpTimer.configs = new HashMap<String, ETConfigData>(); // デフォルトのデータ読み込み ConfigurationSection section = config.getConfigurationSection("default"); ETConfigData defaultData = ETConfigData.loadFromSection(section, null); ExpTimer.config = defaultData; ExpTimer.configs.put("default", defaultData); currentConfigName = "default"; // デフォルト以外のデータ読み込み for ( String key : config.getKeys(false) ) { if ( key.equals("default") ) { continue; } section = config.getConfigurationSection(key); ETConfigData data = ETConfigData.loadFromSection(section, defaultData); ExpTimer.configs.put(key, data); } } /** * 全プレイヤーの経験値レベルを設定する * @param level 設定するレベル */ protected static void setExpLevel(int level, int max) { float progress = (float)level / (float)max; if ( progress > 1.0f ) { progress = 1.0f; } else if ( progress < 0.0f ) { progress = 0.0f; } if ( level > 24000 ) { level = 24000; } else if ( level < 0 ) { level = 0; } Player[] players = instance.getServer().getOnlinePlayers(); for ( Player player : players ) { player.setLevel(level); player.setExp(progress); } } /** * 新しいタスクを開始する * @param configName コンフィグ名。nullならそのままconfigを変更せずにタスクを開始する * @param sender コマンド実行者。nullならcurrentCommandSenderがそのまま引き継がれる */ public void startNewTask(String configName, CommandSender sender) { if ( configName != null && configs.containsKey(configName) ) { config = configs.get(configName).clone(); Messages.initialize(config.messageFileName); currentConfigName = configName; } if ( sender != null ) { currentCommandSender = sender; } runnable = new TimerTask(this); task = getServer().getScheduler().runTaskTimer(this, runnable, 20, 20); } /** * 現在実行中のタスクを中断する。終了時のコマンドは実行されない。 */ public void cancelTask() { if ( runnable != null ) { // タスクを終了する getServer().getScheduler().cancelTask(task.getTaskId()); runnable = null; task = null; if ( ExpTimer.config.useExpBar ) { ExpTimer.setExpLevel(0, 1); } } } /** * 現在実行中のタスクを終了コマンドを実行してから終了する */ public void endTask() { if ( runnable != null ) { // 終了コマンドを実行してタスクを終了する dispatchCommandsBySender(config.commandsOnEnd); dispatchCommandsByConsole(config.consoleCommandsOnEnd); cancelTask(); } } /** * 現在のタイマータスクを取得する * @return タスク */ public TimerTask getTask() { return runnable; } /** * プラグインのデータフォルダを返す * @return プラグインのデータフォルダ */ protected static File getConfigFolder() { return instance.getDataFolder(); } /** * プラグインのJarファイル自体を示すFileオブジェクトを返す * @return プラグインのJarファイル */ protected static File getPluginJarFile() { return instance.getFile(); } /** * キャッシュされているCommandSenderで、指定されたコマンドをまとめて実行する。 * @param commands コマンド */ protected void dispatchCommandsBySender(List<String> commands) { // CommandSender を取得する CommandSender sender = Bukkit.getConsoleSender(); if ( ExpTimer.config != null && currentCommandSender != null ) { sender = currentCommandSender; } // コマンド実行 dispatchCommands(sender, commands); } /** * コンソールで、指定されたコマンドをまとめて実行する。 * @param commands コマンド */ protected void dispatchCommandsByConsole(List<String> commands) { dispatchCommands(Bukkit.getConsoleSender(), commands); } /** * 指定されたコマンドをまとめて実行する。 * @param sender コマンドを実行する人 * @param commands コマンド */ private void dispatchCommands(CommandSender sender, List<String> commands) { for ( String command : commands ) { if ( command.startsWith("/") ) { command = command.substring(1); // スラッシュ削除 } // @aがコマンドに含まれている場合は、展開して実行する。 // 含まれていないならそのまま実行する。 if ( command.contains("@a") ) { Player[] players = Bukkit.getOnlinePlayers(); for ( Player p : players ) { Bukkit.dispatchCommand(sender, command.replaceAll("@a", p.getName())); } } else { Bukkit.dispatchCommand(sender, command); } } } /** * プレイヤー死亡時に呼び出されるメソッド * @param event */ @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { // タイマー起動中の死亡は、経験値を落とさない if ( runnable != null ) event.setDroppedExp(0); } }
false
true
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { // 引数がない場合は実行しない if ( args.length <= 0 ) { return false; } if ( args[0].equalsIgnoreCase("start") ) { // タイマーをスタートする if ( runnable == null ) { if ( args.length == 1 ) { config = configs.get("default").clone(); } else if ( args.length >= 2 ) { if ( args[1].matches("^[0-9]+$") ) { config = configs.get("default").clone(); config.seconds = Integer.parseInt(args[1]); if ( args.length >= 3 && args[2].matches("^[0-9]+$")) { config.readySeconds = Integer.parseInt(args[2]); } } else { if ( !configs.containsKey(args[1]) ) { sender.sendMessage(ChatColor.RED + String.format("設定 %s が見つかりません!", args[1])); return true; } config = configs.get(args[1]).clone(); } } // configからメッセージのリロード Messages.initialize(config.messageFileName); startNewTask(null, sender); sender.sendMessage(ChatColor.GRAY + "タイマーを新規に開始しました。"); return true; } else { if ( runnable.isPaused() ) { runnable.startFromPause(); sender.sendMessage(ChatColor.GRAY + "タイマーを再開しました。"); return true; } else { sender.sendMessage(ChatColor.RED + "タイマーが既に開始されています!"); return true; } } } else if ( args[0].equalsIgnoreCase("pause") ) { // タイマーを一時停止する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } if ( !runnable.isPaused() ) { runnable.pause(); sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。"); return true; } else { sender.sendMessage(ChatColor.RED + "タイマーは既に一時停止状態です!"); return true; } } else if ( args[0].equalsIgnoreCase("end") ) { // タイマーを強制終了する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } endTask(); if ( config.useExpBar ) setExpLevel(0, 1); sender.sendMessage(ChatColor.GRAY + "タイマーを停止しました。"); return true; } else if ( args[0].equalsIgnoreCase("cancel") ) { // タイマーを強制終了する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } cancelTask(); if ( config.useExpBar ) setExpLevel(0, 1); sender.sendMessage(ChatColor.GRAY + "タイマーを強制停止しました。"); return true; } else if ( args[0].equalsIgnoreCase("status") ) { // ステータスを参照する String stat; if ( runnable == null ) { stat = "タイマー停止中"; } else { stat = runnable.getStatusDescription(); } sender.sendMessage(ChatColor.GRAY + "----- ExpTimer information -----"); sender.sendMessage(ChatColor.GRAY + "現在の状況:" + ChatColor.WHITE + stat); sender.sendMessage(ChatColor.GRAY + "現在の設定名:" + currentConfigName); sender.sendMessage(ChatColor.GRAY + "開始時に実行するコマンド:"); for ( String com : config.commandsOnStart ) { sender.sendMessage(ChatColor.WHITE + " " + com); } sender.sendMessage(ChatColor.GRAY + "終了時に実行するコマンド:"); for ( String com : config.commandsOnEnd ) { sender.sendMessage(ChatColor.WHITE + " " + com); } sender.sendMessage(ChatColor.GRAY + "--------------------------------"); return true; } else if ( args[0].equalsIgnoreCase("list") ) { // コンフィグ一覧を表示する String format = ChatColor.GOLD + "%s " + ChatColor.GRAY + ": " + ChatColor.WHITE + "%d " + ChatColor.GRAY + "+ %d seconds"; sender.sendMessage(ChatColor.GRAY + "----- ExpTimer config list -----"); for ( String key : configs.keySet() ) { int sec = configs.get(key).seconds; int ready = configs.get(key).readySeconds; String message = String.format(format, key, sec, ready); sender.sendMessage(message); } sender.sendMessage(ChatColor.GRAY + "--------------------------------"); return true; } else if ( args[0].equalsIgnoreCase("reload") ) { // config.yml をリロードする if ( runnable != null ) { sender.sendMessage(ChatColor.RED + "実行中のタイマーがあるため、リロードできません!"); sender.sendMessage(ChatColor.RED + "先に /" + label + " cancel を実行して、タイマーを終了してください。"); return true; } reloadConfigData(); sender.sendMessage(ChatColor.GRAY + "config.yml をリロードしました。"); return true; } return false; }
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { // 引数がない場合は実行しない if ( args.length <= 0 ) { return false; } if ( args[0].equalsIgnoreCase("start") ) { // タイマーをスタートする if ( runnable == null ) { if ( args.length == 1 ) { currentConfigName = "default"; config = configs.get("default").clone(); } else if ( args.length >= 2 ) { if ( args[1].matches("^[0-9]+$") ) { currentConfigName = "default"; config = configs.get("default").clone(); config.seconds = Integer.parseInt(args[1]); if ( args.length >= 3 && args[2].matches("^[0-9]+$")) { config.readySeconds = Integer.parseInt(args[2]); } } else { if ( !configs.containsKey(args[1]) ) { sender.sendMessage(ChatColor.RED + String.format("設定 %s が見つかりません!", args[1])); return true; } currentConfigName = args[1]; config = configs.get(args[1]).clone(); } } // configからメッセージのリロード Messages.initialize(config.messageFileName); startNewTask(null, sender); sender.sendMessage(ChatColor.GRAY + "タイマーを新規に開始しました。"); return true; } else { if ( runnable.isPaused() ) { runnable.startFromPause(); sender.sendMessage(ChatColor.GRAY + "タイマーを再開しました。"); return true; } else { sender.sendMessage(ChatColor.RED + "タイマーが既に開始されています!"); return true; } } } else if ( args[0].equalsIgnoreCase("pause") ) { // タイマーを一時停止する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } if ( !runnable.isPaused() ) { runnable.pause(); sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。"); return true; } else { sender.sendMessage(ChatColor.RED + "タイマーは既に一時停止状態です!"); return true; } } else if ( args[0].equalsIgnoreCase("end") ) { // タイマーを強制終了する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } endTask(); if ( config.useExpBar ) setExpLevel(0, 1); sender.sendMessage(ChatColor.GRAY + "タイマーを停止しました。"); return true; } else if ( args[0].equalsIgnoreCase("cancel") ) { // タイマーを強制終了する if ( runnable == null ) { sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!"); return true; } cancelTask(); if ( config.useExpBar ) setExpLevel(0, 1); sender.sendMessage(ChatColor.GRAY + "タイマーを強制停止しました。"); return true; } else if ( args[0].equalsIgnoreCase("status") ) { // ステータスを参照する String stat; if ( runnable == null ) { stat = "タイマー停止中"; } else { stat = runnable.getStatusDescription(); } sender.sendMessage(ChatColor.GRAY + "----- ExpTimer information -----"); sender.sendMessage(ChatColor.GRAY + "現在の状況:" + ChatColor.WHITE + stat); sender.sendMessage(ChatColor.GRAY + "現在の設定名:" + currentConfigName); sender.sendMessage(ChatColor.GRAY + "開始時に実行するコマンド:"); for ( String com : config.commandsOnStart ) { sender.sendMessage(ChatColor.WHITE + " " + com); } for ( String com : config.consoleCommandsOnStart ) { sender.sendMessage(ChatColor.AQUA + " " + com); } sender.sendMessage(ChatColor.GRAY + "終了時に実行するコマンド:"); for ( String com : config.commandsOnEnd ) { sender.sendMessage(ChatColor.WHITE + " " + com); } for ( String com : config.consoleCommandsOnEnd ) { sender.sendMessage(ChatColor.AQUA + " " + com); } sender.sendMessage(ChatColor.GRAY + "--------------------------------"); return true; } else if ( args[0].equalsIgnoreCase("list") ) { // コンフィグ一覧を表示する String format = ChatColor.GOLD + "%s " + ChatColor.GRAY + ": " + ChatColor.WHITE + "%d " + ChatColor.GRAY + "+ %d seconds"; sender.sendMessage(ChatColor.GRAY + "----- ExpTimer config list -----"); for ( String key : configs.keySet() ) { int sec = configs.get(key).seconds; int ready = configs.get(key).readySeconds; String message = String.format(format, key, sec, ready); sender.sendMessage(message); } sender.sendMessage(ChatColor.GRAY + "--------------------------------"); return true; } else if ( args[0].equalsIgnoreCase("reload") ) { // config.yml をリロードする if ( runnable != null ) { sender.sendMessage(ChatColor.RED + "実行中のタイマーがあるため、リロードできません!"); sender.sendMessage(ChatColor.RED + "先に /" + label + " cancel を実行して、タイマーを終了してください。"); return true; } reloadConfigData(); sender.sendMessage(ChatColor.GRAY + "config.yml をリロードしました。"); return true; } return false; }
diff --git a/src/main/java/com/github/signed/mp3/Mp3Album.java b/src/main/java/com/github/signed/mp3/Mp3Album.java index d0511dc..d1eb7f7 100644 --- a/src/main/java/com/github/signed/mp3/Mp3Album.java +++ b/src/main/java/com/github/signed/mp3/Mp3Album.java @@ -1,62 +1,63 @@ package com.github.signed.mp3; import com.google.common.collect.Lists; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Mp3Album { public static Mp3Album For(Path path){ return new Mp3Album(path); } private Path path; public Mp3Album(Path path) { this.path = path; } public void forEachMp3File(Callback<Context> callback){ - try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, "*.samples")) { - List<Path> allPath = Lists.newArrayList(ds); + System.out.println("process album at '"+path+"'"); + try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path, "*.mp3")) { + List<Path> allPath = Lists.newArrayList(directoryStream); Collections.sort(allPath, new Comparator<Path>() { @Override public int compare(Path o1, Path o2) { return o1.getFileName().compareTo(o2.getFileName()); } }); final int totalNumberOfTracks = allPath.size(); int currentTrackNumber = 1; for (Path path : allPath) { - //System.out.println(p); + System.out.println(path); Mp3 currentMp3 = Mp3.From(path); Context context = new Context(totalNumberOfTracks, currentTrackNumber, path, currentMp3); callback.call(context); ++currentTrackNumber; } } catch (IOException e) { throw new RuntimeException(e); } } public static class Context{ public final int totalNumberOfTracks; public final int trackNumber; public final Path currentTracksPath; public final Mp3 currentTrack; public Context(int totalNumberOfTracks, int trackNumber, Path currentTracksPath, Mp3 currentTrack) { this.totalNumberOfTracks = totalNumberOfTracks; this.trackNumber = trackNumber; this.currentTracksPath = currentTracksPath; this.currentTrack = currentTrack; } } }
false
true
public void forEachMp3File(Callback<Context> callback){ try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, "*.samples")) { List<Path> allPath = Lists.newArrayList(ds); Collections.sort(allPath, new Comparator<Path>() { @Override public int compare(Path o1, Path o2) { return o1.getFileName().compareTo(o2.getFileName()); } }); final int totalNumberOfTracks = allPath.size(); int currentTrackNumber = 1; for (Path path : allPath) { //System.out.println(p); Mp3 currentMp3 = Mp3.From(path); Context context = new Context(totalNumberOfTracks, currentTrackNumber, path, currentMp3); callback.call(context); ++currentTrackNumber; } } catch (IOException e) { throw new RuntimeException(e); } }
public void forEachMp3File(Callback<Context> callback){ System.out.println("process album at '"+path+"'"); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path, "*.mp3")) { List<Path> allPath = Lists.newArrayList(directoryStream); Collections.sort(allPath, new Comparator<Path>() { @Override public int compare(Path o1, Path o2) { return o1.getFileName().compareTo(o2.getFileName()); } }); final int totalNumberOfTracks = allPath.size(); int currentTrackNumber = 1; for (Path path : allPath) { System.out.println(path); Mp3 currentMp3 = Mp3.From(path); Context context = new Context(totalNumberOfTracks, currentTrackNumber, path, currentMp3); callback.call(context); ++currentTrackNumber; } } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/Datamining/src/datamining/Utils.java b/Datamining/src/datamining/Utils.java index 47a636b..7c03104 100644 --- a/Datamining/src/datamining/Utils.java +++ b/Datamining/src/datamining/Utils.java @@ -1,56 +1,59 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package datamining; import java.util.LinkedList; import static java.lang.Math.*; /** * * @author igor */ public class Utils { /** * Retorna uma opcao sinalizada por uma flag no array de opcoes. * * @param flag sinalizador da opcao desejada * @param options array com sinalizadores e opcoes * * @return o valor da opcao desejada */ public static String getOption(String flag, String[] options) throws Exception { + if (options.length == 0) { + throw new Exception("Nenhuma opcao foi definida!"); + } int i = 0; String readFlag = options[i]; while ((i < options.length) && !readFlag.equals("-" + flag)) { readFlag = options[i]; i = i + 2; } if (!readFlag.equals("-" + flag)) { throw new Exception("A opcao " + flag + " nao pode ser encontrada!"); } return options[i + 1]; } /** * Efetua o calculo da entropia de Shannon para uma colecao de * probabilidades * * @param probs colecao de probabilidades * * @return o valor da entropia para as probabilidades passadas */ public static Double entropy(LinkedList<Double> probs) { double entropyValue = 0; while (!probs.isEmpty()) { double px = probs.poll().doubleValue(); entropyValue += (log(px)/log(2)); } return Double.valueOf(entropyValue); } }
true
true
public static String getOption(String flag, String[] options) throws Exception { int i = 0; String readFlag = options[i]; while ((i < options.length) && !readFlag.equals("-" + flag)) { readFlag = options[i]; i = i + 2; } if (!readFlag.equals("-" + flag)) { throw new Exception("A opcao " + flag + " nao pode ser encontrada!"); } return options[i + 1]; }
public static String getOption(String flag, String[] options) throws Exception { if (options.length == 0) { throw new Exception("Nenhuma opcao foi definida!"); } int i = 0; String readFlag = options[i]; while ((i < options.length) && !readFlag.equals("-" + flag)) { readFlag = options[i]; i = i + 2; } if (!readFlag.equals("-" + flag)) { throw new Exception("A opcao " + flag + " nao pode ser encontrada!"); } return options[i + 1]; }
diff --git a/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java b/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java index 8a6fe2935..a519f90c3 100644 --- a/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java +++ b/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java @@ -1,189 +1,195 @@ package com.googlecode.jmxtrans.model.output; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Result; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.model.ValidationException; import com.googlecode.jmxtrans.model.naming.KeyUtils; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.concurrent.NotThreadSafe; import javax.inject.Inject; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static com.google.common.base.Charsets.UTF_8; import static com.googlecode.jmxtrans.model.PropertyResolver.resolveProps; /** * This low latency and thread safe output writer sends data to a host/port combination * in the Graphite format. * * @see <a href="http://graphite.wikidot.com/getting-your-data-into-graphite">Getting your data into Graphite</a> * * @author jon */ @NotThreadSafe public class GraphiteWriter extends BaseOutputWriter { private static final Logger log = LoggerFactory.getLogger(GraphiteWriter.class); private static final String DEFAULT_ROOT_PREFIX = "servers"; private GenericKeyedObjectPool<InetSocketAddress, Socket> pool; private final String rootPrefix; private final InetSocketAddress address; @JsonCreator public GraphiteWriter( @JsonProperty("typeNames") ImmutableList<String> typeNames, @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("debug") Boolean debugEnabled, @JsonProperty("rootPrefix") String rootPrefix, @JsonProperty("host") String host, @JsonProperty("port") Integer port, @JsonProperty("settings") Map<String, Object> settings) { super(typeNames, booleanAsNumber, debugEnabled, settings); this.rootPrefix = resolveProps( firstNonNull( rootPrefix, (String) getSettings().get("rootPrefix"), DEFAULT_ROOT_PREFIX)); host = resolveProps(host); if (host == null) { host = (String) getSettings().get(HOST); } if (host == null) { throw new NullPointerException("Host cannot be null."); } if (port == null) { port = Settings.getIntegerSetting(getSettings(), PORT, null); } if (port == null) { throw new NullPointerException("Port cannot be null."); } this.address = new InetSocketAddress(host, port); } public void validateSetup(Server server, Query query) throws ValidationException { } public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { Socket socket = null; + PrintWriter writer = null; try { socket = pool.borrowObject(address); - PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); + writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (NumberUtils.isNumeric(value)) { String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix) .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000 + "\n"; log.debug("Graphite Message: {}", line); writer.write(line); writer.flush(); } else { log.warn("Unable to submit non-numeric value to Graphite: [{}] from result [{}]", value, result); } } } } } finally { - pool.returnObject(address, socket); + if (writer != null && writer.checkError()) { + log.error("Error writing to Graphite, clearing Graphite socket pool"); + pool.invalidateObject(address, socket); + } else { + pool.returnObject(address, socket); + } } } public String getHost() { return address.getHostName(); } public int getPort() { return address.getPort(); } @Inject public void setPool(GenericKeyedObjectPool<InetSocketAddress, Socket> pool) { this.pool = pool; } public static Builder builder() { return new Builder(); } public static final class Builder { private final ImmutableList.Builder<String> typeNames = ImmutableList.builder(); private boolean booleanAsNumber; private Boolean debugEnabled; private String rootPrefix; private String host; private Integer port; private Builder() {} public Builder addTypeNames(List<String> typeNames) { this.typeNames.addAll(typeNames); return this; } public Builder addTypeName(String typeName) { typeNames.add(typeName); return this; } public Builder setBooleanAsNumber(boolean booleanAsNumber) { this.booleanAsNumber = booleanAsNumber; return this; } public Builder setDebugEnabled(boolean debugEnabled) { this.debugEnabled = debugEnabled; return this; } public Builder setRootPrefix(String rootPrefix) { this.rootPrefix = rootPrefix; return this; } public Builder setHost(String host) { this.host = host; return this; } public Builder setPort(int port) { this.port = port; return this; } public GraphiteWriter build() { return new GraphiteWriter( typeNames.build(), booleanAsNumber, debugEnabled, rootPrefix, host, port, null ); } } }
false
true
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { Socket socket = null; try { socket = pool.borrowObject(address); PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (NumberUtils.isNumeric(value)) { String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix) .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000 + "\n"; log.debug("Graphite Message: {}", line); writer.write(line); writer.flush(); } else { log.warn("Unable to submit non-numeric value to Graphite: [{}] from result [{}]", value, result); } } } } } finally { pool.returnObject(address, socket); } }
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { Socket socket = null; PrintWriter writer = null; try { socket = pool.borrowObject(address); writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (NumberUtils.isNumeric(value)) { String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix) .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000 + "\n"; log.debug("Graphite Message: {}", line); writer.write(line); writer.flush(); } else { log.warn("Unable to submit non-numeric value to Graphite: [{}] from result [{}]", value, result); } } } } } finally { if (writer != null && writer.checkError()) { log.error("Error writing to Graphite, clearing Graphite socket pool"); pool.invalidateObject(address, socket); } else { pool.returnObject(address, socket); } } }
diff --git a/WeCharades/src/com/example/wecharades/model/DataController.java b/WeCharades/src/com/example/wecharades/model/DataController.java index 3ffba16..d57f4b0 100644 --- a/WeCharades/src/com/example/wecharades/model/DataController.java +++ b/WeCharades/src/com/example/wecharades/model/DataController.java @@ -1,531 +1,538 @@ package com.example.wecharades.model; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.TreeMap; import java.util.TreeSet; import android.content.Context; /** * This is a class intended as an interface to the model and database. * All requests for DATA should be run through this class, which will handle * the logic of fetching cached data and retrieving form the database. * This class will also house the logic for pushing and updating data to both * @author Anton Dahlstr�m * */ public class DataController extends Observable implements Observer{ //TODO Delete later public Game getGame(String gameId){ return m.getGame(gameId); } private static boolean RECREATE = false; private static DataController dc; private Model m; private IDatabase db; private DataController(Context context){ m = Model.getModelInstance(context); db = Database.getDatabaseInstance(context); db.setConverter(this); db.addObserver(this); } public static DataController getDataController(Context context){ if(dc == null || RECREATE){ dc = new DataController(context); RECREATE = false; } return dc; } public void saveState(Context context){ if(m != null) m.saveModel(context); } /** * This method is called when the database has finished fetching turn and game data. */ @Override public void update(Observable db, Object obj) { //TODO Create a DBMessage class as well... if(obj != null && obj.getClass().equals(DBMessage.class)){ DBMessage dbm = (DBMessage) obj; if(dbm.getMessage() == DBMessage.ERROR){ setChanged(); notifyObservers(new DCMessage(DCMessage.ERROR, ((DatabaseException) dbm.getData()).prettyPrint())); } else if(dbm.getMessage() == DBMessage.GAMELIST){ ArrayList<Game> gameList = parseUpdatedGameList((TreeMap<Game, ArrayList<Turn>>) dbm.getData()); setChanged(); notifyObservers(new DCMessage(DCMessage.DATABASE_GAMES, gameList)); } else if(dbm.getMessage() == DBMessage.INVITATIONS){ List<Invitation> invList = parseDbInvitations((List<Invitation>) dbm.getData()); setChanged(); notifyObservers(new DCMessage(DCMessage.INVITATIONS, invList)); } } } //Session handling ----------------------------------------------------------- /** * Log in a player * @param username - The username (case insensitive) * @param password - The password * @throws DatabaseException - if the connection to the database fails */ public void loginPlayer(Context context, String username, String password) throws DatabaseException{ m = Model.getModelInstance(context); db = Database.getDatabaseInstance(context); db.loginPlayer(username, password); m.setCurrentPlayer(db.getCurrentPlayer()); } /** * Log out the current player */ public void logOutPlayer(Context context){ m.logOutCurrentPlayer(context); db.logOut(); RECREATE = true; } /** * returns the current user * @return */ public Player getCurrentPlayer(){ if(m.getCurrentPlayer() == null){ m.setCurrentPlayer(db.getCurrentPlayer()); } return m.getCurrentPlayer(); } /** * Register a player * @param inputNickname - The player * @param inputEmail - The registered email * @param inputPassword - the password * @param inputRepeatPassword - the password, repeated * @throws DatabaseException - if the connection fails */ public void registerPlayer( String inputNickname, String inputEmail, String inputPassword, String inputRepeatPassword ) throws DatabaseException{ db.registerPlayer(inputNickname, inputEmail, inputPassword,inputRepeatPassword); } /** * Resets the password connected to the provided email address * @param email - The email address connected to an account. * @throws DatabaseException - if the connection fails */ public void resetPassword(String email) throws DatabaseException{ db.resetPassword(email); } //Players ----------------------------------------------------------- /** * Get a user by its ParseId * @param parseId - the players ParseId * @return A player * @throws DatabaseException - if the connection to the database fails */ protected Player getPlayerById(String parseId) throws DatabaseException { Player p = m.getPlayerById(parseId); if(p == null){ p = db.getPlayerById(parseId); m.putPlayer(p); } return p; } /** * Get a user by its username * @param username - the players username * @return A player * @throws DatabaseException - if the connection to the database fails */ public Player getPlayer(String username) throws DatabaseException { Player p = m.getPlayer(username); if(p == null){ p = db.getPlayer(username); m.putPlayer(p); } return p; } /** * Returns a list of all players as objects * @return An ArrayList with players * @throws DatabaseException */ public ArrayList<Player> getAllPlayerObjects() throws DatabaseException { ArrayList<Player> players = db.getPlayers(); m.putPlayers(players); return players; } /** * Returns a list with all player names. This list will also be cached locally. * @return an ArrayList containing * @throws DatabaseException - if the connection to the database fails */ public TreeSet<String> getAllPlayerNames() throws DatabaseException { ArrayList<Player> players = getAllPlayerObjects(); TreeSet<String> nameList = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); for(Player p : players){ nameList.add(p.getName()); } return nameList; } /** * Returns a list with all player names. This list will also be cached locally. * @return an ArrayList containing * @throws DatabaseException - if the connection to the database fails */ public TreeSet<String> getAllOtherPlayerNames() throws DatabaseException { TreeSet<String> nameList = getAllPlayerNames(); nameList.remove(getCurrentPlayer().getName()); return nameList; } /** * * @return an ArrayList with Players */ public ArrayList<Player> getTopTenPlayers() throws DatabaseException { return db.getTopTenPlayers(); } public void updatePlayer(Player player){ m.putPlayer(player); db.updatePlayer(player); } //Games ----------------------------------------------------------- public void putInRandomQueue(){ db.putIntoRandomQueue(getCurrentPlayer()); } /** * Create a game. The local storage will not be updated * @param p1 - player 1 * @param p2 - player 2 * @throws DatabaseException - if the connection to the database fails */ public void createGame(Player p1, Player p2) throws DatabaseException{ db.createGame(p1, p2); } /** * Gets a list of current games. This should only be called from the StartPresenter, * as it updates the game-list from the database. If a game has changed, its current turn will be updated. * @throws DatabaseException - if the connection to the database fails */ public ArrayList<Game> getGames(){ //Fetches the db-list of current games db.fetchGames(getCurrentPlayer()); return m.getGames(); } /* * This is one of the core methods of this application. * This method will sync the database with the model! * //TODO This MIGHT have problems with it and is untested */ private ArrayList<Game> parseUpdatedGameList(TreeMap<Game, ArrayList<Turn>> dbGames) { Game localGame; for(Map.Entry<Game, ArrayList<Turn>> gameMap : dbGames.entrySet()){ localGame = m.getGame(gameMap.getKey().getGameId()); if(localGame == null || m.getTurns(localGame) == null){ //If the local game does not exist, or does not have any turns m.putGame(gameMap.getKey()); m.putTurns(gameMap.getValue()); } else if(Game.hasChanged(localGame, gameMap.getKey())){ if(localGame.getTurnNumber() < gameMap.getKey().getTurnNumber()){ //Run if the local turn is older than the db one. //It can then be deduced that the local turns are out-of-date. //Because of the saveEventually, we do not have to check the other way around. m.putGame(gameMap.getKey()); m.putTurns(gameMap.getValue()); } else if(localGame.isFinished()){ //Removes the instance in sent invitations when game is finished for(Invitation i : m.getSentInvitations()){ if(localGame.getPlayer1().equals(i.getInviter())){ m.removeSentInvitation(i); } } if(!localGame.getCurrentPlayer().equals(getCurrentPlayer())){ //This code deletes games and turns after they are finished! //This code is only reachable for the receiving player db.removeGame(localGame); } } } else if(!localGame.getCurrentPlayer().equals(gameMap.getKey().getCurrentPlayer())){ //If current player of a game is different, we must check the turns Turn localTurn = m.getCurrentTurn(localGame); Turn dbTurn = gameMap.getValue().get(gameMap.getKey().getTurnNumber()-1); if(localTurn.getState() > dbTurn.getState()){ //Update db.turn if local version is further ahead db.updateGame(localGame); db.updateTurn(localTurn); } else { //If something is wrong, allways use the "Golden master" - aka. the database m.putGame(gameMap.getKey()); m.putTurn(dbTurn); } + } else if ( + !(localGame.getCurrentPlayer().equals(m.getCurrentTurn(localGame).getRecPlayer()) && m.getCurrentTurn(localGame).getState() == Turn.INIT) + || !(localGame.getCurrentPlayer().equals(m.getCurrentTurn(localGame).getAnsPlayer()) && m.getCurrentTurn(localGame).getState() == Turn.VIDEO) + ){ + //This is done in order to ensure that data has been fetched without errors. If so, we replace everything! + m.putGame(gameMap.getKey()); + m.putTurns(gameMap.getValue()); } } removeOldGames(new ArrayList<Game>(dbGames.keySet())); return m.getGames(); } /* * This part removes any games that are "to old". */ private void removeOldGames(ArrayList<Game> dbGames){ ArrayList<Game> finishedGames = new ArrayList<Game>(); for(Game locGame : m.getGames()){ if(locGame.isFinished()){ finishedGames.add(locGame); } else if(!dbGames.contains(locGame)){ //Remove any sent invitations for the game in question for(Invitation inv : m.getSentInvitations()){ //We know that the local player will always be player 2, because of how games are created if(inv.getInvitee().equals(locGame.getPlayer2())){ m.removeSentInvitation(inv); } } //remove the actual game //TODO We could have a time restriction here, to avoid deleting new games. m.removeGame(locGame); } } if(finishedGames.size() > 0){ //Sort the games using a cusom time-comparator Collections.sort(finishedGames, new Comparator<Game>(){ @Override public int compare(Game g1, Game g2) { return (int) (g1.getLastPlayed().getTime() - g2.getLastPlayed().getTime()); } }); //Removes games that are to old - also with a number restriction. //The newest gemes are preferred (which is why we sort the list) long timeDiff; int numberSaved = 0; for(Game game : finishedGames){ if(numberSaved > Model.FINISHEDGAMES_NUMBERSAVED){ m.removeGame(game); } else{ timeDiff = ((new Date()).getTime() - game.getLastPlayed().getTime()) / (1000L * 3600L); if(timeDiff > 168){ m.removeGame(game); } else{ numberSaved ++; } } } } } public TreeMap<Player, Integer> getGameScore(Game game){ TreeMap<Player, Integer> returnMap = new TreeMap<Player, Integer>(); ArrayList<Turn> turnList = null; if(game != null){ turnList = getTurns(game); } if(turnList != null){ Player p1 = game.getPlayer1(); Player p2 = game.getPlayer2(); int p1s = 0; int p2s = 0; Turn currentTurn; for(int i=0; i < game.getTurnNumber(); i++){ currentTurn = turnList.get(i); p1s += currentTurn.getPlayerScore(p1); p2s += currentTurn.getPlayerScore(p2); } returnMap.put(p1, p1s); returnMap.put(p2, p2s); } else{ returnMap.put(game.getPlayer1(), 0); returnMap.put(game.getPlayer2(), 0); } return returnMap; } /** * Updates the database for the game. * if the turn is finished, this will also be set here. * @param game - the game to be updated * @throws DatabaseException */ private void updateGame(Game game) throws DatabaseException{ if(isFinished(game)){ game.setFinished(); } db.updateGame(game); } /* * Helper method for updateGame() */ private boolean isFinished(Game game){ return (game.getTurnNumber() == 6) && (m.getCurrentTurn(game).getState() == Turn.FINISH); } //Turn ----------------------------------------------------------- /** * Get all turns for a game. These are all collected from the stored instance - updated at startscreen. * @param game - The game who's turns to fetch * @return An ArrayList of turns */ public ArrayList<Turn> getTurns(Game game){ return m.getTurns(game); } public void updateTurn(Turn turn) throws DatabaseException{ m.putTurn(turn); db.updateTurn(turn); Game game = m.getGame(turn.getGameId()); switch(turn.getState()){ case Turn.INIT : game.setCurrentPlayer(turn.getRecPlayer()); break; case Turn.VIDEO : game.setCurrentPlayer(turn.getAnsPlayer()); break; case Turn.FINISH : game.incrementTurn(); break; } db.updateTurn(m.getCurrentTurn(game)); game.setLastPlayed(new Date()); updateGame(game); if(turn.getTurnNumber() == 6 && turn.getState() == Turn.FINISH){ TreeMap<Player, Integer> scoreMap = getGameScore(game); Player rec = turn.getRecPlayer(); Player ans = turn.getAnsPlayer(); rec.setGlobalScore(rec.getGlobalScore() + scoreMap.get(turn.getRecPlayer())); ans.setGlobalScore(ans.getGlobalScore() + scoreMap.get(turn.getAnsPlayer())); if(scoreMap.get(turn.getRecPlayer()) > scoreMap.get(turn.getAnsPlayer())){ rec.incrementWonGames(); ans.incrementLostGames(); } else if(scoreMap.get(turn.getRecPlayer()) < scoreMap.get(turn.getAnsPlayer())){ ans.incrementWonGames(); rec.incrementLostGames(); } else{ rec.incrementDrawGames(); ans.incrementDrawGames(); } rec.incrementFinishedGames(); ans.incrementFinishedGames(); updatePlayer(rec); updatePlayer(ans); } } //Invitation ----------------------------------------------------------- /** * A method to get all current invitations from the database */ public void getInvitations(){ try { db.getInvitations(getCurrentPlayer()); } catch (DatabaseException e) { setChanged(); notifyObservers(new DCMessage(DCMessage.MESSAGE, e.prettyPrint())); } } public List<Invitation> parseDbInvitations(List<Invitation> dbInv){ Date currentTime = new Date(); long timeDifference; ArrayList<Invitation> oldInvitations = new ArrayList<Invitation>(); for(Invitation inv : dbInv){ timeDifference = (currentTime.getTime() - inv.getTimeOfInvite().getTime()) / (1000L*3600L); if(timeDifference > Model.INVITATIONS_SAVETIME){ //if the invitations are considered to old oldInvitations.add(inv); dbInv.remove(inv); } } try{ db.removeInvitations(oldInvitations); } catch (DatabaseException e) { setChanged(); notifyObservers(new DCMessage(DCMessage.MESSAGE, e.prettyPrint())); } return dbInv; } /** * Retrieves a list of all invitations sent form this device. * @return An ArrayList containing Invitations */ public ArrayList<Invitation> getSentInvitations(){ return m.getSentInvitations(); } /** * Returns a set with all players the current player has sent invitations to. * @return A TreeSet containing String (natural)usernames */ public TreeSet<String> getSentInvitationsAsUsernames(){ TreeSet<String> usernames = new TreeSet<String>(); ArrayList<Invitation> invitations = getSentInvitations(); for(Invitation invitation : invitations){ usernames.add(invitation.getInvitee().getName()); } return usernames; } /** * Send an invitation to another player * @param invitation */ public void sendInvitation(Invitation invitation){ if(!m.getSentInvitations().contains(invitation)){ m.setSentInvitation(invitation); db.sendInvitation(invitation); } } /** * Send an invitation to another Player (based on the Player class) * @param player The player-representation of the player */ public void sendInvitation(Player player){ sendInvitation(new Invitation(getCurrentPlayer(), player, new Date())); } /** * Called in order to accept an invitation and automatically create a game. * @param invitation - The invitation to accept * @throws DatabaseException */ public void acceptInvitation(Invitation invitation) throws DatabaseException{ createGame(invitation.getInviter(), invitation.getInvitee()); db.removeInvitation(invitation); } /** * Called to reject an invitation, which is then deleted form the database * @param invitaiton - The invitation to reject * @throws DatabaseException */ public void rejectInvitation(Invitation invitaiton) throws DatabaseException{ db.removeInvitation(invitaiton); } }
true
true
private ArrayList<Game> parseUpdatedGameList(TreeMap<Game, ArrayList<Turn>> dbGames) { Game localGame; for(Map.Entry<Game, ArrayList<Turn>> gameMap : dbGames.entrySet()){ localGame = m.getGame(gameMap.getKey().getGameId()); if(localGame == null || m.getTurns(localGame) == null){ //If the local game does not exist, or does not have any turns m.putGame(gameMap.getKey()); m.putTurns(gameMap.getValue()); } else if(Game.hasChanged(localGame, gameMap.getKey())){ if(localGame.getTurnNumber() < gameMap.getKey().getTurnNumber()){ //Run if the local turn is older than the db one. //It can then be deduced that the local turns are out-of-date. //Because of the saveEventually, we do not have to check the other way around. m.putGame(gameMap.getKey()); m.putTurns(gameMap.getValue()); } else if(localGame.isFinished()){ //Removes the instance in sent invitations when game is finished for(Invitation i : m.getSentInvitations()){ if(localGame.getPlayer1().equals(i.getInviter())){ m.removeSentInvitation(i); } } if(!localGame.getCurrentPlayer().equals(getCurrentPlayer())){ //This code deletes games and turns after they are finished! //This code is only reachable for the receiving player db.removeGame(localGame); } } } else if(!localGame.getCurrentPlayer().equals(gameMap.getKey().getCurrentPlayer())){ //If current player of a game is different, we must check the turns Turn localTurn = m.getCurrentTurn(localGame); Turn dbTurn = gameMap.getValue().get(gameMap.getKey().getTurnNumber()-1); if(localTurn.getState() > dbTurn.getState()){ //Update db.turn if local version is further ahead db.updateGame(localGame); db.updateTurn(localTurn); } else { //If something is wrong, allways use the "Golden master" - aka. the database m.putGame(gameMap.getKey()); m.putTurn(dbTurn); } } } removeOldGames(new ArrayList<Game>(dbGames.keySet())); return m.getGames(); }
private ArrayList<Game> parseUpdatedGameList(TreeMap<Game, ArrayList<Turn>> dbGames) { Game localGame; for(Map.Entry<Game, ArrayList<Turn>> gameMap : dbGames.entrySet()){ localGame = m.getGame(gameMap.getKey().getGameId()); if(localGame == null || m.getTurns(localGame) == null){ //If the local game does not exist, or does not have any turns m.putGame(gameMap.getKey()); m.putTurns(gameMap.getValue()); } else if(Game.hasChanged(localGame, gameMap.getKey())){ if(localGame.getTurnNumber() < gameMap.getKey().getTurnNumber()){ //Run if the local turn is older than the db one. //It can then be deduced that the local turns are out-of-date. //Because of the saveEventually, we do not have to check the other way around. m.putGame(gameMap.getKey()); m.putTurns(gameMap.getValue()); } else if(localGame.isFinished()){ //Removes the instance in sent invitations when game is finished for(Invitation i : m.getSentInvitations()){ if(localGame.getPlayer1().equals(i.getInviter())){ m.removeSentInvitation(i); } } if(!localGame.getCurrentPlayer().equals(getCurrentPlayer())){ //This code deletes games and turns after they are finished! //This code is only reachable for the receiving player db.removeGame(localGame); } } } else if(!localGame.getCurrentPlayer().equals(gameMap.getKey().getCurrentPlayer())){ //If current player of a game is different, we must check the turns Turn localTurn = m.getCurrentTurn(localGame); Turn dbTurn = gameMap.getValue().get(gameMap.getKey().getTurnNumber()-1); if(localTurn.getState() > dbTurn.getState()){ //Update db.turn if local version is further ahead db.updateGame(localGame); db.updateTurn(localTurn); } else { //If something is wrong, allways use the "Golden master" - aka. the database m.putGame(gameMap.getKey()); m.putTurn(dbTurn); } } else if ( !(localGame.getCurrentPlayer().equals(m.getCurrentTurn(localGame).getRecPlayer()) && m.getCurrentTurn(localGame).getState() == Turn.INIT) || !(localGame.getCurrentPlayer().equals(m.getCurrentTurn(localGame).getAnsPlayer()) && m.getCurrentTurn(localGame).getState() == Turn.VIDEO) ){ //This is done in order to ensure that data has been fetched without errors. If so, we replace everything! m.putGame(gameMap.getKey()); m.putTurns(gameMap.getValue()); } } removeOldGames(new ArrayList<Game>(dbGames.keySet())); return m.getGames(); }
diff --git a/Asteroids/src/core/Game.java b/Asteroids/src/core/Game.java index 7205bd8..2c13435 100644 --- a/Asteroids/src/core/Game.java +++ b/Asteroids/src/core/Game.java @@ -1,104 +1,105 @@ /** * */ package core; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Shape; /** * @author a8011484 * */ public class Game extends BasicGame { Ship ship = new Ship(); List<Bullet> bullets = new ArrayList<Bullet>(); public Game() { super("Asteroids"); } @Override public void render(GameContainer container, Graphics g) throws SlickException { for (Entity entity : Entity.entities) { g.draw((Shape) entity.getDrawable()); } } @Override public void init(GameContainer container) throws SlickException { } @Override public void update(GameContainer container, int delta) throws SlickException { Input input = container.getInput(); ship.update(input.getMouseX(), input.getMouseY(), delta); if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) { ship.thrust(); } if (input.isMousePressed(Input.MOUSE_RIGHT_BUTTON)) { bullets.add(new Bullet(ship.getAngle(), ship.getX(), ship.getY())); } Iterator<Bullet> iterator = bullets.iterator(); while (iterator.hasNext()) { Bullet bullet = iterator.next(); bullet.update(delta); if (bullet.getX() > container.getWidth() || bullet.getX() < 0 || bullet.getY() > container.getHeight() || bullet.getY() < 0 ) { iterator.remove(); + Entity.entities.remove(bullet); } } if (ship.getX() > container.getWidth()) { ship.setX(0); } if (ship.getX() < 0) { ship.setX(container.getWidth()); } if (ship.getY() > container.getHeight()) { ship.setY(0); } if (ship.getY() < 0) { ship.setY(container.getHeight()); } } public static void main(String[] args) { try { AppGameContainer container = new AppGameContainer(new Game()); container.setDisplayMode(800,600,false); container.setVSync(true); container.start(); } catch (SlickException e) { e.printStackTrace(); } } }
true
true
public void update(GameContainer container, int delta) throws SlickException { Input input = container.getInput(); ship.update(input.getMouseX(), input.getMouseY(), delta); if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) { ship.thrust(); } if (input.isMousePressed(Input.MOUSE_RIGHT_BUTTON)) { bullets.add(new Bullet(ship.getAngle(), ship.getX(), ship.getY())); } Iterator<Bullet> iterator = bullets.iterator(); while (iterator.hasNext()) { Bullet bullet = iterator.next(); bullet.update(delta); if (bullet.getX() > container.getWidth() || bullet.getX() < 0 || bullet.getY() > container.getHeight() || bullet.getY() < 0 ) { iterator.remove(); } } if (ship.getX() > container.getWidth()) { ship.setX(0); } if (ship.getX() < 0) { ship.setX(container.getWidth()); } if (ship.getY() > container.getHeight()) { ship.setY(0); } if (ship.getY() < 0) { ship.setY(container.getHeight()); } }
public void update(GameContainer container, int delta) throws SlickException { Input input = container.getInput(); ship.update(input.getMouseX(), input.getMouseY(), delta); if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) { ship.thrust(); } if (input.isMousePressed(Input.MOUSE_RIGHT_BUTTON)) { bullets.add(new Bullet(ship.getAngle(), ship.getX(), ship.getY())); } Iterator<Bullet> iterator = bullets.iterator(); while (iterator.hasNext()) { Bullet bullet = iterator.next(); bullet.update(delta); if (bullet.getX() > container.getWidth() || bullet.getX() < 0 || bullet.getY() > container.getHeight() || bullet.getY() < 0 ) { iterator.remove(); Entity.entities.remove(bullet); } } if (ship.getX() > container.getWidth()) { ship.setX(0); } if (ship.getX() < 0) { ship.setX(container.getWidth()); } if (ship.getY() > container.getHeight()) { ship.setY(0); } if (ship.getY() < 0) { ship.setY(container.getHeight()); } }
diff --git a/test-src/org/pentaho/platform/dataaccess/catalog/impl/DatasourceChildTest.java b/test-src/org/pentaho/platform/dataaccess/catalog/impl/DatasourceChildTest.java index 4d56cb13..1c6a6a14 100644 --- a/test-src/org/pentaho/platform/dataaccess/catalog/impl/DatasourceChildTest.java +++ b/test-src/org/pentaho/platform/dataaccess/catalog/impl/DatasourceChildTest.java @@ -1,56 +1,56 @@ /** * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright 2006 - 2013 Pentaho Corporation. All rights reserved. * */ package org.pentaho.platform.dataaccess.catalog.impl; import org.junit.Before; import org.junit.Test; import org.pentaho.platform.dataaccess.catalog.api.IDatasourceChild; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DatasourceChildTest { DatasourceChild datasourceChild; @Before public void setUp() throws Exception { datasourceChild = new DatasourceChild( ); datasourceChild.setId( "1" ); datasourceChild.setName( "testDatasource1" ); DatasourceChild datasourceChild2 = new DatasourceChild( ); datasourceChild2.setId( "2" ); datasourceChild2.setName( "testDatasource2" ); DatasourceChild datasourceChild3 = new DatasourceChild( ); datasourceChild3.setId( "3" ); datasourceChild3.setName( "testDatasource3" ); - List<IDatasourceChild> datasourceChildList = new ArrayList<IDatasourceChild>( + List<DatasourceChild> datasourceChildList = new ArrayList<DatasourceChild>( Arrays.asList( datasourceChild2, datasourceChild3 ) ); datasourceChild.setChildren( datasourceChildList ); } @Test public void testGetChildren() throws Exception { assert ( datasourceChild.getChildren().size() == 2 ); } }
true
true
public void setUp() throws Exception { datasourceChild = new DatasourceChild( ); datasourceChild.setId( "1" ); datasourceChild.setName( "testDatasource1" ); DatasourceChild datasourceChild2 = new DatasourceChild( ); datasourceChild2.setId( "2" ); datasourceChild2.setName( "testDatasource2" ); DatasourceChild datasourceChild3 = new DatasourceChild( ); datasourceChild3.setId( "3" ); datasourceChild3.setName( "testDatasource3" ); List<IDatasourceChild> datasourceChildList = new ArrayList<IDatasourceChild>( Arrays.asList( datasourceChild2, datasourceChild3 ) ); datasourceChild.setChildren( datasourceChildList ); }
public void setUp() throws Exception { datasourceChild = new DatasourceChild( ); datasourceChild.setId( "1" ); datasourceChild.setName( "testDatasource1" ); DatasourceChild datasourceChild2 = new DatasourceChild( ); datasourceChild2.setId( "2" ); datasourceChild2.setName( "testDatasource2" ); DatasourceChild datasourceChild3 = new DatasourceChild( ); datasourceChild3.setId( "3" ); datasourceChild3.setName( "testDatasource3" ); List<DatasourceChild> datasourceChildList = new ArrayList<DatasourceChild>( Arrays.asList( datasourceChild2, datasourceChild3 ) ); datasourceChild.setChildren( datasourceChildList ); }
diff --git a/OpenLogJava/WebContent/WEB-INF/src/com/paulwithers/openLog/OpenLogItem.java b/OpenLogJava/WebContent/WEB-INF/src/com/paulwithers/openLog/OpenLogItem.java index 3de8a0b..7f9d1e3 100644 --- a/OpenLogJava/WebContent/WEB-INF/src/com/paulwithers/openLog/OpenLogItem.java +++ b/OpenLogJava/WebContent/WEB-INF/src/com/paulwithers/openLog/OpenLogItem.java @@ -1,1186 +1,1188 @@ package com.paulwithers.openLog; /* <!-- Copyright 2011 Paul Withers, Nathan T. Freeman & Tim Tripcony Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License --> */ /* * Paul Withers, Intec March 2013 * Some significant enhancements here since the version Nathan cleaned up for XPages Help Application. * Consequently, I've renamed the package completely, so there is no conflict * * 1. Everything is now static, so no need to create an OpenLog object * * 2. Everything now uses ExtLibUtil instead of Tim Tripcony's code (sorry, Tim! ;-) ) * * 3. _logDbName and olDebugLevel are set using getXspProperty(String, String). That method gets a value from * xsp.properties looking for the first parameter, looking first to current NSF, then the server. * If nothing is found, getIniVar is then called, looking to the notes.ini using the same key. * If nothing is still found, the second parameter from both methods is used, the default. * * 4. setThisAgent(boolean) method has been added. By default it gets the current page. * Otherwise it gets the previous page. Why? Because if we've been redirected to an error page, * we want to know which page the ACTUAL error occurred on. * * 5. logErrorEx has been fixed. It didn't work before. * * 6. _eventTime and _startTime recycled after creating logDoc. Nathan, I'll sleep a little less tonight, * but it's best practice ;-) */ /* * Nathan T. Freeman, GBS Jun 20, 2011 * Developers notes... * * There's more than I'd like to do here, but I think the entry points are much more sensible now. * * Because the log methods are static, one simply needs to call.. * * OpenLogItem.logError(session, throwable) * * or... * * OpenLogItem.logError(session, throwable, message, level, document) * * or... * * OpenLogItem.logEvent(session, message, level, document) * * All Domino objects have been made recycle-proof. All the nonsense about "init" and "reset" * and overloading constructors to do all the work is gone. * * There really SHOULD be an OpenLogManager that tracks settings like the java.util.Logging package does * but that is well beyond the scope of this little update * * Honestly, knowing that Julian does so much more Java work now, I can completely * sympathize with his occasional statement that OpenLog could use a major refactor. * * I wouldn't call this "major" but certainly "significant." * * One thing that would be SUPER useful is if the logEvent traced the caller automatically * even without a Throwable object passed. The problem is that the most likely use for this * entire class is from SSJS, which won't pass a contextual call stack by default. * * We'd need a LOT more infrastructure for that! */ import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.util.Date; import java.util.StringTokenizer; import java.util.Vector; import java.util.logging.Level; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import lotus.domino.Database; import lotus.domino.DateTime; import lotus.domino.Document; import lotus.domino.NotesException; import lotus.domino.RichTextItem; import lotus.domino.Session; import com.ibm.commons.util.StringUtil; import com.ibm.xsp.application.ApplicationEx; import com.ibm.xsp.extlib.util.ExtLibUtil; public class OpenLogItem implements Serializable { /* * ======================================================= <HEADER> NAME: OpenLogClass script library VERSION: * 20070321a AUTHOR(S): Julian Robichaux ( http://www.nsftools.com ) ORIGINAL SOURCE: The OpenLog database, * available as an open-source project at http://www.OpenNTF.org HISTORY: 20070321a: Added startTime global to mark * when this particular agent run began, so you can group multiple errors/events together more easily (see the * "by Database and Start Time" view) 20060314a: fixed bug where logErrorEx would set the message to the severity * type instead of the value of msg. 20041111a: made SEVERITY_ and TYPE_ constants public. 20040928a: added * callingMethodDepth variable, which should be incremented by one in the Synchronized class so we'll get a proper * reference to the calling method; make $PublicAccess = "1" when we create new log docs, so users with Depositor * access to this database can still create log docs. 20040226a: removed synchronization from all methods in the * main OpenLogItem class and added the new SynchronizedOpenLogItem class, which simply extends OpenLogItem and * calls all the public methods as synchronized methods. Added olDebugLevel and debugOut public members to report on * internal errors. 20040223a: add variables for user name, effective user name, access level, user roles, and * client version; synchronized most of the public methods. 20040222a: this version got a lot less aggressive with * the Notes object recycling, due to potential problems. Also made LogErrorEx and LogEvent return "" if an error * occurred (to be consistent with LogError); added OpenLogItem(Session s) constructor; now get server name from the * Session object, not the AgentContext object (due to differences in what those two things will give you); add * UseDefaultLogDb and UseCustomLogDb methods; added getLogDatabase method, to be consistent with LotusScript * functions; added useServerLogWhenLocal and logToCurrentDatabase variables/options 20040217a: this version made * the agentContext object global and fixed a problem where the agentContext was being recycled in the constuctor * (this is very bad) 20040214b: initial version * * DISCLAIMER: This code is provided "as-is", and should be used at your own risk. The authors make no express or * implied warranty about anything, and they will not be responsible or liable for any damage caused by the use or * misuse of this code or its byproducts. No guarantees are made about anything. * * That being said, you can use, modify, and distribute this code in any way you want, as long as you keep this * header section intact and in a prominent place in the code. </HEADER> * ======================================================= * * This class contains generic functions that can be used to log events and errors to the OpenLog database. All you * have to do it copy this script library to any database that should be sending errors to the OpenLog database, and * add it to your Java agents using the Edit Project button (see the "Using This Database" doc in the OpenLog * database for more details). * * At the beginning of your agent, create a global instance of this class like this: * * private OpenLogItem oli = new OpenLogItem(); * * and then in all the try/catch blocks that you want to send errors from, add the line: * * oli.logError(e); * * where "e" is the Exception that you caught. That's all you have to do. The LogError method will automatically * create a document in the OpenLog database that contains all sorts of information about the error that occurred, * including the name of the agent and function/sub that it occurred in. * * For additional functionality, you can use the LogErrorEx function to add a custom message, a severity level, * and/or a link to a NotesDocument to the log doc. * * In addition, you can use the LogEvent function to add a notification document to the OpenLog database. * * You'll notice that I trap and discard almost all of the Exceptions that may occur as the methods in this class * are running. This is because the class is normally only used when an error is occurring anyway, so there's not * sense in trying to pass any new errors back up the stack. * * The master copy of this script library resides in the OpenLog database. All copies of this library in other * databases should be set to inherit changes from that database. */ /** * */ private static final long serialVersionUID = 1L; public static final String TYPE_ERROR = "Error"; public static final String TYPE_EVENT = "Event"; private final static String _logFormName = "LogEvent"; // MODIFY THESE FOR YOUR OWN ENVIRONMENT // (don't forget to use double-backslashes if this database // is in a Windows subdirectory -- like "logs\\OpenLog.nsf") private static String _logDbName = ""; private static String _thisDatabase; private static String _thisServer; private static String _thisAgent; // why the object? Because the object version is serializable private static Boolean _logSuccess = true; private static String _accessLevel; private static Vector<String> _userRoles; private static Vector<String> _clientVersion; private static Boolean _displayError; private static String _displayErrorGeneric; private String _formName; private static Level _severity; private static String _eventType; private static String _message; private static Throwable _baseException; private static Date _startJavaTime; private static Date _eventJavaTime; private static String _errDocUnid; // These objects cannot be serialized, so they must be considered transient // so they'll be null on a restore private transient static Session _session; private transient static Database _logDb; private transient static Boolean _suppressEventStack; private transient static String _logEmail; private transient static Database _currentDatabase; private transient static DateTime _startTime; private transient static DateTime _eventTime; private transient static Document _errDoc; public static void setBase(Throwable base) { _baseException = base; } public static Throwable getBase() { return _baseException; } public static void setSeverity(Level severity) { _severity = severity; } /** * @param message * the message to set */ public static void setMessage(String message) { _message = message; } public static String getThisDatabase() { if (_thisDatabase == null) { try { _thisDatabase = getCurrentDatabase().getFilePath(); } catch (Exception e) { debugPrint(e); } } return _thisDatabase; } /** * @return the thisServer */ public static String getThisServer() { if (_thisServer == null) { try { _thisServer = getSession().getServerName(); if (_thisServer == null) _thisServer = ""; } catch (Exception e) { debugPrint(e); } } return _thisServer; } /** * @return the thisAgent */ public static String getThisAgent() { if (_thisAgent == null) { setThisAgent(true); } return _thisAgent; } public static void setThisAgent(boolean currPage) { String fromPage = ""; String[] historyUrls = ExtLibUtil.getXspContext().getHistoryUrls(); if (currPage) { fromPage = historyUrls[0]; } else { if (historyUrls.length > 1) { fromPage = historyUrls[1]; } else { fromPage = historyUrls[0]; } } _thisAgent = fromPage; if (fromPage.indexOf("?") > -1) { _thisAgent = _thisAgent.substring(1, _thisAgent.indexOf("?")); } } /** * @return the logDb */ public static Database getLogDb() { if (_logDb == null) { try { _logDb = getSession().getDatabase(getThisServer(), getLogDbName(), false); } catch (Exception e) { debugPrint(e); } } else { try { @SuppressWarnings("unused") boolean pointless = _logDb.isOpen(); } catch (NotesException recycleSucks) { // our database object was recycled so we'll need to get it // again try { _logDb = getSession().getDatabase(getThisServer(), getLogDbName(), false); } catch (Exception e) { debugPrint(e); } } } return _logDb; } /** * @return the currentDatabase */ public static Database getCurrentDatabase() { if (_currentDatabase == null) { try { _currentDatabase = getSession().getCurrentDatabase(); } catch (Exception e) { debugPrint(e); } } else { try { @SuppressWarnings("unused") boolean pointless = _currentDatabase.isOpen(); } catch (NotesException recycleSucks) { // our database object was recycled so we'll need to get it // again try { _currentDatabase = getSession().getCurrentDatabase(); } catch (Exception e) { debugPrint(e); } } } return _currentDatabase; } /** * @return the userName */ public static String getUserName() { try { return getSession().getUserName(); } catch (Exception e) { debugPrint(e); return ""; } } /** * @return the effName */ public static String getEffName() { try { return getSession().getEffectiveUserName(); } catch (Exception e) { debugPrint(e); return ""; } } /** * @return the accessLevel */ public static String getAccessLevel() { if (_accessLevel == null) { try { switch (getCurrentDatabase().getCurrentAccessLevel()) { case 0: _accessLevel = "0: No Access"; break; case 1: _accessLevel = "1: Depositor"; break; case 2: _accessLevel = "2: Reader"; break; case 3: _accessLevel = "3: Author"; break; case 4: _accessLevel = "4: Editor"; break; case 5: _accessLevel = "5: Designer"; break; case 6: _accessLevel = "6: Manager"; break; } } catch (Exception e) { debugPrint(e); } } return _accessLevel; } /** * @return the userRoles */ @SuppressWarnings("unchecked") public static Vector<String> getUserRoles() { if (_userRoles == null) { try { _userRoles = getSession().evaluate("@UserRoles"); } catch (Exception e) { debugPrint(e); } } return _userRoles; } /** * @return the clientVersion */ public static Vector<String> getClientVersion() { if (_clientVersion == null) { _clientVersion = new Vector<String>(); try { String cver = getSession().getNotesVersion(); if (cver != null) { if (cver.indexOf("|") > 0) { _clientVersion.addElement(cver.substring(0, cver.indexOf("|"))); _clientVersion.addElement(cver.substring(cver.indexOf("|") + 1)); } else { _clientVersion.addElement(cver); } } } catch (Exception e) { debugPrint(e); } } return _clientVersion; } /** * @return the startTime */ public static DateTime getStartTime() { if (_startTime == null) { try { _startTime = getSession().createDateTime("Today"); _startTime.setNow(); _startJavaTime = _startTime.toJavaDate(); } catch (Exception e) { debugPrint(e); } } else { try { @SuppressWarnings("unused") boolean junk = _startTime.isDST(); } catch (NotesException recycleSucks) { try { _startTime = getSession().createDateTime(_startJavaTime); } catch (Exception e) { debugPrint(e); } } } return _startTime; } /** * @return the logDbName */ public static String getLogEmail() { if (StringUtil.isEmpty(_logEmail)) { _logEmail = getXspProperty("xsp.openlog.email", ""); } return _logEmail; } /** * @return the logDbName */ public static String getLogDbName() { if ("".equals(_logDbName)) { _logDbName = getXspProperty("xsp.openlog.filepath", "OpenLog.nsf"); if ("[CURRENT]".equals(_logDbName.toUpperCase())) { setLogDbName(getThisDatabasePath()); } } return _logDbName; } /** * Gets xsp.property of whether to suppress stack trace. Should be xsp.openlog.suppressEventStack=true to suppress. * Anything else will return false * * @return whether or not stack should be suppressed for events */ public static Boolean getSuppressEventStack() { String dummyVar = getXspProperty("xsp.openlog.suppressEventStack", "false"); if (StringUtil.isEmpty(dummyVar)) { setSuppressEventStack(true); } else if ("FALSE".equals(dummyVar.toUpperCase())) { setSuppressEventStack(false); } else { setSuppressEventStack(true); } return _suppressEventStack; } /** * @param suppressEventStack * Boolean whether or not to suppress stack trace for Events */ public static void setSuppressEventStack(final Boolean suppressEventStack) { _suppressEventStack = suppressEventStack; } private static String getThisDatabasePath() { try { return getCurrentDatabase().getFilePath(); } catch (NotesException e) { debugPrint(e); return ""; } } /** * @return whether errors should be displayed or not */ public static Boolean getDisplayError() { if (null == _displayError) { String dummyVar = getXspProperty("xsp.openlog.displayError", "true"); if ("FALSE".equals(dummyVar.toUpperCase())) { setDisplayError(false); } else { setDisplayError(true); } } return _displayError; } /** * @param error * whether or not to display the errors */ public static void setDisplayError(Boolean error) { _displayError = error; } /** * @return String of a generic error message or an empty string */ public static String getDisplayErrorGeneric() { if (null == _displayErrorGeneric) { _displayErrorGeneric = getXspProperty("xsp.openlog.genericErrorMessage", ""); } return _displayErrorGeneric; } /** * @return the logFormName */ public String getLogFormName() { return _logFormName; } /** * @return the formName */ public String getFormName() { return _formName; } /** * @return the errLine */ public static int getErrLine(Throwable ee) { return ee.getStackTrace()[0].getLineNumber(); } /** * @return the severity */ public static Level getSeverity() { return _severity; } /** * @return the eventTime */ public static DateTime getEventTime() { if (_eventTime == null) { try { _eventTime = getSession().createDateTime("Today"); _eventTime.setNow(); _eventJavaTime = _eventTime.toJavaDate(); } catch (Exception e) { debugPrint(e); } } else { try { @SuppressWarnings("unused") boolean junk = _eventTime.isDST(); } catch (NotesException recycleSucks) { try { _eventTime = getSession().createDateTime(_eventJavaTime); } catch (Exception e) { debugPrint(e); } } } return _eventTime; } /** * @return the eventType */ public static String getEventType() { return _eventType; } /** * @return the message */ public static String getMessage() { if (_message.length() > 0) return _message; return getBase().getMessage(); } /** * @return the errDoc */ public static Document getErrDoc() { if (_errDoc != null) { try { @SuppressWarnings("unused") boolean junk = _errDoc.isProfile(); } catch (NotesException recycleSucks) { try { _errDoc = getCurrentDatabase().getDocumentByUNID(_errDocUnid); } catch (Exception e) { debugPrint(e); } } } return _errDoc; } public static void setErrDoc(Document doc) { if (doc != null) { _errDoc = doc; try { _errDocUnid = doc.getUniversalID(); } catch (NotesException ne) { debugPrint(ne); } catch (Exception ee) { // Added PW debugPrint(ee); // Added PW } } } // this variable sets the "debug level" of all the methods. Right now // the valid debug levels are: // 0 -- internal errors are discarded // 1 -- Exception messages from internal errors are printed // 2 -- stack traces from internal errors are also printed public static transient String olDebugLevel = getXspProperty("xsp.openlog.debugLevel", "2"); // debugOut is the PrintStream that errors will be printed to, for debug // levels // greater than 1 (System.err by default) public static PrintStream debugOut = System.err; // this is a strange little variable we use to determine how far down the // stack // the calling method should be (see the getBasicLogFields method if you're // curious) // protected int callingMethodDepth = 2; // Added PW 27/04/2011 to initialise variables for XPages Java and allow the // user to update logDbName public static void setLogDbName(String newLogPath) { _logDbName = newLogPath; } public static void setOlDebugLevel(String newDebugLevel) { olDebugLevel = newDebugLevel; } /* * Use this constructor when you're creating an instance of the class within the confines of an Agent. It will * automatically pick up the agent name, the current database, and the server. */ public OpenLogItem() { } private static String getXspProperty(String propertyName, String defaultValue) { String retVal = ApplicationEx.getInstance().getApplicationProperty(propertyName, getIniVar(propertyName, defaultValue)); return retVal; } private static String getIniVar(String propertyName, String defaultValue) { try { String newVal = getSession().getEnvironmentString(propertyName, true); if (StringUtil.isNotEmpty(newVal)) { return newVal; } else { return defaultValue; } } catch (NotesException e) { debugPrint(e); return defaultValue; } } private static Session getSession() { if (_session == null) { _session = ExtLibUtil.getCurrentSession(); } else { try { @SuppressWarnings("unused") boolean pointless = _session.isOnServer(); } catch (NotesException recycleSucks) { // our database object was recycled so we'll need to get it // again try { _session = ExtLibUtil.getCurrentSession(); } catch (Exception e) { debugPrint(e); } } } return _session; } /* * We can't really safely recycle() any of the global Notes objects, because there's no guarantee that nothing else * is using them. Instead, just set everything to null */ public void recycle() { _errDoc = null; _logDb = null; _session = null; } /* * This gets called automatically when the object is destroyed. */ // @Override // protected void finalize() throws Throwable { // recycle(); // super.finalize(); // } /* * see what the status of the last logging event was */ public boolean getLogSuccess() { return _logSuccess; } /* * reset all the global fields to their default values */ // public void resetFields() { // try { // _formName = _logFormName; // _errNum = 0; // _errLine = 0; // _errMsg = ""; // _methodName = ""; // _eventType = TYPE_ERROR; // _message = ""; // _errDoc = null; // } catch (Exception e) { // debugPrint(e); // } // } /* * The basic method you can use to log an error. Just pass the Exception that you caught and this method collects * information and saves it to the OpenLog database. */ public static String logError(Throwable ee) { if (ee != null) { for (StackTraceElement elem : ee.getStackTrace()) { if (elem.getClassName().equals(OpenLogItem.class.getName())) { // NTF - we are by definition in a loop System.out.println(ee.toString()); debugPrint(ee); _logSuccess = false; return ""; } } } try { StackTraceElement[] s = ee.getStackTrace(); FacesMessage m = new FacesMessage("Error in " + s[0].getClassName() + ", line " + s[0].getLineNumber() + ": " + ee.toString()); ExtLibUtil.getXspContext().getFacesContext().addMessage(null, m); setBase(ee); // if (ee.getMessage().length() > 0) { if (ee.getMessage() != null) { setMessage(ee.getMessage()); } else { setMessage(ee.getClass().getCanonicalName()); } setSeverity(Level.WARNING); setEventType(TYPE_ERROR); _logSuccess = writeToLog(); return getMessage(); } catch (Exception e) { System.out.println(e.toString()); debugPrint(e); _logSuccess = false; return ""; } } private static void setEventType(String typeError) { _eventType = typeError; } /* * A slightly more flexible way to send an error to the OpenLog database. This allows you to include a message * string (which gets added to the log document just before the stack trace), a severity type (normally one of the * standard severity types within this class: OpenLogItem.SEVERITY_LOW, OpenLogItem.SEVERITY_MEDIUM, or * OpenLogItem.SEVERITY_HIGH), and/or a Document that may have something to do with the error (in which case a * DocLink to that Document will be added to the log document). */ public static String logErrorEx(Throwable ee, String msg, Level severityType, Document doc) { if (ee != null) { for (StackTraceElement elem : ee.getStackTrace()) { if (elem.getClassName().equals(OpenLogItem.class.getName())) { // NTF - we are by definition in a loop System.out.println(ee.toString()); debugPrint(ee); _logSuccess = false; return ""; } } } try { setBase((ee == null ? new Throwable() : ee)); setMessage((msg == null ? "" : msg)); setSeverity(severityType == null ? Level.WARNING : severityType); setEventType(TYPE_ERROR); setErrDoc(doc); _logSuccess = writeToLog(); return msg; } catch (Exception e) { debugPrint(e); _logSuccess = false; return ""; } } /* * This method allows you to log an Event to the OpenLog database. You should include a message describing the * event, a severity type (normally one of the standard severity types within this class: OpenLogItem.SEVERITY_LOW, * OpenLogItem.SEVERITY_MEDIUM, or OpenLogItem.SEVERITY_HIGH), and optionally a Document that may have something to * do with the event (in which case a DocLink to that Document will be added to the log document). */ public static String logEvent(Throwable ee, String msg, Level severityType, Document doc) { try { setMessage(msg); setSeverity(severityType == null ? Level.INFO : severityType); setEventType(TYPE_EVENT); setErrDoc(doc); if (ee == null) { // Added PW - LogEvent will not pass a throwable setBase(new Throwable("")); // Added PW } else { // Added PW setBase(ee); // Added PW } // Added PW _logSuccess = writeToLog(); return msg; } catch (Exception e) { debugPrint(e); _logSuccess = false; return ""; } } /* * A helper method that gets some basic information for the global variables that's common to all errors and events * (event time and the name of the calling method). * * The stacklevel parameter probably looks a little mysterious. It's supposed to be the number of levels below the * calling method that we're at right now, so we know how far down the stack trace we need to look to get the name * of the calling method. For example, if another method called the logError method, and the logError method called * this method, then the calling method is going to be 2 levels down the stack, so stacklevel should be = 2. That * may not make sense to anyone but me, but it seems to work... */ // private boolean getBasicLogFields(int stacklevel) { // try { // try { // Throwable ee = new Throwable("whatever"); // _stackTrace = getStackTrace(ee, stacklevel + 1); // // stackTrace = getStackTrace(ee); // } catch (Exception e) { // } // // // if (_eventTime == null) // // _eventTime = _session.createDateTime("Today"); // // _eventTime.setNow(); // // _methodName = getMethodName(_stackTrace, 0); // // return true; // } catch (Exception e) { // debugPrint(e); // return false; // } // } /* * If an Exception is a NotesException, this method will extract the Notes error number and error message. */ // private boolean setErrorLogFields(Throwable ee) { // try { // // try { // if (ee instanceof NotesException) { // NotesException ne = (NotesException) ee; // setErrNum(ne.id); // setErrMsg(ne.text); // } else { // setErrMsg(getStackTrace().elementAt(0).toString()); // } // } catch (Exception e) { // setErrMsg(""); // } // // return true; // } catch (Exception e) { // debugPrint(e); // return false; // } // } /* * Get the stack trace of an Exception as a Vector, without the initial error message, and skipping over a given * number of items (as determined by the skip variable) */ private static Vector<String> getStackTrace(Throwable ee, int skip) { Vector<String> v = new Vector<String>(32); try { StringWriter sw = new StringWriter(); ee.printStackTrace(new PrintWriter(sw)); StringTokenizer st = new StringTokenizer(sw.toString(), "\n"); int count = 0; while (st.hasMoreTokens()) { if (skip <= count++) v.addElement(st.nextToken().trim()); else st.nextToken(); } } catch (Exception e) { debugPrint(e); } return v; } private static Vector<String> getStackTrace(Throwable ee) { return getStackTrace(ee, 0); } public static void logError(Session s, Throwable ee) { if (s != null) { _session = s; } logError(ee); } public static void logError(Session s, Throwable ee, String message, Level severity, Document doc) { if (s != null) { _session = s; } logErrorEx(ee, message, severity, doc); } public static void logEvent(Session s, Throwable ee, String message, Level severity, Document doc) { if (s != null) { _session = s; } logEvent(ee, message, severity, doc); } /* * This is the method that does the actual logging to the OpenLog database. You'll notice that I actually have a * Database parameter, which is normally a reference to the OpenLog database that you're using. However, it occurred * to me that you might want to use this class to write to an alternate log database at times, so I left you that * option (although you're stuck with the field names used by the OpenLog database in that case). * * This method creates a document in the log database, populates the fields of that document with the values in our * global variables, and adds some associated information about any Document that needs to be referenced. If you do * decide to send log information to an alternate database, you can just call this method manually after you've * called logError or logEvent, and it will write everything to the database of your choice. */ public static boolean writeToLog() { // exit early if there is no database Database db = null; boolean retval = false; Document logDoc = null; RichTextItem rtitem = null; Database docDb = null; try { if (StringUtil.isEmpty(getLogEmail())) { db = getLogDb(); } else { db = getSession().getDatabase(getThisServer(), "mail.box", false); } if (db == null) { System.out.println("Could not retrieve database at path " + getLogDbName()); return false; } logDoc = db.createDocument(); rtitem = logDoc.createRichTextItem("LogDocInfo"); logDoc.appendItemValue("Form", _logFormName); Throwable ee = getBase(); String errMsg = ""; if (null != ee) { StackTraceElement ste = ee.getStackTrace()[0]; if (ee instanceof NotesException) { logDoc.replaceItemValue("LogErrorNumber", ((NotesException) ee).id); errMsg = ((NotesException) ee).text; } else if ("Interpret exception".equals(ee.getMessage()) && ee instanceof com.ibm.jscript.JavaScriptException) { com.ibm.jscript.InterpretException ie = (com.ibm.jscript.InterpretException) ee; errMsg = "Expression Language Interpret Exception " + ie.getExpressionText(); } else { errMsg = ee.getMessage(); } if (TYPE_EVENT.equals(getEventType())) { if (!getSuppressEventStack()) { logDoc.replaceItemValue("LogStackTrace", getStackTrace(ee)); } + } else { + logDoc.replaceItemValue("LogStackTrace", getStackTrace(ee)); } logDoc.replaceItemValue("LogErrorLine", ste.getLineNumber()); logDoc.replaceItemValue("LogFromMethod", ste.getClass() + "." + ste.getMethodName()); } if ("".equals(errMsg)) { errMsg = getMessage(); } logDoc.replaceItemValue("LogErrorMessage", errMsg); logDoc.replaceItemValue("LogEventTime", getEventTime()); logDoc.replaceItemValue("LogEventType", getEventType()); // If greater than 32k, put in logDocInfo if (getMessage().length() > 32000) { rtitem.appendText(getMessage()); rtitem.addNewLine(); } else { logDoc.replaceItemValue("LogMessage", getMessage()); } logDoc.replaceItemValue("LogSeverity", getSeverity().getName()); logDoc.replaceItemValue("LogFromDatabase", getThisDatabase()); logDoc.replaceItemValue("LogFromServer", getThisServer()); logDoc.replaceItemValue("LogFromAgent", getThisAgent()); logDoc.replaceItemValue("LogAgentLanguage", "Java"); logDoc.replaceItemValue("LogUserName", getUserName()); logDoc.replaceItemValue("LogEffectiveName", getEffName()); logDoc.replaceItemValue("LogAccessLevel", getAccessLevel()); logDoc.replaceItemValue("LogUserRoles", getUserRoles()); logDoc.replaceItemValue("LogClientVersion", getClientVersion()); logDoc.replaceItemValue("LogAgentStartTime", getStartTime()); if (getErrDoc() != null) { docDb = getErrDoc().getParentDatabase(); rtitem.appendText("The document associated with this event is:"); rtitem.addNewLine(1); rtitem.appendText("Server: " + docDb.getServer()); rtitem.addNewLine(1); rtitem.appendText("Database: " + docDb.getFilePath()); rtitem.addNewLine(1); rtitem.appendText("UNID: " + getErrDoc().getUniversalID()); rtitem.addNewLine(1); rtitem.appendText("Note ID: " + getErrDoc().getNoteID()); rtitem.addNewLine(1); rtitem.appendText("DocLink: "); rtitem.appendDocLink(_errDoc, getErrDoc().getUniversalID()); } // make sure Depositor-level users can add documents too logDoc.appendItemValue("$PublicAccess", "1"); if (StringUtil.isNotEmpty(getLogEmail())) { logDoc.replaceItemValue("Recipients", getLogEmail()); logDoc.replaceItemValue("SendTo", getLogEmail()); logDoc.replaceItemValue("From", getUserName()); logDoc.replaceItemValue("Principal", getUserName()); } logDoc.save(true); retval = true; } catch (Throwable t) { debugPrint(t); retval = false; } finally { // recycle all the logDoc objects when we're done with them try { if (rtitem != null) rtitem.recycle(); } catch (Exception e2) { // NTF why the hell does .recycle() throw an Exception? } rtitem = null; try { if (logDoc != null) logDoc.recycle(); } catch (Exception e2) { // see above } logDoc = null; try { if (_startTime != null) _startTime.recycle(); } catch (Exception e2) { // see above } _startTime = null; try { if (_eventTime != null) _eventTime.recycle(); } catch (Exception e2) { // see above } _eventTime = null; } return retval; } /* * This method decides what to do with any Exceptions that we encounter internal to this class, based on the * olDebugLevel variable. */ private static void debugPrint(Throwable ee) { if ((ee == null) || (debugOut == null)) return; try { // debug level of 1 prints the basic error message# int debugLevel = Integer.parseInt(olDebugLevel); if (debugLevel >= 1) { String debugMsg = ee.toString(); try { if (ee instanceof NotesException) { NotesException ne = (NotesException) ee; debugMsg = "Notes error " + ne.id + ": " + ne.text; } } catch (Exception e2) { } debugOut.println("OpenLogItem error: " + debugMsg); } // debug level of 2 prints the whole stack trace if (debugLevel >= 2) { debugOut.print("OpenLogItem error trace: "); ee.printStackTrace(debugOut); } } catch (Exception e) { // at this point, if we have an error just discard it } } /** * @param component * String component ID * @param msg * String message to be passed back to the browser */ public static void addFacesMessage(String component, String msg) { if (!"".equals(getDisplayErrorGeneric())) { if (null == ExtLibUtil.getRequestScope().get("genericOpenLogMessage")) { ExtLibUtil.getRequestScope().put("genericOpenLogMessage", "Added"); } else { return; } msg = _displayErrorGeneric; } FacesContext.getCurrentInstance().addMessage(component, new FacesMessage(msg)); } }
true
true
public static boolean writeToLog() { // exit early if there is no database Database db = null; boolean retval = false; Document logDoc = null; RichTextItem rtitem = null; Database docDb = null; try { if (StringUtil.isEmpty(getLogEmail())) { db = getLogDb(); } else { db = getSession().getDatabase(getThisServer(), "mail.box", false); } if (db == null) { System.out.println("Could not retrieve database at path " + getLogDbName()); return false; } logDoc = db.createDocument(); rtitem = logDoc.createRichTextItem("LogDocInfo"); logDoc.appendItemValue("Form", _logFormName); Throwable ee = getBase(); String errMsg = ""; if (null != ee) { StackTraceElement ste = ee.getStackTrace()[0]; if (ee instanceof NotesException) { logDoc.replaceItemValue("LogErrorNumber", ((NotesException) ee).id); errMsg = ((NotesException) ee).text; } else if ("Interpret exception".equals(ee.getMessage()) && ee instanceof com.ibm.jscript.JavaScriptException) { com.ibm.jscript.InterpretException ie = (com.ibm.jscript.InterpretException) ee; errMsg = "Expression Language Interpret Exception " + ie.getExpressionText(); } else { errMsg = ee.getMessage(); } if (TYPE_EVENT.equals(getEventType())) { if (!getSuppressEventStack()) { logDoc.replaceItemValue("LogStackTrace", getStackTrace(ee)); } } logDoc.replaceItemValue("LogErrorLine", ste.getLineNumber()); logDoc.replaceItemValue("LogFromMethod", ste.getClass() + "." + ste.getMethodName()); } if ("".equals(errMsg)) { errMsg = getMessage(); } logDoc.replaceItemValue("LogErrorMessage", errMsg); logDoc.replaceItemValue("LogEventTime", getEventTime()); logDoc.replaceItemValue("LogEventType", getEventType()); // If greater than 32k, put in logDocInfo if (getMessage().length() > 32000) { rtitem.appendText(getMessage()); rtitem.addNewLine(); } else { logDoc.replaceItemValue("LogMessage", getMessage()); } logDoc.replaceItemValue("LogSeverity", getSeverity().getName()); logDoc.replaceItemValue("LogFromDatabase", getThisDatabase()); logDoc.replaceItemValue("LogFromServer", getThisServer()); logDoc.replaceItemValue("LogFromAgent", getThisAgent()); logDoc.replaceItemValue("LogAgentLanguage", "Java"); logDoc.replaceItemValue("LogUserName", getUserName()); logDoc.replaceItemValue("LogEffectiveName", getEffName()); logDoc.replaceItemValue("LogAccessLevel", getAccessLevel()); logDoc.replaceItemValue("LogUserRoles", getUserRoles()); logDoc.replaceItemValue("LogClientVersion", getClientVersion()); logDoc.replaceItemValue("LogAgentStartTime", getStartTime()); if (getErrDoc() != null) { docDb = getErrDoc().getParentDatabase(); rtitem.appendText("The document associated with this event is:"); rtitem.addNewLine(1); rtitem.appendText("Server: " + docDb.getServer()); rtitem.addNewLine(1); rtitem.appendText("Database: " + docDb.getFilePath()); rtitem.addNewLine(1); rtitem.appendText("UNID: " + getErrDoc().getUniversalID()); rtitem.addNewLine(1); rtitem.appendText("Note ID: " + getErrDoc().getNoteID()); rtitem.addNewLine(1); rtitem.appendText("DocLink: "); rtitem.appendDocLink(_errDoc, getErrDoc().getUniversalID()); } // make sure Depositor-level users can add documents too logDoc.appendItemValue("$PublicAccess", "1"); if (StringUtil.isNotEmpty(getLogEmail())) { logDoc.replaceItemValue("Recipients", getLogEmail()); logDoc.replaceItemValue("SendTo", getLogEmail()); logDoc.replaceItemValue("From", getUserName()); logDoc.replaceItemValue("Principal", getUserName()); } logDoc.save(true); retval = true; } catch (Throwable t) { debugPrint(t); retval = false; } finally { // recycle all the logDoc objects when we're done with them try { if (rtitem != null) rtitem.recycle(); } catch (Exception e2) { // NTF why the hell does .recycle() throw an Exception? } rtitem = null; try { if (logDoc != null) logDoc.recycle(); } catch (Exception e2) { // see above } logDoc = null; try { if (_startTime != null) _startTime.recycle(); } catch (Exception e2) { // see above } _startTime = null; try { if (_eventTime != null) _eventTime.recycle(); } catch (Exception e2) { // see above } _eventTime = null; } return retval; }
public static boolean writeToLog() { // exit early if there is no database Database db = null; boolean retval = false; Document logDoc = null; RichTextItem rtitem = null; Database docDb = null; try { if (StringUtil.isEmpty(getLogEmail())) { db = getLogDb(); } else { db = getSession().getDatabase(getThisServer(), "mail.box", false); } if (db == null) { System.out.println("Could not retrieve database at path " + getLogDbName()); return false; } logDoc = db.createDocument(); rtitem = logDoc.createRichTextItem("LogDocInfo"); logDoc.appendItemValue("Form", _logFormName); Throwable ee = getBase(); String errMsg = ""; if (null != ee) { StackTraceElement ste = ee.getStackTrace()[0]; if (ee instanceof NotesException) { logDoc.replaceItemValue("LogErrorNumber", ((NotesException) ee).id); errMsg = ((NotesException) ee).text; } else if ("Interpret exception".equals(ee.getMessage()) && ee instanceof com.ibm.jscript.JavaScriptException) { com.ibm.jscript.InterpretException ie = (com.ibm.jscript.InterpretException) ee; errMsg = "Expression Language Interpret Exception " + ie.getExpressionText(); } else { errMsg = ee.getMessage(); } if (TYPE_EVENT.equals(getEventType())) { if (!getSuppressEventStack()) { logDoc.replaceItemValue("LogStackTrace", getStackTrace(ee)); } } else { logDoc.replaceItemValue("LogStackTrace", getStackTrace(ee)); } logDoc.replaceItemValue("LogErrorLine", ste.getLineNumber()); logDoc.replaceItemValue("LogFromMethod", ste.getClass() + "." + ste.getMethodName()); } if ("".equals(errMsg)) { errMsg = getMessage(); } logDoc.replaceItemValue("LogErrorMessage", errMsg); logDoc.replaceItemValue("LogEventTime", getEventTime()); logDoc.replaceItemValue("LogEventType", getEventType()); // If greater than 32k, put in logDocInfo if (getMessage().length() > 32000) { rtitem.appendText(getMessage()); rtitem.addNewLine(); } else { logDoc.replaceItemValue("LogMessage", getMessage()); } logDoc.replaceItemValue("LogSeverity", getSeverity().getName()); logDoc.replaceItemValue("LogFromDatabase", getThisDatabase()); logDoc.replaceItemValue("LogFromServer", getThisServer()); logDoc.replaceItemValue("LogFromAgent", getThisAgent()); logDoc.replaceItemValue("LogAgentLanguage", "Java"); logDoc.replaceItemValue("LogUserName", getUserName()); logDoc.replaceItemValue("LogEffectiveName", getEffName()); logDoc.replaceItemValue("LogAccessLevel", getAccessLevel()); logDoc.replaceItemValue("LogUserRoles", getUserRoles()); logDoc.replaceItemValue("LogClientVersion", getClientVersion()); logDoc.replaceItemValue("LogAgentStartTime", getStartTime()); if (getErrDoc() != null) { docDb = getErrDoc().getParentDatabase(); rtitem.appendText("The document associated with this event is:"); rtitem.addNewLine(1); rtitem.appendText("Server: " + docDb.getServer()); rtitem.addNewLine(1); rtitem.appendText("Database: " + docDb.getFilePath()); rtitem.addNewLine(1); rtitem.appendText("UNID: " + getErrDoc().getUniversalID()); rtitem.addNewLine(1); rtitem.appendText("Note ID: " + getErrDoc().getNoteID()); rtitem.addNewLine(1); rtitem.appendText("DocLink: "); rtitem.appendDocLink(_errDoc, getErrDoc().getUniversalID()); } // make sure Depositor-level users can add documents too logDoc.appendItemValue("$PublicAccess", "1"); if (StringUtil.isNotEmpty(getLogEmail())) { logDoc.replaceItemValue("Recipients", getLogEmail()); logDoc.replaceItemValue("SendTo", getLogEmail()); logDoc.replaceItemValue("From", getUserName()); logDoc.replaceItemValue("Principal", getUserName()); } logDoc.save(true); retval = true; } catch (Throwable t) { debugPrint(t); retval = false; } finally { // recycle all the logDoc objects when we're done with them try { if (rtitem != null) rtitem.recycle(); } catch (Exception e2) { // NTF why the hell does .recycle() throw an Exception? } rtitem = null; try { if (logDoc != null) logDoc.recycle(); } catch (Exception e2) { // see above } logDoc = null; try { if (_startTime != null) _startTime.recycle(); } catch (Exception e2) { // see above } _startTime = null; try { if (_eventTime != null) _eventTime.recycle(); } catch (Exception e2) { // see above } _eventTime = null; } return retval; }
diff --git a/extrabiomes/src/extrabiomes/module/amica/forestry/ForestryPlugin.java b/extrabiomes/src/extrabiomes/module/amica/forestry/ForestryPlugin.java index 70acf212..be57c715 100644 --- a/extrabiomes/src/extrabiomes/module/amica/forestry/ForestryPlugin.java +++ b/extrabiomes/src/extrabiomes/module/amica/forestry/ForestryPlugin.java @@ -1,257 +1,257 @@ /** * This work is licensed under the Creative Commons * Attribution-ShareAlike 3.0 Unported License. To view a copy of this * license, visit http://creativecommons.org/licenses/by-sa/3.0/. */ package extrabiomes.module.amica.forestry; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import net.minecraft.src.Block; import net.minecraft.src.ItemStack; import net.minecraftforge.event.ForgeSubscribe; import com.google.common.base.Optional; import extrabiomes.Extrabiomes; import extrabiomes.ExtrabiomesLog; import extrabiomes.api.PluginEvent; import extrabiomes.api.Stuff; import extrabiomes.module.summa.TreeSoilRegistry; import extrabiomes.module.summa.block.BlockAutumnLeaves; import extrabiomes.module.summa.block.BlockCustomFlower; import extrabiomes.module.summa.block.BlockCustomSapling; import extrabiomes.module.summa.block.BlockGreenLeaves; import extrabiomes.module.summa.block.BlockRedRock; public class ForestryPlugin { private Class liquidStack; private Object fermenterManager; private static boolean enabled = true; private ArrayList arborealCrops; private ArrayList plainFlowers; private ArrayList leafBlockIds; private ArrayList[] backpackItems; public static ArrayList loggerWindfall; /** * public LiquidStack(int itemID, int amount, int itemDamage); */ private Optional<Constructor> liquidStackConstructor = Optional .absent(); /** * public void addRecipe(ItemStack resource, int fermentationValue, * float modifier, LiquidStack output, LiquisStack liquid); */ private Optional<Method> fermenterAddRecipe = Optional .absent(); /** * public static ItemStack getItem(String ident); */ private Optional<Method> getForestryItem = Optional .absent(); /** * public static ItemStack getItem(String ident); */ private static Optional<Method> getForestryBlock = Optional .absent(); private static final int DIGGER = 1; private static final int FORESTER = 2; static ItemStack getBlock(String name) { try { return (ItemStack) getForestryBlock.get() .invoke(null, name); } catch (final Exception e) { return null; } } private void addBackPackItems() { if (Stuff.crackedSand.isPresent()) backpackItems[DIGGER].add(new ItemStack(Stuff.crackedSand .get())); if (Stuff.redRock.isPresent()) backpackItems[DIGGER].add(new ItemStack( Stuff.redRock.get(), 1, BlockRedRock.BlockType.RED_COBBLE.metadata())); if (Stuff.quickSand.isPresent()) backpackItems[DIGGER].add(new ItemStack(Stuff.quickSand .get())); if (Stuff.leavesAutumn.isPresent()) for (final BlockAutumnLeaves.BlockType type : BlockAutumnLeaves.BlockType .values()) backpackItems[FORESTER].add(new ItemStack( Stuff.leavesAutumn.get(), 1, type.metadata())); if (Stuff.leavesGreen.isPresent()) for (final BlockGreenLeaves.BlockType type : BlockGreenLeaves.BlockType .values()) backpackItems[FORESTER].add(new ItemStack( Stuff.leavesGreen.get(), 1, type.metadata())); if (Stuff.sapling.isPresent()) for (final BlockCustomSapling.BlockType type : BlockCustomSapling.BlockType .values()) backpackItems[FORESTER].add(new ItemStack(Stuff.sapling .get(), 1, type.metadata())); if (Stuff.flower.isPresent()) for (final BlockCustomFlower.BlockType type : BlockCustomFlower.BlockType .values()) backpackItems[FORESTER].add(new ItemStack(Stuff.flower .get(), 1, type.metadata())); } private void addBasicFlowers() { if (!Stuff.flower.isPresent()) return; plainFlowers.add(new ItemStack(Stuff.flower.get(), 1, BlockCustomFlower.BlockType.HYDRANGEA.metadata())); plainFlowers.add(new ItemStack(Stuff.flower.get(), 1, BlockCustomFlower.BlockType.ORANGE.metadata())); plainFlowers.add(new ItemStack(Stuff.flower.get(), 1, BlockCustomFlower.BlockType.PURPLE.metadata())); plainFlowers.add(new ItemStack(Stuff.flower.get(), 1, BlockCustomFlower.BlockType.WHITE.metadata())); } private void addFermenterRecipeSapling(ItemStack resource) throws Exception { fermenterAddRecipe.get().invoke( fermenterManager, resource, 800, 1.0f, getLiquidStack("liquidBiomass"), liquidStackConstructor.get().newInstance( Block.waterStill.blockID, 1, 0)); fermenterAddRecipe.get().invoke(fermenterManager, resource, 800, 1.5f, getLiquidStack("liquidBiomass"), getLiquidStack("liquidJuice")); fermenterAddRecipe.get().invoke(fermenterManager, resource, 800, 1.5f, getLiquidStack("liquidBiomass"), getLiquidStack("liquidHoney")); } private void addGlobals() { if (Stuff.leavesAutumn.isPresent()) leafBlockIds.add(Stuff.leavesAutumn.get().blockID); if (Stuff.leavesGreen.isPresent()) leafBlockIds.add(Stuff.leavesGreen.get().blockID); } private void addRecipes() throws Exception { if (fermenterAddRecipe.isPresent() && getForestryItem.isPresent() && Stuff.sapling.isPresent() && liquidStackConstructor.isPresent()) for (final BlockCustomSapling.BlockType type : BlockCustomSapling.BlockType .values()) addFermenterRecipeSapling(new ItemStack( Stuff.sapling.get().blockID, 1, type.metadata())); } private void addSaplings() { if (!Stuff.sapling.isPresent()) return; final Optional<ItemStack> soil = Optional .fromNullable(getBlock("soil")); if (soil.isPresent()) TreeSoilRegistry .addValidSoil(Block.blocksList[soil.get().itemID]); arborealCrops.add(new CropProviderSapling()); } private Object getLiquidStack(String name) throws Exception { final ItemStack itemStack = (ItemStack) getForestryItem.get() .invoke(null, name); return liquidStackConstructor.get().newInstance( itemStack.itemID, 1, itemStack.getItemDamage()); } @ForgeSubscribe public void init(PluginEvent.Init event) throws Exception { if (!isEnabled()) return; addSaplings(); addBasicFlowers(); addGlobals(); addBackPackItems(); addRecipes(); } private boolean isEnabled() { return enabled && Extrabiomes.proxy.isModLoaded("Forestry"); } @ForgeSubscribe public void preInit(PluginEvent.Pre event) { if (!isEnabled()) return; ExtrabiomesLog.info("Initializing Forestry plugin."); try { liquidStack = Class .forName("buildcraft.api.liquids.LiquidStack"); liquidStackConstructor = Optional.fromNullable(liquidStack .getConstructor(int.class, int.class, int.class)); Class cls = Class .forName("forestry.api.core.ItemInterface"); getForestryItem = Optional.fromNullable(cls.getMethod( "getItem", String.class)); cls = Class.forName("forestry.api.core.BlockInterface"); getForestryBlock = Optional.fromNullable(cls.getMethod( "getBlock", String.class)); cls = Class.forName("forestry.api.recipes.RecipeManagers"); Field fld = cls.getField("fermenterManager"); fermenterManager = fld.get(null); cls = Class - .forName("forestry.api.cultivation.CropProviders"); + .forName("forestry.api.core.ForestryAPI"); fld = cls.getField("loggerWindfall"); loggerWindfall = (ArrayList) fld.get(null); - cls = Class.forName("forestry.api.core.ForestryAPI"); + cls = Class.forName("forestry.api.cultivation.CropProviders"); fld = cls.getField("arborealCrops"); arborealCrops = (ArrayList) fld.get(null); cls = Class .forName("forestry.api.apiculture.FlowerManager"); fld = cls.getField("plainFlowers"); plainFlowers = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.core.GlobalManager"); fld = cls.getField("leafBlockIds"); leafBlockIds = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.storage.BackpackManager"); fld = cls.getField("backpackItems"); backpackItems = (ArrayList[]) fld.get(null); cls = Class .forName("forestry.api.recipes.IFermenterManager"); fermenterAddRecipe = Optional.fromNullable(cls.getMethod( "addRecipe", ItemStack.class, int.class, float.class, liquidStack, liquidStack)); } catch (final Exception ex) { ex.printStackTrace(); ExtrabiomesLog .fine("Could not find Forestry fields. Disabling plugin."); enabled = false; } } }
false
true
public void preInit(PluginEvent.Pre event) { if (!isEnabled()) return; ExtrabiomesLog.info("Initializing Forestry plugin."); try { liquidStack = Class .forName("buildcraft.api.liquids.LiquidStack"); liquidStackConstructor = Optional.fromNullable(liquidStack .getConstructor(int.class, int.class, int.class)); Class cls = Class .forName("forestry.api.core.ItemInterface"); getForestryItem = Optional.fromNullable(cls.getMethod( "getItem", String.class)); cls = Class.forName("forestry.api.core.BlockInterface"); getForestryBlock = Optional.fromNullable(cls.getMethod( "getBlock", String.class)); cls = Class.forName("forestry.api.recipes.RecipeManagers"); Field fld = cls.getField("fermenterManager"); fermenterManager = fld.get(null); cls = Class .forName("forestry.api.cultivation.CropProviders"); fld = cls.getField("loggerWindfall"); loggerWindfall = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.core.ForestryAPI"); fld = cls.getField("arborealCrops"); arborealCrops = (ArrayList) fld.get(null); cls = Class .forName("forestry.api.apiculture.FlowerManager"); fld = cls.getField("plainFlowers"); plainFlowers = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.core.GlobalManager"); fld = cls.getField("leafBlockIds"); leafBlockIds = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.storage.BackpackManager"); fld = cls.getField("backpackItems"); backpackItems = (ArrayList[]) fld.get(null); cls = Class .forName("forestry.api.recipes.IFermenterManager"); fermenterAddRecipe = Optional.fromNullable(cls.getMethod( "addRecipe", ItemStack.class, int.class, float.class, liquidStack, liquidStack)); } catch (final Exception ex) { ex.printStackTrace(); ExtrabiomesLog .fine("Could not find Forestry fields. Disabling plugin."); enabled = false; } }
public void preInit(PluginEvent.Pre event) { if (!isEnabled()) return; ExtrabiomesLog.info("Initializing Forestry plugin."); try { liquidStack = Class .forName("buildcraft.api.liquids.LiquidStack"); liquidStackConstructor = Optional.fromNullable(liquidStack .getConstructor(int.class, int.class, int.class)); Class cls = Class .forName("forestry.api.core.ItemInterface"); getForestryItem = Optional.fromNullable(cls.getMethod( "getItem", String.class)); cls = Class.forName("forestry.api.core.BlockInterface"); getForestryBlock = Optional.fromNullable(cls.getMethod( "getBlock", String.class)); cls = Class.forName("forestry.api.recipes.RecipeManagers"); Field fld = cls.getField("fermenterManager"); fermenterManager = fld.get(null); cls = Class .forName("forestry.api.core.ForestryAPI"); fld = cls.getField("loggerWindfall"); loggerWindfall = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.cultivation.CropProviders"); fld = cls.getField("arborealCrops"); arborealCrops = (ArrayList) fld.get(null); cls = Class .forName("forestry.api.apiculture.FlowerManager"); fld = cls.getField("plainFlowers"); plainFlowers = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.core.GlobalManager"); fld = cls.getField("leafBlockIds"); leafBlockIds = (ArrayList) fld.get(null); cls = Class.forName("forestry.api.storage.BackpackManager"); fld = cls.getField("backpackItems"); backpackItems = (ArrayList[]) fld.get(null); cls = Class .forName("forestry.api.recipes.IFermenterManager"); fermenterAddRecipe = Optional.fromNullable(cls.getMethod( "addRecipe", ItemStack.class, int.class, float.class, liquidStack, liquidStack)); } catch (final Exception ex) { ex.printStackTrace(); ExtrabiomesLog .fine("Could not find Forestry fields. Disabling plugin."); enabled = false; } }
diff --git a/src/com/mojang/mojam/resources/Texts.java b/src/com/mojang/mojam/resources/Texts.java index f28f45ca..5375c547 100644 --- a/src/com/mojang/mojam/resources/Texts.java +++ b/src/com/mojang/mojam/resources/Texts.java @@ -1,77 +1,77 @@ package com.mojang.mojam.resources; import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBundle; public class Texts { protected final ResourceBundle texts; public Texts(Locale locale) { texts = ResourceBundle.getBundle("properties/texts", locale); } public String playerName(int team) { switch (team) { case 1: return player1Name(); case 2: - return player1Name(); + return player2Name(); } return ""; } public String player1Name() { return texts.getString("player1Name"); } public String player2Name() { return texts.getString("player2Name"); } public String player1Win() { return MessageFormat.format(texts.getString("player1Win"), player1Name().toUpperCase()); } public String player2Win() { return MessageFormat.format(texts.getString("player2Win"), player2Name().toUpperCase()); } public String hasDied(int team) { return MessageFormat.format(texts.getString("hasDied"), playerName(team)); } public String score(int team, int score) { return MessageFormat.format(texts.getString("score"), playerName(team), score); } public String cost(int cost) { return MessageFormat.format(texts.getString("cost"), cost); } public String health(int health, int maxHealth) { return MessageFormat.format(texts.getString("health"), health, maxHealth); } public String money(int money) { return MessageFormat.format(texts.getString("money"), money); } public String waitingForClient() { return texts.getString("waitingForClient"); } public String enterIP() { return texts.getString("enterIP"); } public String FPS(int fps) { return MessageFormat.format(texts.getString("FPS"), fps); } }
true
true
public String playerName(int team) { switch (team) { case 1: return player1Name(); case 2: return player1Name(); } return ""; }
public String playerName(int team) { switch (team) { case 1: return player1Name(); case 2: return player2Name(); } return ""; }
diff --git a/javamelody-swing/src/main/java/net/bull/javamelody/ChartsPanel.java b/javamelody-swing/src/main/java/net/bull/javamelody/ChartsPanel.java index a1ba6f17..3794e8d9 100644 --- a/javamelody-swing/src/main/java/net/bull/javamelody/ChartsPanel.java +++ b/javamelody-swing/src/main/java/net/bull/javamelody/ChartsPanel.java @@ -1,139 +1,140 @@ /* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java Melody is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.Map; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.SwingWorker; import net.bull.javamelody.swing.MButton; import net.bull.javamelody.swing.Utilities; import net.bull.javamelody.swing.util.MSwingUtilities; /** * Panel des graphiques principaux. * @author Emeric Vernat */ class ChartsPanel extends MelodyPanel { static final ImageIcon PLUS_ICON = ImageIconCache.getImageIcon("bullets/plus.png"); static final ImageIcon MINUS_ICON = ImageIconCache.getImageIcon("bullets/minus.png"); private static final long serialVersionUID = 1L; private static final Cursor HAND_CURSOR = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); private static final ImageIcon THROBBER_ICON = new ImageIcon( ChartsPanel.class.getResource("/icons/throbber.gif")); private static final int NB_COLS = 3; private static final int CHART_HEIGHT = 50; private static final int CHART_WIDTH = 200; private JPanel otherJRobinsPanel; ChartsPanel(RemoteCollector remoteCollector) { super(remoteCollector); final JLabel throbberLabel = new JLabel(THROBBER_ICON); add(throbberLabel, BorderLayout.NORTH); add(createButtonsPanel(), BorderLayout.CENTER); // SwingWorker pour afficher le reste de l'écran et pour éviter de faire attendre rien que pour les graphiques final SwingWorker<Map<String, byte[]>, Object> swingWorker = new SwingWorker<Map<String, byte[]>, Object>() { @Override protected Map<String, byte[]> doInBackground() throws IOException { return getRemoteCollector().collectJRobins(CHART_WIDTH, CHART_HEIGHT); } @Override protected void done() { try { final Map<String, byte[]> jrobins = get(); final JPanel mainJRobinsPanel = createJRobinPanel(jrobins); remove(throbberLabel); add(mainJRobinsPanel, BorderLayout.NORTH); revalidate(); } catch (final Exception e) { MSwingUtilities.showException(e); + remove(throbberLabel); } } }; swingWorker.execute(); } final JPanel createJRobinPanel(Map<String, byte[]> jrobins) { final JPanel centerPanel = new JPanel(new GridLayout(-1, NB_COLS)); centerPanel.setOpaque(false); for (final Map.Entry<String, byte[]> entry : jrobins.entrySet()) { final ImageIcon icon = new ImageIcon(entry.getValue()); final JLabel label = new JLabel(icon); label.setHorizontalAlignment(SwingConstants.CENTER); label.setCursor(HAND_CURSOR); // TODO MouseListener pour zoom centerPanel.add(label); } final JPanel graphicsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); graphicsPanel.setOpaque(false); graphicsPanel.add(centerPanel); return graphicsPanel; } private JPanel createButtonsPanel() { final MButton detailsButton = new MButton(I18N.getString("Autres_courbes"), PLUS_ICON); detailsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { showOtherJRobinsPanel(); if (detailsButton.getIcon() == PLUS_ICON) { detailsButton.setIcon(MINUS_ICON); } else { detailsButton.setIcon(PLUS_ICON); } } catch (final IOException ex) { MSwingUtilities.showException(ex); } } }); return Utilities.createButtonsPanel(detailsButton); } final void showOtherJRobinsPanel() throws IOException { if (otherJRobinsPanel == null) { final Map<String, byte[]> otherJRobins = getRemoteCollector().collectOtherJRobins( CHART_WIDTH, CHART_HEIGHT); otherJRobinsPanel = createJRobinPanel(otherJRobins); otherJRobinsPanel.setVisible(false); add(otherJRobinsPanel, BorderLayout.SOUTH); } otherJRobinsPanel.setVisible(!otherJRobinsPanel.isVisible()); otherJRobinsPanel.validate(); } }
true
true
ChartsPanel(RemoteCollector remoteCollector) { super(remoteCollector); final JLabel throbberLabel = new JLabel(THROBBER_ICON); add(throbberLabel, BorderLayout.NORTH); add(createButtonsPanel(), BorderLayout.CENTER); // SwingWorker pour afficher le reste de l'écran et pour éviter de faire attendre rien que pour les graphiques final SwingWorker<Map<String, byte[]>, Object> swingWorker = new SwingWorker<Map<String, byte[]>, Object>() { @Override protected Map<String, byte[]> doInBackground() throws IOException { return getRemoteCollector().collectJRobins(CHART_WIDTH, CHART_HEIGHT); } @Override protected void done() { try { final Map<String, byte[]> jrobins = get(); final JPanel mainJRobinsPanel = createJRobinPanel(jrobins); remove(throbberLabel); add(mainJRobinsPanel, BorderLayout.NORTH); revalidate(); } catch (final Exception e) { MSwingUtilities.showException(e); } } }; swingWorker.execute(); }
ChartsPanel(RemoteCollector remoteCollector) { super(remoteCollector); final JLabel throbberLabel = new JLabel(THROBBER_ICON); add(throbberLabel, BorderLayout.NORTH); add(createButtonsPanel(), BorderLayout.CENTER); // SwingWorker pour afficher le reste de l'écran et pour éviter de faire attendre rien que pour les graphiques final SwingWorker<Map<String, byte[]>, Object> swingWorker = new SwingWorker<Map<String, byte[]>, Object>() { @Override protected Map<String, byte[]> doInBackground() throws IOException { return getRemoteCollector().collectJRobins(CHART_WIDTH, CHART_HEIGHT); } @Override protected void done() { try { final Map<String, byte[]> jrobins = get(); final JPanel mainJRobinsPanel = createJRobinPanel(jrobins); remove(throbberLabel); add(mainJRobinsPanel, BorderLayout.NORTH); revalidate(); } catch (final Exception e) { MSwingUtilities.showException(e); remove(throbberLabel); } } }; swingWorker.execute(); }
diff --git a/GlassLineFactory/src/engine/sky/agent/SkyPopUpAgent.java b/GlassLineFactory/src/engine/sky/agent/SkyPopUpAgent.java index c007590..6d96c06 100755 --- a/GlassLineFactory/src/engine/sky/agent/SkyPopUpAgent.java +++ b/GlassLineFactory/src/engine/sky/agent/SkyPopUpAgent.java @@ -1,497 +1,498 @@ package engine.sky.agent; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Semaphore; import engine.agent.Agent; import engine.interfaces.ConveyorFamily; import engine.interfaces.SkyMachine; import engine.util.GlassType; import transducer.TChannel; import transducer.TEvent; import transducer.Transducer; public class SkyPopUpAgent extends Agent implements ConveyorFamily { /** Data **/ private MyConveyor postConveyor; private MyConveyor preConveyor; private MyMachine firstMachine; private MyMachine secondMachine; private int myGuiIndex; private GlassType currentGlass; private Target target; private State myState, savedState; private boolean glassLoaded; private boolean informed = false; public enum MachineState {Idle, Processing, Done, Off}; public enum ConveyorState {Available, UnAvailable}; public enum Target {None, PreConveyor, PostConveyor, Machine1, Machine2, Animating}; public enum State { Down, Up, Animating, Broken}; private class MyConveyor { ConveyorFamily conveyor; ConveyorState state; public MyConveyor(ConveyorFamily c, ConveyorState s) { conveyor = c; state = s; } } private class MyMachine { SkyMachine machine; MachineState state, savedState; public MyMachine(SkyMachine m, MachineState s) { machine = m; state = s; } } /** Constructor **/ public SkyPopUpAgent(ConveyorFamily pre, ConveyorFamily post, SkyMachine first, SkyMachine second, int guiIndex, String n, Transducer tr) { super(n,tr); preConveyor = new MyConveyor(pre, ConveyorState.UnAvailable); postConveyor = new MyConveyor(post, ConveyorState.UnAvailable); firstMachine = new MyMachine (first, MachineState.Idle); secondMachine = new MyMachine (second, MachineState.Idle); myGuiIndex = guiIndex; transducer.register(this, TChannel.POPUP); } public SkyPopUpAgent(int guiIndex, String n, Transducer tr) { super(n,tr); myGuiIndex = guiIndex; transducer.register(this, TChannel.POPUP); target = Target.None; myState = State.Down; glassLoaded = false; } /** Messages **/ public void msgGlassRemoved(SkyMachine machine){ if (machine == firstMachine.machine) { if (firstMachine.state != MachineState.Off) { firstMachine.state = MachineState.Idle; } else { firstMachine.savedState = MachineState.Idle; } } else if (machine == secondMachine.machine) { if (secondMachine.state != MachineState.Off) { secondMachine.state =MachineState.Idle; } else { secondMachine.savedState = MachineState.Idle; } } stateChanged(); } @Override public void msgPassingGlass(GlassType gt) { currentGlass = gt; glassLoaded = false; target = Target.PreConveyor; stateChanged(); } @Override public void msgIAmAvailable() { System.out.println(this + " received msgIAmAvailable"); postConveyor.state = ConveyorState.Available; stateChanged(); } @Override public void msgIAmNotAvailable() { System.out.println(this + " msgIAmNotAvailable: Target = " + target + " State = " + myState); postConveyor.state = ConveyorState.UnAvailable; if (currentGlass == null) { System.out.println("CurrentGlass = null"); } else { System.out.println("CurrentGlass != null"); } if (glassLoaded == true) { System.out.println("Load finished"); } else { System.out.println("Load Not Finished"); } stateChanged(); } //Called by machine when machine finished loading public void msgLoadFinished() { target = Target.None; if (myState != State.Broken) { myState = State.Up; } else { savedState = State.Up; } System.out.println("msgLoadFinished: Target = " + target + " State = " + myState); stateChanged(); } public void msgGlassDone(SkyMachine machine, GlassType gt) { if (machine == firstMachine.machine) { if (firstMachine.state != MachineState.Off) { firstMachine.state = MachineState.Done; } else { firstMachine.savedState = MachineState.Done; } } else if (machine == secondMachine.machine) { if (secondMachine.state != MachineState.Off) { secondMachine.state =MachineState.Done; } else { secondMachine.savedState = MachineState.Done; } } stateChanged(); } public void msgReturningGlass(SkyMachine machine, GlassType gt) { currentGlass = gt; glassLoaded = false; if (machine == firstMachine.machine) { firstMachine.state = MachineState.Idle; target = Target.Machine1; } else if (machine == secondMachine.machine) { secondMachine.state =MachineState.Idle; target = Target.Machine2; } stateChanged(); } public void msgPopUpBreak() { if (myState == State.Up) { savedState = State.Up; } else if (myState == State.Down) { savedState = State.Down; } else if (myState == State.Animating) { savedState = State.Animating; } preConveyor.conveyor.msgIAmNotAvailable(); informed = false; myState = State.Broken; System.out.println(this+" breaking the pop up"); } public void msgPopUpUnbreak() { myState = savedState; System.out.println(this+" fixing the pop up with state = "); stateChanged(); } public void msgOfflineMachineOn(int machineIndex) { if (machineIndex%2 ==0) { firstMachine.state = firstMachine.savedState; } else { secondMachine.state = secondMachine.savedState; } } public void msgOfflineMachineOff(int machineIndex) { if (machineIndex%2 ==0) { firstMachine.savedState = firstMachine.state; firstMachine.state = MachineState.Off; } else { secondMachine.savedState = secondMachine.state; secondMachine.state = MachineState.Off; } } // Animation messages private void msgGlassLoaded() { glassLoaded = true; if (target == Target.None || target == Target.PostConveyor || target == Target.PreConveyor) { if (myState!=State.Broken) myState = State.Down; else { savedState = State.Down; } target = Target.None; } else{ if (myState!=State.Broken) myState = State.Up; else { savedState = State.Up; } target = Target.PostConveyor; } stateChanged(); } private void msgMovedUp() { if (myState!=State.Broken) myState = State.Up; else { savedState = State.Up; } stateChanged(); } private void msgMovedDown() { if (myState!=State.Broken) myState = State.Down; else { savedState = State.Down; } stateChanged(); } private void msgGlassReleased() { currentGlass = null; if (myState!=State.Broken) myState = State.Down; else { savedState = State.Down; } target = Target.None; stateChanged(); } /** Scheduler **/ @Override public boolean pickAndExecuteAnAction() { System.out.println(this + " Scheduler with state = " +myState + " target = " + target); if (currentGlass != null && target == Target.None && myState == State.Up) { if (firstMachine.state == MachineState.Idle) { target = Target.Machine1; passToMachine(firstMachine); return true; } else if (secondMachine.state == MachineState.Idle){ target = Target.Machine2; passToMachine(secondMachine); return true; } } if (currentGlass == null && target == Target.None && myState == State.Down) { if (firstMachine.state == MachineState.Done) { target = Target.Machine1; popUp(); // pop up to say ready return true; } else if (secondMachine.state == MachineState.Done) { target = Target.Machine2; popUp(); // pop up to say ready return true; } else if (!informed && (firstMachine.state == MachineState.Idle || secondMachine.state == MachineState.Idle)){ informIAmAvailable(); return true; } else if (!informed) { informOkToSkip(); return true; } } if (currentGlass != null && target == Target.None && myState == State.Down && glassLoaded) { if (currentGlass.getConfig(myGuiIndex)) { target = Target.None; popUp(); // pop up to give to machine return true; } } if (currentGlass == null && myState == State.Up) { if (target == Target.None) { popDown(); } else if (target == Target.Machine1) { sayReady(firstMachine); } else if (target == Target.Machine2) { sayReady(secondMachine); } return true; } if (currentGlass !=null && myState == State.Up && target == Target.PostConveyor) { popDown(); return true; } if (currentGlass !=null && myState == State.Down && glassLoaded) { if (postConveyor.state == ConveyorState.Available) { passToConveyor(); return true; } - else { + else if (!informed){ preConveyor.conveyor.msgIAmNotAvailable(); + informed = true; return true; } } return false; } /**Actions **/ private void informIAmAvailable() { System.out.println(this +" Action: informIAmAvailable"); preConveyor.conveyor.msgIAmAvailable(); // myState = State.Animating; informed = true; } private void informOkToSkip() { System.out.println(this +" Action: informOkToPass"); ((SkyConveyorAgent) preConveyor.conveyor).msgOkToSkip(); informed = true; } private void popUp() { System.out.println(this +" Action: popUp"); preConveyor.conveyor.msgIAmNotAvailable(); Object[] args = new Object[1]; args[0] = myGuiIndex; transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_DO_MOVE_UP, args); myState = State.Animating; } private void popDown() { System.out.println(this +" Action: popDown"); Object[] args = new Object[1]; args[0] = myGuiIndex; transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_DO_MOVE_DOWN, args); myState = State.Animating; informed = false; } private void sayReady(MyMachine mm) { System.out.println(this +" Action: sayReady"); mm.machine.msgIAmReady(); myState = State.Animating; } private void passToMachine(MyMachine mm) { System.out.println(this +" Action: passToMachine"); mm.machine.msgPassingGlass(currentGlass); mm.state = MachineState.Processing; myState = State.Animating; currentGlass = null; } private void passToConveyor() { System.out.println(this + " Action: passToConveyor"); preConveyor.conveyor.msgIAmNotAvailable(); Object[] args = new Object[1]; args[0] = myGuiIndex; postConveyor.conveyor.msgPassingGlass(currentGlass); transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_RELEASE_GLASS, args); myState = State.Animating; informed = false; } /** Utilities **/ public GlassType getGlass() { return currentGlass; } public MachineState getFirstMachineState() { return firstMachine.state; } public MachineState getSecondMachineState() { return secondMachine.state; } public ConveyorState getPostConveyorState() { return postConveyor.state; } public void connectAgents(ConveyorFamily pre, ConveyorFamily post, SkyMachine first, SkyMachine second) { preConveyor = new MyConveyor(pre, ConveyorState.UnAvailable); postConveyor = new MyConveyor(post, ConveyorState.UnAvailable); firstMachine = new MyMachine (first, MachineState.Idle); secondMachine = new MyMachine (second, MachineState.Idle); } @Override public void eventFired(TChannel channel, TEvent event, Object[] args) { if (channel == TChannel.POPUP && event == TEvent.POPUP_GUI_LOAD_FINISHED &&((Integer)args[0]).equals(myGuiIndex)) { this.msgGlassLoaded(); } if (channel == TChannel.POPUP && event == TEvent.POPUP_GUI_MOVED_UP && ((Integer)args[0]).equals(myGuiIndex)) { this.msgMovedUp(); } if (channel == TChannel.POPUP && event == TEvent.POPUP_GUI_MOVED_DOWN && ((Integer)args[0]).equals(myGuiIndex)) { this.msgMovedDown(); } if (channel == TChannel.POPUP && event == TEvent.POPUP_GUI_RELEASE_FINISHED && ((Integer)args[0]).equals(myGuiIndex)) { this.msgGlassReleased(); } } }
false
true
public boolean pickAndExecuteAnAction() { System.out.println(this + " Scheduler with state = " +myState + " target = " + target); if (currentGlass != null && target == Target.None && myState == State.Up) { if (firstMachine.state == MachineState.Idle) { target = Target.Machine1; passToMachine(firstMachine); return true; } else if (secondMachine.state == MachineState.Idle){ target = Target.Machine2; passToMachine(secondMachine); return true; } } if (currentGlass == null && target == Target.None && myState == State.Down) { if (firstMachine.state == MachineState.Done) { target = Target.Machine1; popUp(); // pop up to say ready return true; } else if (secondMachine.state == MachineState.Done) { target = Target.Machine2; popUp(); // pop up to say ready return true; } else if (!informed && (firstMachine.state == MachineState.Idle || secondMachine.state == MachineState.Idle)){ informIAmAvailable(); return true; } else if (!informed) { informOkToSkip(); return true; } } if (currentGlass != null && target == Target.None && myState == State.Down && glassLoaded) { if (currentGlass.getConfig(myGuiIndex)) { target = Target.None; popUp(); // pop up to give to machine return true; } } if (currentGlass == null && myState == State.Up) { if (target == Target.None) { popDown(); } else if (target == Target.Machine1) { sayReady(firstMachine); } else if (target == Target.Machine2) { sayReady(secondMachine); } return true; } if (currentGlass !=null && myState == State.Up && target == Target.PostConveyor) { popDown(); return true; } if (currentGlass !=null && myState == State.Down && glassLoaded) { if (postConveyor.state == ConveyorState.Available) { passToConveyor(); return true; } else { preConveyor.conveyor.msgIAmNotAvailable(); return true; } } return false; }
public boolean pickAndExecuteAnAction() { System.out.println(this + " Scheduler with state = " +myState + " target = " + target); if (currentGlass != null && target == Target.None && myState == State.Up) { if (firstMachine.state == MachineState.Idle) { target = Target.Machine1; passToMachine(firstMachine); return true; } else if (secondMachine.state == MachineState.Idle){ target = Target.Machine2; passToMachine(secondMachine); return true; } } if (currentGlass == null && target == Target.None && myState == State.Down) { if (firstMachine.state == MachineState.Done) { target = Target.Machine1; popUp(); // pop up to say ready return true; } else if (secondMachine.state == MachineState.Done) { target = Target.Machine2; popUp(); // pop up to say ready return true; } else if (!informed && (firstMachine.state == MachineState.Idle || secondMachine.state == MachineState.Idle)){ informIAmAvailable(); return true; } else if (!informed) { informOkToSkip(); return true; } } if (currentGlass != null && target == Target.None && myState == State.Down && glassLoaded) { if (currentGlass.getConfig(myGuiIndex)) { target = Target.None; popUp(); // pop up to give to machine return true; } } if (currentGlass == null && myState == State.Up) { if (target == Target.None) { popDown(); } else if (target == Target.Machine1) { sayReady(firstMachine); } else if (target == Target.Machine2) { sayReady(secondMachine); } return true; } if (currentGlass !=null && myState == State.Up && target == Target.PostConveyor) { popDown(); return true; } if (currentGlass !=null && myState == State.Down && glassLoaded) { if (postConveyor.state == ConveyorState.Available) { passToConveyor(); return true; } else if (!informed){ preConveyor.conveyor.msgIAmNotAvailable(); informed = true; return true; } } return false; }
diff --git a/src/rabbitmish/coloringchickens/MainThread.java b/src/rabbitmish/coloringchickens/MainThread.java index 5a0a720..952d208 100644 --- a/src/rabbitmish/coloringchickens/MainThread.java +++ b/src/rabbitmish/coloringchickens/MainThread.java @@ -1,89 +1,91 @@ /* -*- mode:java; coding:utf-8; -*- Time-stamp: <MainThread.java - root> */ package rabbitmish.coloringchickens; import android.graphics.Canvas; import android.view.SurfaceHolder; public class MainThread extends Thread { private final static int FRAME_DURATION = 1000 / 25 /* frames per second */; private boolean _running; private SurfaceHolder _surface_holder; private MainView _view; private void draw() { Canvas canvas = null; try { canvas = _surface_holder.lockCanvas(); synchronized (_surface_holder) { _view.render(canvas); } } finally { if (canvas != null) { _surface_holder.unlockCanvasAndPost(canvas); } } } public MainThread(SurfaceHolder h, MainView v) { super(); _surface_holder = h; _view = v; } @Override public void run() { final long start_time = System.currentTimeMillis(); long skip_interval = 0; while (_running) { - final long frame_time = (start_time + (System.currentTimeMillis() - start_time) / FRAME_DURATION * FRAME_DURATION + skip_interval); + final long frame_time = (start_time + + (System.currentTimeMillis() - start_time) / FRAME_DURATION * FRAME_DURATION + + skip_interval); _view.update(); if (System.currentTimeMillis() > frame_time) { draw(); final long delta = frame_time + FRAME_DURATION - System.currentTimeMillis(); if (delta < 0) { skip_interval = FRAME_DURATION; } else { try { Thread.sleep(delta); } catch (InterruptedException e) { // ignore } skip_interval = 0; } } } } public void setRunning(boolean running) { _running = running; } }
true
true
public void run() { final long start_time = System.currentTimeMillis(); long skip_interval = 0; while (_running) { final long frame_time = (start_time + (System.currentTimeMillis() - start_time) / FRAME_DURATION * FRAME_DURATION + skip_interval); _view.update(); if (System.currentTimeMillis() > frame_time) { draw(); final long delta = frame_time + FRAME_DURATION - System.currentTimeMillis(); if (delta < 0) { skip_interval = FRAME_DURATION; } else { try { Thread.sleep(delta); } catch (InterruptedException e) { // ignore } skip_interval = 0; } } } }
public void run() { final long start_time = System.currentTimeMillis(); long skip_interval = 0; while (_running) { final long frame_time = (start_time + (System.currentTimeMillis() - start_time) / FRAME_DURATION * FRAME_DURATION + skip_interval); _view.update(); if (System.currentTimeMillis() > frame_time) { draw(); final long delta = frame_time + FRAME_DURATION - System.currentTimeMillis(); if (delta < 0) { skip_interval = FRAME_DURATION; } else { try { Thread.sleep(delta); } catch (InterruptedException e) { // ignore } skip_interval = 0; } } } }
diff --git a/src/main/java/hudson/plugins/blazemeter/api/BlazemeterApi.java b/src/main/java/hudson/plugins/blazemeter/api/BlazemeterApi.java index 2d55742..f74ce59 100644 --- a/src/main/java/hudson/plugins/blazemeter/api/BlazemeterApi.java +++ b/src/main/java/hudson/plugins/blazemeter/api/BlazemeterApi.java @@ -1,636 +1,636 @@ package hudson.plugins.blazemeter.api; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.sun.mail.util.LineOutputStream; import java.io.*; import java.net.URLEncoder; import java.util.ArrayList; import javax.mail.MessagingException; /** * User: Vitali * Date: 4/2/12 * Time: 14:05 * <p/> * Updated - Platform independent * User: moshe * Date: 5/12/12 * Time: 1:05 PM * <p/> * Updated - Minor fixes * User: Doron * Date: 8/7/12 */ public class BlazemeterApi { PrintStream logger = new PrintStream(System.out); public class TestStatus { public static final String Running = "Running"; public static final String NotRunning = "Not Running"; public static final String NotFound = "NotFound"; public static final String Error = "error"; } public static final String APP_KEY = "jnk100x987c06f4e10c4"; DefaultHttpClient httpClient; BmUrlManager urlManager; public BlazemeterApi(String blazeMeterUrl) { urlManager = new BmUrlManager(blazeMeterUrl); try { //logger = new PrintStream(new FileOutputStream("/Users/moshe/tests/jenkins.log")); httpClient = new DefaultHttpClient(); } catch (Exception ex) { logger.format("error Instantiating HTTPClient. Exception received: %s", ex); } } private HttpResponse getResponse(String url, JSONObject data) throws IOException { logger.println("Requesting : " + url); HttpPost postRequest = new HttpPost(url); postRequest.setHeader("Accept", "application/json"); postRequest.setHeader("Content-type", "application/json; charset=UTF-8"); if (data != null) { postRequest.setEntity(new StringEntity(data.toString())); } HttpResponse response = null; try { response = this.httpClient.execute(postRequest); int statusCode = response.getStatusLine().getStatusCode(); String error = response.getStatusLine().getReasonPhrase(); if ((statusCode >= 300) || (statusCode < 200)) { throw new RuntimeException(String.format("Failed : %d %s", statusCode, error)); } } catch (Exception e) { System.err.format("Wrong response: %s", e); } return response; } private JSONObject getJson(String url, JSONObject data) { JSONObject jo = null; try { HttpResponse response = getResponse(url, data); if (response != null) { String output = EntityUtils.toString(response.getEntity()); logger.println(output); jo = new JSONObject(output); } } catch (IOException e) { logger.println("error decoding Json " + e); } catch (JSONException e) { logger.println("error decoding Json " + e); } return jo; } // public synchronized void getReports(String userKey, String id) throws IOException, JSONException { // String url = this.urlManager.testReport(APP_KEY, userKey, id); // // JSONObject jo = getJson(url, null); // ArrayList<JSONObject> arr = (ArrayList<JSONObject>) jo.get("reports"); // HashMap<String, String> rpt = new HashMap<String, String>(); // // for (JSONObject en : arr) { // String zipurl = (String) en.get("zip_url"); // String date = (String) en.get("date"); // String test_url = (String) en.get("url"); // String title = (String) en.get("title"); // // if (rpt.containsKey(id)) { // rpt.put("title", title); // rpt.put("date", date); // rpt.put("url", url); // rpt.put("zipurl", zipurl); // } // // System.out.format("zip URL " + zipurl); // System.out.format("Date of Test Run " + date); // System.out.format("URL For Test" + test_url); // System.out.format("Title" + title); // } // } // public interface TestContainerNotifier { // public void testReceived(ArrayList<TestInfo> tests); // } // public synchronized void getTestsAsync(String userKey, TestContainerNotifier notifier) { // class TestsFetcher implements Runnable { // String userKey; // TestContainerNotifier notifier; // // TestsFetcher(String userKey, TestContainerNotifier notifier) { // this.userKey = userKey; // this.notifier = notifier; // } // // public void run() { // ArrayList<TestInfo> tests = getTests(userKey); // notifier.testReceived(tests); // } // } // new Thread(new TestsFetcher(userKey, notifier)).start(); // } // public synchronized ArrayList<TestInfo> getTests(String userKey) { // if (userKey.trim().isEmpty()) { // logger.println("getTests userKey is empty"); // return null; // } // // String url = this.urlManager.getTests(APP_KEY, userKey, "all"); // // JSONObject jo = getJson(url, null); // JSONArray arr; // try { // String r = jo.get("response_code").toString(); // if (!r.equals("200")) // return null; // arr = (JSONArray) jo.get("tests"); // } catch (JSONException e) { // return null; // } // // // ArrayList<TestInfo> tests = new ArrayList<TestInfo>(); // for (int i = 0; i < arr.length(); i++) { // JSONObject en; // try { // en = arr.getJSONObject(i); // } catch (JSONException e) { // System.err.format(e.getMessage()); // continue; // } // String id = null; // String name = null; // try { // id = en.getString("test_id"); // name = en.getString("test_name"); // } catch (JSONException ignored) { // } // TestInfo testInfo = new TestInfo(); // testInfo.name = name; // testInfo.id = id; // tests.add(testInfo); // } // return tests; // } // public synchronized TestInfo createTest(String userKey, String testName) { // if (userKey == null || userKey.trim().isEmpty()) { // logger.println("createTest userKey is empty"); // return null; // } // // String url = this.urlManager.scriptCreation(APP_KEY, userKey, testName); // JSONObject jo = getJson(url, null); // TestInfo ti = new TestInfo(); // try { // if (jo.isNull("error")) { // ti.id = jo.getString("test_id"); // ti.name = jo.getString("test_name"); // } else { // ti.status = jo.getString("error"); // } // } catch (JSONException e) { // ti.status = "error"; // } // return ti; // } // public synchronized JSONObject getTestReport(String userKey, String session) { // if (userKey == null || userKey.trim().isEmpty()) { // logger.println("createTest userKey is empty"); // return null; // } // // String url = this.urlManager.testReport(APP_KEY, userKey, session); // JSONObject jo = getJson(url, null); // return jo; // } /** * @param userKey - user key * @param testId - test id * @param fileName - test name * @param pathName - jmx file path // * @return test id // * @throws java.io.IOException // * @throws org.json.JSONException */ public synchronized void uploadJmx(String userKey, String testId, String fileName, String pathName) { if (!validate(userKey, testId)) return; String url = this.urlManager.scriptUpload(APP_KEY, userKey, testId, fileName); JSONObject jmxData = new JSONObject(); String fileCon = getFileContents(pathName); try { jmxData.put("data", fileCon); } catch (JSONException e) { System.err.format(e.getMessage()); } getJson(url, jmxData); } /** * * @param userKey - user key * @param testId - test id * @param fileName - name for file you like to upload * @param pathName - to the file you like to upload * @return test id // * @throws java.io.IOException // * @throws org.json.JSONException */ public synchronized JSONObject uploadFile(String userKey, String testId, String fileName, String pathName) { if (!validate(userKey, testId)) return null; String url = this.urlManager.fileUpload(APP_KEY, userKey, testId, fileName); JSONObject jmxData = new JSONObject(); String fileCon = getFileContents(pathName); try { jmxData.put("data", fileCon); } catch (JSONException e) { System.err.format(e.getMessage()); } return getJson(url, jmxData); } private String getFileContents(String fn) { // ...checks on aFile are elided StringBuilder contents = new StringBuilder(); File aFile = new File(fn); try { // use buffering, reading one line at a time // FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line; // not declared within while loop /* * readLine is a bit quirky : it returns the content of a line * MINUS the newline. it returns null only for the END of the * stream. it returns an empty String if two newlines appear in * a row. */ while ((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ignored) { } return contents.toString(); } // public synchronized int dataUpload(String userKey, String testId, String reportName, String buff, String dataType) { // // if (!validate(userKey, testId)) return -1; // // Integer fileSize = -1; // // reportName = reportName.trim().isEmpty() ? "sample" : reportName; // if (dataType.equals("jtl")) // reportName = reportName.toLowerCase().endsWith(".jtl") ? reportName : reportName + ".jtl"; // // String url = this.urlManager.testResultsJTLUpload(APP_KEY, userKey, testId, reportName, dataType); // // JSONObject obj = new JSONObject(); // try { // obj.put("data", buff); // JSONObject jo = getJson(url, obj); // fileSize = (Integer) jo.get("file_size"); // // } catch (JSONException e) { // System.err.format(e.getMessage()); // } // return fileSize; // } public TestInfo getTestRunStatus(String userKey, String testId) { TestInfo ti = new TestInfo(); if (!validate(userKey, testId)) { ti.status = TestStatus.NotFound; return ti; } try { String url = this.urlManager.testStatus(APP_KEY, userKey, testId); JSONObject jo = getJson(url, null); if (jo.get("status") == "Test not found") ti.status = TestStatus.NotFound; else { ti.id = jo.getString("test_id"); ti.name = jo.getString("test_name"); ti.status = jo.getString("status"); } } catch (Exception e) { logger.println("error getting status " + e); ti.status = TestStatus.Error; } return ti; } public synchronized JSONObject startTest(String userKey, String testId) { if (!validate(userKey, testId)) return null; String url = this.urlManager.testStart(APP_KEY, userKey, testId); return getJson(url, null); } public synchronized ArrayList<TestInfo> getTests(String userKey) throws JSONException, IOException { if (userKey.trim().isEmpty()) { logger.println("getTests userKey is empty"); return null; } String url =getUrlForTestList(APP_KEY, userKey); JSONObject jo = getJson(url, null); JSONArray arr; try { String r = jo.get("response_code").toString(); if (!r.equals("200")) return null; arr = (JSONArray) jo.get("tests"); } catch (JSONException e) { return null; } - FileOutputStream fc = new FileOutputStream("testList.jelly"); + FileOutputStream fc = new FileOutputStream("src/main/resources/hudson/plugins/blazemeter/PerformancePublisher/testList.jelly"); LineOutputStream li = new LineOutputStream(fc); try { li.writeln("<j:jelly xmlns:j=\"jelly:core\" xmlns:st=\"jelly:stapler\" xmlns:d=\"jelly:define\" " + "xmlns:l=\"/lib/layout\" xmlns:t=\"/lib/hudson\" xmlns:f=\"/lib/form\" xmlns:x=\"jelly:xml\" xmlns:html=\"jelly:html\">"+ "<f:entry name=\"testList\" title=\"Choose Test from List\" field=\"tests\">" + "<select name=\"testId\">" ); } catch (MessagingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<TestInfo> testList = new ArrayList<TestInfo>(); for (int i = 0; i < arr.length(); i++) { JSONObject en; try { en = arr.getJSONObject(i); } catch (JSONException e) { System.err.format(e.getMessage()); continue; } String id = null; String name = null; try { id = en.getString("test_id"); name = en.getString("test_name"); } catch (JSONException ignored) { } TestInfo testInfo = new TestInfo(); testInfo.name = name; testInfo.id = id; try { li.writeln("<option value=\"" + id + "\">" + name + "</option>"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } testList.add(testInfo); } try { li.writeln("</select></f:entry></j:jelly>"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } li.close(); return testList; } private String getUrlForTestList(String appKey, String userKey) { // TODO Auto-generated method stub try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return String.format("https://a.blazemeter.com/api/rest/blazemeter/getTests.json/?app_key=%s&user_key=%s&test_id=all", appKey, userKey); } private boolean validate(String userKey, String testId) { if (userKey == null || userKey.trim().isEmpty()) { logger.println("startTest userKey is empty"); return false; } if (testId == null || testId.trim().isEmpty()) { logger.println("testId is empty"); return false; } return true; } /** * * @param userKey - user key * @param testId - test id // * @throws IOException // * @throws ClientProtocolException */ public JSONObject stopTest(String userKey, String testId) { if (!validate(userKey, testId)) return null; String url = this.urlManager.testStop(APP_KEY, userKey, testId); return getJson(url, null); } /** * * @param userKey - user key * @param reportId - report Id same as Session Id, can be obtained from start stop status. // * @throws IOException // * @throws ClientProtocolException */ public JSONObject aggregateReport(String userKey, String reportId) { if (!validate(userKey, reportId)) return null; String url = this.urlManager.testAggregateReport(APP_KEY, userKey, reportId); return getJson(url, null); } public static class BmUrlManager { private String SERVER_URL; // public BmUrlManager() { // this("https://a.blazemeter.com"); // } public BmUrlManager(String blazeMeterUrl) { SERVER_URL = blazeMeterUrl; //logger.println("Server url is :" + SERVER_URL); } // public String getServerUrl() { // return SERVER_URL; // } public String testStatus(String appKey, String userKey, String testId) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testId = URLEncoder.encode(testId, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return String.format("%s/api/rest/blazemeter/testGetStatus.json/?app_key=%s&user_key=%s&test_id=%s", SERVER_URL, appKey, userKey, testId); } // public String scriptCreation(String appKey, String userKey, String testName) { // try { // appKey = URLEncoder.encode(appKey, "UTF-8"); // userKey = URLEncoder.encode(userKey, "UTF-8"); // testName = URLEncoder.encode(testName, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return String.format("%s/api/rest/blazemeter/testCreate.json/?app_key=%s&user_key=%s&test_name=%s", SERVER_URL, appKey, userKey, testName); // } public String scriptUpload(String appKey, String userKey, String testId, String fileName) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testId = URLEncoder.encode(testId, "UTF-8"); fileName = URLEncoder.encode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return String.format("%s/api/rest/blazemeter/testScriptUpload.json/?app_key=%s&user_key=%s&test_id=%s&file_name=%s", SERVER_URL, appKey, userKey, testId, fileName); } public String fileUpload(String appKey, String userKey, String testId, String fileName) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testId = URLEncoder.encode(testId, "UTF-8"); fileName = URLEncoder.encode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return String.format("%s/api/rest/blazemeter/testArtifactUpload.json/?app_key=%s&user_key=%s&test_id=%s&file_name=%s", SERVER_URL, appKey, userKey, testId, fileName); } public String testStart(String appKey, String userKey, String testId) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testId = URLEncoder.encode(testId, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return String.format("%s/api/rest/blazemeter/testStart.json/?app_key=%s&user_key=%s&test_id=%s", SERVER_URL, appKey, userKey, testId); } public String testStop(String appKey, String userKey, String testId) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testId = URLEncoder.encode(testId, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return String.format("%s/api/rest/blazemeter/testStop.json/?app_key=%s&user_key=%s&test_id=%s", SERVER_URL, appKey, userKey, testId); } // public String testReport(String appKey, String userKey, String reportId) { // try { // appKey = URLEncoder.encode(appKey, "UTF-8"); // userKey = URLEncoder.encode(userKey, "UTF-8"); // reportId = URLEncoder.encode(reportId, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return String.format("%s/api/rest/blazemeter/testGetArchive.json/?app_key=%s&user_key=%s&report_id=%s", SERVER_URL, appKey, userKey, reportId); // } // public String testResultsJTLUpload(String appKey, String userKey, String testId, String fileName, String dataType) { // try { // appKey = URLEncoder.encode(appKey, "UTF-8"); // userKey = URLEncoder.encode(userKey, "UTF-8"); // testId = URLEncoder.encode(testId, "UTF-8"); // fileName = URLEncoder.encode(fileName, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return String.format("%s/api/rest/blazemeter/testDataUpload.json/?app_key=%s&user_key=%s&test_id=%s&file_name=%s&data_type=%s", SERVER_URL, appKey, userKey, testId, fileName, dataType); // } // public String getTests(String appKey, String userKey, String type) { // try { // appKey = URLEncoder.encode(appKey, "UTF-8"); // userKey = URLEncoder.encode(userKey, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // return String.format("%s/api/rest/blazemeter/getTests.json/?app_key=%s&user_key=%s&type=%s", SERVER_URL, appKey, userKey, type); // } public String testAggregateReport(String appKey, String userKey, String reportId) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); reportId = URLEncoder.encode(reportId, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return String.format("%s/api/rest/blazemeter/testGetReport.json/?app_key=%s&user_key=%s&report_id=%s&get_aggregate=true", SERVER_URL, appKey, userKey, reportId); } } }
true
true
public synchronized ArrayList<TestInfo> getTests(String userKey) throws JSONException, IOException { if (userKey.trim().isEmpty()) { logger.println("getTests userKey is empty"); return null; } String url =getUrlForTestList(APP_KEY, userKey); JSONObject jo = getJson(url, null); JSONArray arr; try { String r = jo.get("response_code").toString(); if (!r.equals("200")) return null; arr = (JSONArray) jo.get("tests"); } catch (JSONException e) { return null; } FileOutputStream fc = new FileOutputStream("testList.jelly"); LineOutputStream li = new LineOutputStream(fc); try { li.writeln("<j:jelly xmlns:j=\"jelly:core\" xmlns:st=\"jelly:stapler\" xmlns:d=\"jelly:define\" " + "xmlns:l=\"/lib/layout\" xmlns:t=\"/lib/hudson\" xmlns:f=\"/lib/form\" xmlns:x=\"jelly:xml\" xmlns:html=\"jelly:html\">"+ "<f:entry name=\"testList\" title=\"Choose Test from List\" field=\"tests\">" + "<select name=\"testId\">" ); } catch (MessagingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<TestInfo> testList = new ArrayList<TestInfo>(); for (int i = 0; i < arr.length(); i++) { JSONObject en; try { en = arr.getJSONObject(i); } catch (JSONException e) { System.err.format(e.getMessage()); continue; } String id = null; String name = null; try { id = en.getString("test_id"); name = en.getString("test_name"); } catch (JSONException ignored) { } TestInfo testInfo = new TestInfo(); testInfo.name = name; testInfo.id = id; try { li.writeln("<option value=\"" + id + "\">" + name + "</option>"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } testList.add(testInfo); } try { li.writeln("</select></f:entry></j:jelly>"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } li.close(); return testList; }
public synchronized ArrayList<TestInfo> getTests(String userKey) throws JSONException, IOException { if (userKey.trim().isEmpty()) { logger.println("getTests userKey is empty"); return null; } String url =getUrlForTestList(APP_KEY, userKey); JSONObject jo = getJson(url, null); JSONArray arr; try { String r = jo.get("response_code").toString(); if (!r.equals("200")) return null; arr = (JSONArray) jo.get("tests"); } catch (JSONException e) { return null; } FileOutputStream fc = new FileOutputStream("src/main/resources/hudson/plugins/blazemeter/PerformancePublisher/testList.jelly"); LineOutputStream li = new LineOutputStream(fc); try { li.writeln("<j:jelly xmlns:j=\"jelly:core\" xmlns:st=\"jelly:stapler\" xmlns:d=\"jelly:define\" " + "xmlns:l=\"/lib/layout\" xmlns:t=\"/lib/hudson\" xmlns:f=\"/lib/form\" xmlns:x=\"jelly:xml\" xmlns:html=\"jelly:html\">"+ "<f:entry name=\"testList\" title=\"Choose Test from List\" field=\"tests\">" + "<select name=\"testId\">" ); } catch (MessagingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<TestInfo> testList = new ArrayList<TestInfo>(); for (int i = 0; i < arr.length(); i++) { JSONObject en; try { en = arr.getJSONObject(i); } catch (JSONException e) { System.err.format(e.getMessage()); continue; } String id = null; String name = null; try { id = en.getString("test_id"); name = en.getString("test_name"); } catch (JSONException ignored) { } TestInfo testInfo = new TestInfo(); testInfo.name = name; testInfo.id = id; try { li.writeln("<option value=\"" + id + "\">" + name + "</option>"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } testList.add(testInfo); } try { li.writeln("</select></f:entry></j:jelly>"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } li.close(); return testList; }
diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/InterventionView.java b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/InterventionView.java index 2ea75823..9b066d08 100644 --- a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/InterventionView.java +++ b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/InterventionView.java @@ -1,791 +1,788 @@ package ch.cern.atlas.apvs.client.ui; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.cern.atlas.apvs.client.ClientFactory; import ch.cern.atlas.apvs.client.domain.Device; import ch.cern.atlas.apvs.client.domain.Intervention; import ch.cern.atlas.apvs.client.domain.User; import ch.cern.atlas.apvs.client.event.SelectTabEvent; import ch.cern.atlas.apvs.client.service.InterventionServiceAsync; import ch.cern.atlas.apvs.client.service.SortOrder; import ch.cern.atlas.apvs.client.validation.EmptyValidator; import ch.cern.atlas.apvs.client.validation.ValidationFieldset; import ch.cern.atlas.apvs.client.validation.IntegerValidator; import ch.cern.atlas.apvs.client.validation.ListBoxField; import ch.cern.atlas.apvs.client.validation.NotNullValidator; import ch.cern.atlas.apvs.client.validation.OrValidator; import ch.cern.atlas.apvs.client.validation.StringValidator; import ch.cern.atlas.apvs.client.validation.TextAreaField; import ch.cern.atlas.apvs.client.validation.TextBoxField; import ch.cern.atlas.apvs.client.validation.ValidationForm; import ch.cern.atlas.apvs.client.widget.ClickableHtmlColumn; import ch.cern.atlas.apvs.client.widget.ClickableTextColumn; import ch.cern.atlas.apvs.client.widget.DataStoreName; import ch.cern.atlas.apvs.client.widget.EditTextColumn; import ch.cern.atlas.apvs.client.widget.EditableCell; import ch.cern.atlas.apvs.client.widget.GenericColumn; import ch.cern.atlas.apvs.client.widget.HumanTime; import ch.cern.atlas.apvs.client.widget.ScrolledDataGrid; import ch.cern.atlas.apvs.client.widget.UpdateScheduler; import ch.cern.atlas.apvs.ptu.shared.PtuClientConstants; import com.github.gwtbootstrap.client.ui.Button; import com.github.gwtbootstrap.client.ui.Label; import com.github.gwtbootstrap.client.ui.Modal; import com.github.gwtbootstrap.client.ui.ModalFooter; import com.github.gwtbootstrap.client.ui.constants.ButtonType; import com.github.gwtbootstrap.client.ui.constants.FormType; import com.google.gwt.cell.client.ButtonCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.cell.client.TextCell; import com.google.gwt.cell.client.ValueUpdater; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.ScrollEvent; import com.google.gwt.event.dom.client.ScrollHandler; import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler; import com.google.gwt.user.cellview.client.ColumnSortList; import com.google.gwt.user.cellview.client.ColumnSortList.ColumnSortInfo; import com.google.gwt.user.cellview.client.Header; import com.google.gwt.user.cellview.client.SimplePager; import com.google.gwt.user.cellview.client.SimplePager.TextLocation; import com.google.gwt.user.cellview.client.TextHeader; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.validation.client.Validation; import com.google.gwt.view.client.AsyncDataProvider; import com.google.gwt.view.client.HasData; import com.google.gwt.view.client.Range; import com.google.gwt.view.client.RangeChangeEvent; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; import com.google.web.bindery.event.shared.EventBus; public class InterventionView extends DockPanel implements Module { private Logger log = LoggerFactory.getLogger(getClass().getName()); private ScrolledDataGrid<Intervention> table = new ScrolledDataGrid<Intervention>(); private ScrollPanel scrollPanel; private ClickableTextColumn<Intervention> startTime; private boolean selectable = false; private boolean sortable = true; private final String END_INTERVENTION = "End Intervention"; private InterventionServiceAsync interventionService; private Validator validator; private UpdateScheduler scheduler = new UpdateScheduler(this); private HorizontalPanel footer = new HorizontalPanel(); private SimplePager pager; private Button update; private boolean showUpdate; public InterventionView() { interventionService = InterventionServiceAsync.Util.getInstance(); validator = Validation.buildDefaultValidatorFactory().getValidator(); } @Override public boolean configure(Element element, ClientFactory clientFactory, Arguments args) { String height = args.getArg(0); EventBus eventBus = clientFactory.getEventBus(args.getArg(1)); table.setSize("100%", height); table.setEmptyTableWidget(new Label("No Interventions")); pager = new SimplePager(TextLocation.RIGHT); footer.add(pager); pager.setDisplay(table); update = new Button("Update"); update.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { pager.setPage(0); scrollPanel.setVerticalScrollPosition(scrollPanel .getMinimumHorizontalScrollPosition()); table.getColumnSortList().push(new ColumnSortInfo(startTime, false)); scheduler.update(); } }); update.setVisible(false); footer.add(update); setWidth("100%"); add(table, CENTER); scrollPanel = table.getScrollPanel(); scrollPanel.addScrollHandler(new ScrollHandler() { @Override public void onScroll(ScrollEvent event) { if (scrollPanel.getVerticalScrollPosition() == scrollPanel .getMinimumVerticalScrollPosition()) { scheduler.update(); } } }); AsyncDataProvider<Intervention> dataProvider = new AsyncDataProvider<Intervention>() { @Override protected void onRangeChanged(HasData<Intervention> display) { log.info("ON RANGE CHANGED " + display.getVisibleRange()); interventionService.getRowCount(new AsyncCallback<Integer>() { @Override public void onSuccess(Integer result) { updateRowCount(result, true); } @Override public void onFailure(Throwable caught) { updateRowCount(0, true); } }); final Range range = display.getVisibleRange(); final ColumnSortList sortList = table.getColumnSortList(); SortOrder[] order = new SortOrder[sortList.size()]; for (int i = 0; i < sortList.size(); i++) { ColumnSortInfo info = sortList.get(i); // FIXME #88 remove cast order[i] = new SortOrder( ((DataStoreName) info.getColumn()) .getDataStoreName(), info.isAscending()); } if (order.length == 0) { order = new SortOrder[1]; order[0] = new SortOrder("tbl_inspections.starttime", false); } interventionService.getTableData(range, order, new AsyncCallback<List<Intervention>>() { @Override public void onSuccess(List<Intervention> result) { updateRowData(range.getStart(), result); } @Override public void onFailure(Throwable caught) { log.warn("RPC DB FAILED " + caught); updateRowCount(0, true); } }); } }; // Table dataProvider.addDataDisplay(table); AsyncHandler columnSortHandler = new AsyncHandler(table); table.addColumnSortHandler(columnSortHandler); // startTime startTime = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return PtuClientConstants.dateFormatNoSeconds.format(object .getStartTime()); } @Override public String getDataStoreName() { return "tbl_inspections.starttime"; } }; startTime.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); startTime.setSortable(sortable); if (selectable) { startTime.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> interventionFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Start a new Intervention"; } }; interventionFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final ListBoxField userField = new ListBoxField("User", new NotNullValidator()); fieldset.add(userField); interventionService.getUsers(true, new AsyncCallback<List<User>>() { @Override public void onSuccess(List<User> result) { for (Iterator<User> i = result.iterator(); i .hasNext();) { User user = i.next(); userField.addItem(user.getDisplayName(), user.getId()); } } @Override public void onFailure(Throwable caught) { log.warn("Caught : " + caught); } }); final ListBoxField ptu = new ListBoxField("PTU", new NotNullValidator()); fieldset.add(ptu); interventionService.getDevices(true, new AsyncCallback<List<Device>>() { @Override public void onSuccess(List<Device> result) { for (Iterator<Device> i = result.iterator(); i .hasNext();) { Device device = i.next(); ptu.addItem(device.getName(), device.getId()); } } @Override public void onFailure(Throwable caught) { log.warn("Caught : " + caught); } }); final TextAreaField description = new TextAreaField( "Description"); fieldset.add(description); final Modal m = new Modal(); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); Button ok = new Button("Ok"); - ok.setType(ButtonType.PRIMARY); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); Intervention intervention = new Intervention(userField .getId(), ptu.getId(), new Date(), description .getValue()); // FIXME #194 Set<ConstraintViolation<Intervention>> violations = validator .validate(intervention); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<Intervention> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addIntervention(intervention, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed"); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Start a new Intervention"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(startTime, new TextHeader("Start Time"), interventionFooter); table.getColumnSortList().push(new ColumnSortInfo(startTime, false)); // endTime EditableCell cell = new EditableCell() { @Override protected Class<? extends Cell<? extends Object>> getCellClass( Context context, Object value) { return value == END_INTERVENTION ? ButtonCell.class : TextCell.class; } }; Column<Intervention, Object> endTime = new GenericColumn<Intervention>( cell) { @Override public String getValue(Intervention object) { return object.getEndTime() != null ? PtuClientConstants.dateFormatNoSeconds .format(object.getEndTime()) : END_INTERVENTION; } @Override public String getDataStoreName() { return "tbl_inspections.starttime"; } }; endTime.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); endTime.setSortable(sortable); endTime.setFieldUpdater(new FieldUpdater<Intervention, Object>() { @Override public void update(int index, Intervention object, Object value) { if (Window.confirm("Are you sure")) { interventionService.endIntervention(object.getId(), new Date(), new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); table.addColumn(endTime, new TextHeader("End Time"), new TextHeader("")); ClickableTextColumn<Intervention> duration = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { long d = object.getEndTime() == null ? new Date().getTime() : object.getEndTime().getTime(); d = d - object.getStartTime().getTime(); return HumanTime.upToMins(d); } }; duration.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); duration.setSortable(false); if (selectable) { duration.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } table.addColumn(duration, new TextHeader("Duration"), new TextHeader("")); // Name ClickableHtmlColumn<Intervention> name = new ClickableHtmlColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getName(); } @Override public String getDataStoreName() { return "tbl_users.lname"; } }; name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); name.setSortable(sortable); if (selectable) { name.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> nameFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Add a new User"; } }; nameFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final TextBoxField fname = new TextBoxField("First Name", new StringValidator(1, 50)); fieldset.add(fname); final TextBoxField lname = new TextBoxField("Last Name", new StringValidator(4, 50)); fieldset.add(lname); final TextBoxField cernId = new TextBoxField("CERN ID", new OrValidator(new EmptyValidator(), new IntegerValidator())); fieldset.add(cernId); final Modal m = new Modal(); final Button cancel = new Button("Cancel"); - cancel.setType(ButtonType.PRIMARY); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); final Button ok = new Button("Ok"); ok.setEnabled(false); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); User user = new User(0, fname.getValue(), lname .getValue(), cernId.getValue()); // FIXME #194 Set<ConstraintViolation<User>> violations = validator .validate(user); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<User> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addUser(user, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Add a new User"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(name, new TextHeader("Name"), nameFooter); // PtuID ClickableTextColumn<Intervention> ptu = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getPtuId(); } @Override public String getDataStoreName() { return "tbl_devices.name"; } }; ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); ptu.setSortable(sortable); if (selectable) { ptu.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> deviceFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Add a new PTU"; } }; deviceFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final TextBoxField ptuId = new TextBoxField("PTU ID", new StringValidator(2, 20)); fieldset.add(ptuId); final TextBoxField ip = new TextBoxField("IP"); fieldset.add(ip); final TextAreaField description = new TextAreaField( "Description"); fieldset.add(description); final Modal m = new Modal(); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); Button ok = new Button("Ok"); - ok.setType(ButtonType.PRIMARY); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); Device device = new Device(0, ptuId.getValue(), ip .getValue(), description.getValue()); // FIXME #194 Set<ConstraintViolation<Device>> violations = validator .validate(device); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<Device> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addDevice(device, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Add a new PTU"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(ptu, new TextHeader("PTU ID"), deviceFooter); // Description EditTextColumn<Intervention> description = new EditTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getDescription() != null ? object .getDescription() : ""; } @Override public String getDataStoreName() { return "tbl_inspections.dscr"; } }; description.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); description.setSortable(true); description.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { interventionService.updateInterventionDescription( object.getId(), value, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } }); table.addColumn(description, new TextHeader("Description"), new TextHeader("")); // Selection if (selectable) { final SingleSelectionModel<Intervention> selectionModel = new SingleSelectionModel<Intervention>(); table.setSelectionModel(selectionModel); selectionModel .addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { Intervention m = selectionModel.getSelectedObject(); log.info(m + " " + event.getSource()); } }); } // FIXME #189 this is the normal way, but does not work in our tabs... // tabs should detach, attach... addAttachHandler(new AttachEvent.Handler() { private Timer timer; @Override public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { // refresh for duration timer = new Timer() { @Override public void run() { table.redraw(); } }; timer.scheduleRepeating(60000); } else { if (timer != null) { timer.cancel(); timer = null; } } } }); // FIXME #189 so we handle it with events SelectTabEvent.subscribe(eventBus, new SelectTabEvent.Handler() { @Override public void onTabSelected(SelectTabEvent event) { if (event.getTab().equals("Interventions")) { showUpdate = true; table.redraw(); } } }); return true; } private void selectIntervention(Intervention intervention) { } private boolean needsUpdate() { if (showUpdate) { ColumnSortList sortList = table.getColumnSortList(); ColumnSortInfo sortInfo = sortList.size() > 0 ? sortList.get(0) : null; if (sortInfo == null) { return true; } if (!sortInfo.getColumn().equals(startTime)) { return true; } if (sortInfo.isAscending()) { return true; } showUpdate = (scrollPanel.getVerticalScrollPosition() != scrollPanel .getMinimumVerticalScrollPosition()) || (pager.getPage() != pager.getPageStart()); return showUpdate; } return false; } @Override public boolean update() { // show or hide update button update.setVisible(needsUpdate()); RangeChangeEvent.fire(table, table.getVisibleRange()); table.redraw(); return false; } }
false
true
public boolean configure(Element element, ClientFactory clientFactory, Arguments args) { String height = args.getArg(0); EventBus eventBus = clientFactory.getEventBus(args.getArg(1)); table.setSize("100%", height); table.setEmptyTableWidget(new Label("No Interventions")); pager = new SimplePager(TextLocation.RIGHT); footer.add(pager); pager.setDisplay(table); update = new Button("Update"); update.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { pager.setPage(0); scrollPanel.setVerticalScrollPosition(scrollPanel .getMinimumHorizontalScrollPosition()); table.getColumnSortList().push(new ColumnSortInfo(startTime, false)); scheduler.update(); } }); update.setVisible(false); footer.add(update); setWidth("100%"); add(table, CENTER); scrollPanel = table.getScrollPanel(); scrollPanel.addScrollHandler(new ScrollHandler() { @Override public void onScroll(ScrollEvent event) { if (scrollPanel.getVerticalScrollPosition() == scrollPanel .getMinimumVerticalScrollPosition()) { scheduler.update(); } } }); AsyncDataProvider<Intervention> dataProvider = new AsyncDataProvider<Intervention>() { @Override protected void onRangeChanged(HasData<Intervention> display) { log.info("ON RANGE CHANGED " + display.getVisibleRange()); interventionService.getRowCount(new AsyncCallback<Integer>() { @Override public void onSuccess(Integer result) { updateRowCount(result, true); } @Override public void onFailure(Throwable caught) { updateRowCount(0, true); } }); final Range range = display.getVisibleRange(); final ColumnSortList sortList = table.getColumnSortList(); SortOrder[] order = new SortOrder[sortList.size()]; for (int i = 0; i < sortList.size(); i++) { ColumnSortInfo info = sortList.get(i); // FIXME #88 remove cast order[i] = new SortOrder( ((DataStoreName) info.getColumn()) .getDataStoreName(), info.isAscending()); } if (order.length == 0) { order = new SortOrder[1]; order[0] = new SortOrder("tbl_inspections.starttime", false); } interventionService.getTableData(range, order, new AsyncCallback<List<Intervention>>() { @Override public void onSuccess(List<Intervention> result) { updateRowData(range.getStart(), result); } @Override public void onFailure(Throwable caught) { log.warn("RPC DB FAILED " + caught); updateRowCount(0, true); } }); } }; // Table dataProvider.addDataDisplay(table); AsyncHandler columnSortHandler = new AsyncHandler(table); table.addColumnSortHandler(columnSortHandler); // startTime startTime = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return PtuClientConstants.dateFormatNoSeconds.format(object .getStartTime()); } @Override public String getDataStoreName() { return "tbl_inspections.starttime"; } }; startTime.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); startTime.setSortable(sortable); if (selectable) { startTime.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> interventionFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Start a new Intervention"; } }; interventionFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final ListBoxField userField = new ListBoxField("User", new NotNullValidator()); fieldset.add(userField); interventionService.getUsers(true, new AsyncCallback<List<User>>() { @Override public void onSuccess(List<User> result) { for (Iterator<User> i = result.iterator(); i .hasNext();) { User user = i.next(); userField.addItem(user.getDisplayName(), user.getId()); } } @Override public void onFailure(Throwable caught) { log.warn("Caught : " + caught); } }); final ListBoxField ptu = new ListBoxField("PTU", new NotNullValidator()); fieldset.add(ptu); interventionService.getDevices(true, new AsyncCallback<List<Device>>() { @Override public void onSuccess(List<Device> result) { for (Iterator<Device> i = result.iterator(); i .hasNext();) { Device device = i.next(); ptu.addItem(device.getName(), device.getId()); } } @Override public void onFailure(Throwable caught) { log.warn("Caught : " + caught); } }); final TextAreaField description = new TextAreaField( "Description"); fieldset.add(description); final Modal m = new Modal(); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); Button ok = new Button("Ok"); ok.setType(ButtonType.PRIMARY); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); Intervention intervention = new Intervention(userField .getId(), ptu.getId(), new Date(), description .getValue()); // FIXME #194 Set<ConstraintViolation<Intervention>> violations = validator .validate(intervention); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<Intervention> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addIntervention(intervention, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed"); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Start a new Intervention"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(startTime, new TextHeader("Start Time"), interventionFooter); table.getColumnSortList().push(new ColumnSortInfo(startTime, false)); // endTime EditableCell cell = new EditableCell() { @Override protected Class<? extends Cell<? extends Object>> getCellClass( Context context, Object value) { return value == END_INTERVENTION ? ButtonCell.class : TextCell.class; } }; Column<Intervention, Object> endTime = new GenericColumn<Intervention>( cell) { @Override public String getValue(Intervention object) { return object.getEndTime() != null ? PtuClientConstants.dateFormatNoSeconds .format(object.getEndTime()) : END_INTERVENTION; } @Override public String getDataStoreName() { return "tbl_inspections.starttime"; } }; endTime.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); endTime.setSortable(sortable); endTime.setFieldUpdater(new FieldUpdater<Intervention, Object>() { @Override public void update(int index, Intervention object, Object value) { if (Window.confirm("Are you sure")) { interventionService.endIntervention(object.getId(), new Date(), new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); table.addColumn(endTime, new TextHeader("End Time"), new TextHeader("")); ClickableTextColumn<Intervention> duration = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { long d = object.getEndTime() == null ? new Date().getTime() : object.getEndTime().getTime(); d = d - object.getStartTime().getTime(); return HumanTime.upToMins(d); } }; duration.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); duration.setSortable(false); if (selectable) { duration.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } table.addColumn(duration, new TextHeader("Duration"), new TextHeader("")); // Name ClickableHtmlColumn<Intervention> name = new ClickableHtmlColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getName(); } @Override public String getDataStoreName() { return "tbl_users.lname"; } }; name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); name.setSortable(sortable); if (selectable) { name.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> nameFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Add a new User"; } }; nameFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final TextBoxField fname = new TextBoxField("First Name", new StringValidator(1, 50)); fieldset.add(fname); final TextBoxField lname = new TextBoxField("Last Name", new StringValidator(4, 50)); fieldset.add(lname); final TextBoxField cernId = new TextBoxField("CERN ID", new OrValidator(new EmptyValidator(), new IntegerValidator())); fieldset.add(cernId); final Modal m = new Modal(); final Button cancel = new Button("Cancel"); cancel.setType(ButtonType.PRIMARY); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); final Button ok = new Button("Ok"); ok.setEnabled(false); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); User user = new User(0, fname.getValue(), lname .getValue(), cernId.getValue()); // FIXME #194 Set<ConstraintViolation<User>> violations = validator .validate(user); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<User> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addUser(user, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Add a new User"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(name, new TextHeader("Name"), nameFooter); // PtuID ClickableTextColumn<Intervention> ptu = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getPtuId(); } @Override public String getDataStoreName() { return "tbl_devices.name"; } }; ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); ptu.setSortable(sortable); if (selectable) { ptu.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> deviceFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Add a new PTU"; } }; deviceFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final TextBoxField ptuId = new TextBoxField("PTU ID", new StringValidator(2, 20)); fieldset.add(ptuId); final TextBoxField ip = new TextBoxField("IP"); fieldset.add(ip); final TextAreaField description = new TextAreaField( "Description"); fieldset.add(description); final Modal m = new Modal(); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); Button ok = new Button("Ok"); ok.setType(ButtonType.PRIMARY); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); Device device = new Device(0, ptuId.getValue(), ip .getValue(), description.getValue()); // FIXME #194 Set<ConstraintViolation<Device>> violations = validator .validate(device); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<Device> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addDevice(device, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Add a new PTU"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(ptu, new TextHeader("PTU ID"), deviceFooter); // Description EditTextColumn<Intervention> description = new EditTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getDescription() != null ? object .getDescription() : ""; } @Override public String getDataStoreName() { return "tbl_inspections.dscr"; } }; description.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); description.setSortable(true); description.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { interventionService.updateInterventionDescription( object.getId(), value, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } }); table.addColumn(description, new TextHeader("Description"), new TextHeader("")); // Selection if (selectable) { final SingleSelectionModel<Intervention> selectionModel = new SingleSelectionModel<Intervention>(); table.setSelectionModel(selectionModel); selectionModel .addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { Intervention m = selectionModel.getSelectedObject(); log.info(m + " " + event.getSource()); } }); } // FIXME #189 this is the normal way, but does not work in our tabs... // tabs should detach, attach... addAttachHandler(new AttachEvent.Handler() { private Timer timer; @Override public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { // refresh for duration timer = new Timer() { @Override public void run() { table.redraw(); } }; timer.scheduleRepeating(60000); } else { if (timer != null) { timer.cancel(); timer = null; } } } }); // FIXME #189 so we handle it with events SelectTabEvent.subscribe(eventBus, new SelectTabEvent.Handler() { @Override public void onTabSelected(SelectTabEvent event) { if (event.getTab().equals("Interventions")) { showUpdate = true; table.redraw(); } } }); return true; }
public boolean configure(Element element, ClientFactory clientFactory, Arguments args) { String height = args.getArg(0); EventBus eventBus = clientFactory.getEventBus(args.getArg(1)); table.setSize("100%", height); table.setEmptyTableWidget(new Label("No Interventions")); pager = new SimplePager(TextLocation.RIGHT); footer.add(pager); pager.setDisplay(table); update = new Button("Update"); update.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { pager.setPage(0); scrollPanel.setVerticalScrollPosition(scrollPanel .getMinimumHorizontalScrollPosition()); table.getColumnSortList().push(new ColumnSortInfo(startTime, false)); scheduler.update(); } }); update.setVisible(false); footer.add(update); setWidth("100%"); add(table, CENTER); scrollPanel = table.getScrollPanel(); scrollPanel.addScrollHandler(new ScrollHandler() { @Override public void onScroll(ScrollEvent event) { if (scrollPanel.getVerticalScrollPosition() == scrollPanel .getMinimumVerticalScrollPosition()) { scheduler.update(); } } }); AsyncDataProvider<Intervention> dataProvider = new AsyncDataProvider<Intervention>() { @Override protected void onRangeChanged(HasData<Intervention> display) { log.info("ON RANGE CHANGED " + display.getVisibleRange()); interventionService.getRowCount(new AsyncCallback<Integer>() { @Override public void onSuccess(Integer result) { updateRowCount(result, true); } @Override public void onFailure(Throwable caught) { updateRowCount(0, true); } }); final Range range = display.getVisibleRange(); final ColumnSortList sortList = table.getColumnSortList(); SortOrder[] order = new SortOrder[sortList.size()]; for (int i = 0; i < sortList.size(); i++) { ColumnSortInfo info = sortList.get(i); // FIXME #88 remove cast order[i] = new SortOrder( ((DataStoreName) info.getColumn()) .getDataStoreName(), info.isAscending()); } if (order.length == 0) { order = new SortOrder[1]; order[0] = new SortOrder("tbl_inspections.starttime", false); } interventionService.getTableData(range, order, new AsyncCallback<List<Intervention>>() { @Override public void onSuccess(List<Intervention> result) { updateRowData(range.getStart(), result); } @Override public void onFailure(Throwable caught) { log.warn("RPC DB FAILED " + caught); updateRowCount(0, true); } }); } }; // Table dataProvider.addDataDisplay(table); AsyncHandler columnSortHandler = new AsyncHandler(table); table.addColumnSortHandler(columnSortHandler); // startTime startTime = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return PtuClientConstants.dateFormatNoSeconds.format(object .getStartTime()); } @Override public String getDataStoreName() { return "tbl_inspections.starttime"; } }; startTime.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); startTime.setSortable(sortable); if (selectable) { startTime.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> interventionFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Start a new Intervention"; } }; interventionFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final ListBoxField userField = new ListBoxField("User", new NotNullValidator()); fieldset.add(userField); interventionService.getUsers(true, new AsyncCallback<List<User>>() { @Override public void onSuccess(List<User> result) { for (Iterator<User> i = result.iterator(); i .hasNext();) { User user = i.next(); userField.addItem(user.getDisplayName(), user.getId()); } } @Override public void onFailure(Throwable caught) { log.warn("Caught : " + caught); } }); final ListBoxField ptu = new ListBoxField("PTU", new NotNullValidator()); fieldset.add(ptu); interventionService.getDevices(true, new AsyncCallback<List<Device>>() { @Override public void onSuccess(List<Device> result) { for (Iterator<Device> i = result.iterator(); i .hasNext();) { Device device = i.next(); ptu.addItem(device.getName(), device.getId()); } } @Override public void onFailure(Throwable caught) { log.warn("Caught : " + caught); } }); final TextAreaField description = new TextAreaField( "Description"); fieldset.add(description); final Modal m = new Modal(); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); Button ok = new Button("Ok"); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); Intervention intervention = new Intervention(userField .getId(), ptu.getId(), new Date(), description .getValue()); // FIXME #194 Set<ConstraintViolation<Intervention>> violations = validator .validate(intervention); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<Intervention> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addIntervention(intervention, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed"); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Start a new Intervention"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(startTime, new TextHeader("Start Time"), interventionFooter); table.getColumnSortList().push(new ColumnSortInfo(startTime, false)); // endTime EditableCell cell = new EditableCell() { @Override protected Class<? extends Cell<? extends Object>> getCellClass( Context context, Object value) { return value == END_INTERVENTION ? ButtonCell.class : TextCell.class; } }; Column<Intervention, Object> endTime = new GenericColumn<Intervention>( cell) { @Override public String getValue(Intervention object) { return object.getEndTime() != null ? PtuClientConstants.dateFormatNoSeconds .format(object.getEndTime()) : END_INTERVENTION; } @Override public String getDataStoreName() { return "tbl_inspections.starttime"; } }; endTime.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); endTime.setSortable(sortable); endTime.setFieldUpdater(new FieldUpdater<Intervention, Object>() { @Override public void update(int index, Intervention object, Object value) { if (Window.confirm("Are you sure")) { interventionService.endIntervention(object.getId(), new Date(), new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); table.addColumn(endTime, new TextHeader("End Time"), new TextHeader("")); ClickableTextColumn<Intervention> duration = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { long d = object.getEndTime() == null ? new Date().getTime() : object.getEndTime().getTime(); d = d - object.getStartTime().getTime(); return HumanTime.upToMins(d); } }; duration.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); duration.setSortable(false); if (selectable) { duration.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } table.addColumn(duration, new TextHeader("Duration"), new TextHeader("")); // Name ClickableHtmlColumn<Intervention> name = new ClickableHtmlColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getName(); } @Override public String getDataStoreName() { return "tbl_users.lname"; } }; name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); name.setSortable(sortable); if (selectable) { name.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> nameFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Add a new User"; } }; nameFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final TextBoxField fname = new TextBoxField("First Name", new StringValidator(1, 50)); fieldset.add(fname); final TextBoxField lname = new TextBoxField("Last Name", new StringValidator(4, 50)); fieldset.add(lname); final TextBoxField cernId = new TextBoxField("CERN ID", new OrValidator(new EmptyValidator(), new IntegerValidator())); fieldset.add(cernId); final Modal m = new Modal(); final Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); final Button ok = new Button("Ok"); ok.setEnabled(false); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); User user = new User(0, fname.getValue(), lname .getValue(), cernId.getValue()); // FIXME #194 Set<ConstraintViolation<User>> violations = validator .validate(user); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<User> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addUser(user, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Add a new User"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(name, new TextHeader("Name"), nameFooter); // PtuID ClickableTextColumn<Intervention> ptu = new ClickableTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getPtuId(); } @Override public String getDataStoreName() { return "tbl_devices.name"; } }; ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); ptu.setSortable(sortable); if (selectable) { ptu.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { selectIntervention(object); } }); } Header<String> deviceFooter = new Header<String>(new ButtonCell()) { @Override public String getValue() { return "Add a new PTU"; } }; deviceFooter.setUpdater(new ValueUpdater<String>() { @Override public void update(String value) { ValidationFieldset fieldset = new ValidationFieldset(); final TextBoxField ptuId = new TextBoxField("PTU ID", new StringValidator(2, 20)); fieldset.add(ptuId); final TextBoxField ip = new TextBoxField("IP"); fieldset.add(ip); final TextAreaField description = new TextAreaField( "Description"); fieldset.add(description); final Modal m = new Modal(); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); } }); Button ok = new Button("Ok"); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { m.hide(); Device device = new Device(0, ptuId.getValue(), ip .getValue(), description.getValue()); // FIXME #194 Set<ConstraintViolation<Device>> violations = validator .validate(device); if (!violations.isEmpty()) { StringBuffer errorMessage = new StringBuffer(); for (ConstraintViolation<Device> constraintViolation : violations) { errorMessage.append('\n'); errorMessage.append(constraintViolation .getMessage()); } log.warn(errorMessage.toString()); } else { interventionService.addDevice(device, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } } }); ValidationForm form = new ValidationForm(ok, cancel); form.setType(FormType.HORIZONTAL); form.add(fieldset); m.setTitle("Add a new PTU"); m.add(form); m.add(new ModalFooter(cancel, ok)); m.show(); } }); table.addColumn(ptu, new TextHeader("PTU ID"), deviceFooter); // Description EditTextColumn<Intervention> description = new EditTextColumn<Intervention>() { @Override public String getValue(Intervention object) { return object.getDescription() != null ? object .getDescription() : ""; } @Override public String getDataStoreName() { return "tbl_inspections.dscr"; } }; description.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); description.setSortable(true); description.setFieldUpdater(new FieldUpdater<Intervention, String>() { @Override public void update(int index, Intervention object, String value) { interventionService.updateInterventionDescription( object.getId(), value, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { scheduler.update(); } @Override public void onFailure(Throwable caught) { log.warn("Failed " + caught); } }); } }); table.addColumn(description, new TextHeader("Description"), new TextHeader("")); // Selection if (selectable) { final SingleSelectionModel<Intervention> selectionModel = new SingleSelectionModel<Intervention>(); table.setSelectionModel(selectionModel); selectionModel .addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { Intervention m = selectionModel.getSelectedObject(); log.info(m + " " + event.getSource()); } }); } // FIXME #189 this is the normal way, but does not work in our tabs... // tabs should detach, attach... addAttachHandler(new AttachEvent.Handler() { private Timer timer; @Override public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { // refresh for duration timer = new Timer() { @Override public void run() { table.redraw(); } }; timer.scheduleRepeating(60000); } else { if (timer != null) { timer.cancel(); timer = null; } } } }); // FIXME #189 so we handle it with events SelectTabEvent.subscribe(eventBus, new SelectTabEvent.Handler() { @Override public void onTabSelected(SelectTabEvent event) { if (event.getTab().equals("Interventions")) { showUpdate = true; table.redraw(); } } }); return true; }
diff --git a/org.dawnsci.plotting/src/org/dawnsci/plotting/expression/ExpressionLazyDataset.java b/org.dawnsci.plotting/src/org/dawnsci/plotting/expression/ExpressionLazyDataset.java index 78fc2bb91..8aa124363 100644 --- a/org.dawnsci.plotting/src/org/dawnsci/plotting/expression/ExpressionLazyDataset.java +++ b/org.dawnsci.plotting/src/org/dawnsci/plotting/expression/ExpressionLazyDataset.java @@ -1,28 +1,28 @@ package org.dawnsci.plotting.expression; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.LazyDataset; import uk.ac.diamond.scisoft.analysis.io.ILazyLoader; class ExpressionLazyDataset extends LazyDataset { /** * */ private static final long serialVersionUID = -4008063310659517138L; public ExpressionLazyDataset(String name, int dtype, int[] shape, ILazyLoader loader) { super(name, dtype, shape, loader); } public void setShapeSilently(final int[] shape) { this.shape = shape; try { size = AbstractDataset.calcSize(shape); } catch (IllegalArgumentException e) { size = Integer.MAX_VALUE; // this indicates that the entire dataset cannot be read in! } - if (lazyErrorDeligate!=null) lazyErrorDeligate.setShape(shape); + if (lazyErrorDelegate!=null) lazyErrorDelegate.setShape(shape); } }
true
true
public void setShapeSilently(final int[] shape) { this.shape = shape; try { size = AbstractDataset.calcSize(shape); } catch (IllegalArgumentException e) { size = Integer.MAX_VALUE; // this indicates that the entire dataset cannot be read in! } if (lazyErrorDeligate!=null) lazyErrorDeligate.setShape(shape); }
public void setShapeSilently(final int[] shape) { this.shape = shape; try { size = AbstractDataset.calcSize(shape); } catch (IllegalArgumentException e) { size = Integer.MAX_VALUE; // this indicates that the entire dataset cannot be read in! } if (lazyErrorDelegate!=null) lazyErrorDelegate.setShape(shape); }
diff --git a/src/ui/side/TimeWavePanel.java b/src/ui/side/TimeWavePanel.java index 276d12c..3af40f1 100644 --- a/src/ui/side/TimeWavePanel.java +++ b/src/ui/side/TimeWavePanel.java @@ -1,168 +1,169 @@ package src.ui.side; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import src.Runner; import src.ui.controller.GameController; public class TimeWavePanel extends JPanel { private static final long serialVersionUID = 1L; private GameController gc; private static final String waveText = "Wave: "; private static final String nextWaveText = "Next wave in: "; private static final String elapsedText = "Time elapsed: "; private static final String nextWaveButtonText = "Next Wave!"; private static final String fastForwardButtonText = ">>"; private JLabel waveNumberLabel; private JLabel waveNumberValueLabel; private JLabel nextWaveValueLabel; private JLabel nextWaveLabel; private JLabel elapsedLabel; private JLabel elapsedValueLabel; private JButton nextWaveButton; private JButton fastForwardButton; public TimeWavePanel(GameController controller, boolean isMultiplayer) { super(new GridBagLayout()); this.gc = controller; waveNumberLabel = new JLabel(waveText); waveNumberValueLabel = new JLabel(Integer.toString(gc.getGame().getWavesSent())); nextWaveLabel = new JLabel(nextWaveText); nextWaveValueLabel = new JLabel(); elapsedLabel = new JLabel(elapsedText); elapsedValueLabel = new JLabel(); nextWaveButton = new JButton(nextWaveButtonText); nextWaveButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { - gc.getGame().sendNextWave(); + if(nextWaveButton.isEnabled()) + gc.getGame().sendNextWave(); } public void mouseReleased(MouseEvent e) { gc.toggleDoubleTime(false); } }); fastForwardButton = new JButton(fastForwardButtonText); fastForwardButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { gc.toggleDoubleTime(true); } public void mouseReleased(MouseEvent e) { gc.toggleDoubleTime(false); } }); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1; c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.NONE; add(waveNumberLabel, c); c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.NONE; add(waveNumberValueLabel, c); c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.NONE; add(nextWaveLabel, c); c.gridx = 1; c.gridy = 1; c.fill = GridBagConstraints.NONE; add(nextWaveValueLabel, c); c.gridx = 0; c.gridy = 2; c.fill = GridBagConstraints.NONE; add(elapsedLabel, c); c.gridx = 1; c.gridy = 2; c.fill = GridBagConstraints.NONE; add(elapsedValueLabel, c); if (!isMultiplayer) { c.gridx = 0; c.gridy = 3; c.fill = GridBagConstraints.NONE; add(nextWaveButton, c); c.gridx = 1; c.gridy = 3; c.fill = GridBagConstraints.NONE; add(fastForwardButton, c); } } public void paintComponent(Graphics g) { super.paintComponent(g); setPauseButton(); updateDisplay(); } public void updateDisplay() { //update wave number waveNumberValueLabel.setText(Integer.toString(gc.getGame().getWavesSent())); //update Next Wave in long secondsUntilNextWave = gc.getGame().getTicksUntilNextWave() * Runner.tickDuration / 1000; nextWaveValueLabel.setText(convertSecondsToTimeString(secondsUntilNextWave)); //update Time elapsed long secondsElapsed = (gc.getGame().getElapsedTime() * Runner.tickDuration) / 1000; elapsedValueLabel.setText(convertSecondsToTimeString(secondsElapsed)); } private String convertSecondsToTimeString(long seconds) { long hours = seconds / 3600; String hoursText = Long.toString(hours); if(hours < 10) hoursText = "0"+hoursText; seconds = seconds % 3600; long minutes = seconds / 60; String minutesText = Long.toString(minutes); if(minutes < 10) minutesText = "0"+minutesText; seconds = seconds % 60; String secondsText = Long.toString(seconds); if(seconds < 10) secondsText = "0"+secondsText; return hoursText + ":" + minutesText + ":" + secondsText; } //Check if there are creeps on the map, and if so, disables the pause button. private void setPauseButton(){ if (gc.getGame().getCreepQueue().size() > 0 || gc.getGame().getCreeps().size() > 0) nextWaveButton.setEnabled(false); else if (!gc.getPaused()) nextWaveButton.setEnabled(true); } }
true
true
public TimeWavePanel(GameController controller, boolean isMultiplayer) { super(new GridBagLayout()); this.gc = controller; waveNumberLabel = new JLabel(waveText); waveNumberValueLabel = new JLabel(Integer.toString(gc.getGame().getWavesSent())); nextWaveLabel = new JLabel(nextWaveText); nextWaveValueLabel = new JLabel(); elapsedLabel = new JLabel(elapsedText); elapsedValueLabel = new JLabel(); nextWaveButton = new JButton(nextWaveButtonText); nextWaveButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { gc.getGame().sendNextWave(); } public void mouseReleased(MouseEvent e) { gc.toggleDoubleTime(false); } }); fastForwardButton = new JButton(fastForwardButtonText); fastForwardButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { gc.toggleDoubleTime(true); } public void mouseReleased(MouseEvent e) { gc.toggleDoubleTime(false); } }); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1; c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.NONE; add(waveNumberLabel, c); c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.NONE; add(waveNumberValueLabel, c); c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.NONE; add(nextWaveLabel, c); c.gridx = 1; c.gridy = 1; c.fill = GridBagConstraints.NONE; add(nextWaveValueLabel, c); c.gridx = 0; c.gridy = 2; c.fill = GridBagConstraints.NONE; add(elapsedLabel, c); c.gridx = 1; c.gridy = 2; c.fill = GridBagConstraints.NONE; add(elapsedValueLabel, c); if (!isMultiplayer) { c.gridx = 0; c.gridy = 3; c.fill = GridBagConstraints.NONE; add(nextWaveButton, c); c.gridx = 1; c.gridy = 3; c.fill = GridBagConstraints.NONE; add(fastForwardButton, c); } }
public TimeWavePanel(GameController controller, boolean isMultiplayer) { super(new GridBagLayout()); this.gc = controller; waveNumberLabel = new JLabel(waveText); waveNumberValueLabel = new JLabel(Integer.toString(gc.getGame().getWavesSent())); nextWaveLabel = new JLabel(nextWaveText); nextWaveValueLabel = new JLabel(); elapsedLabel = new JLabel(elapsedText); elapsedValueLabel = new JLabel(); nextWaveButton = new JButton(nextWaveButtonText); nextWaveButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if(nextWaveButton.isEnabled()) gc.getGame().sendNextWave(); } public void mouseReleased(MouseEvent e) { gc.toggleDoubleTime(false); } }); fastForwardButton = new JButton(fastForwardButtonText); fastForwardButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { gc.toggleDoubleTime(true); } public void mouseReleased(MouseEvent e) { gc.toggleDoubleTime(false); } }); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1; c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.NONE; add(waveNumberLabel, c); c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.NONE; add(waveNumberValueLabel, c); c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.NONE; add(nextWaveLabel, c); c.gridx = 1; c.gridy = 1; c.fill = GridBagConstraints.NONE; add(nextWaveValueLabel, c); c.gridx = 0; c.gridy = 2; c.fill = GridBagConstraints.NONE; add(elapsedLabel, c); c.gridx = 1; c.gridy = 2; c.fill = GridBagConstraints.NONE; add(elapsedValueLabel, c); if (!isMultiplayer) { c.gridx = 0; c.gridy = 3; c.fill = GridBagConstraints.NONE; add(nextWaveButton, c); c.gridx = 1; c.gridy = 3; c.fill = GridBagConstraints.NONE; add(fastForwardButton, c); } }
diff --git a/pmd/src/net/sourceforge/pmd/ast/ASTModifiers.java b/pmd/src/net/sourceforge/pmd/ast/ASTModifiers.java index 41faff52c..96c6eae12 100644 --- a/pmd/src/net/sourceforge/pmd/ast/ASTModifiers.java +++ b/pmd/src/net/sourceforge/pmd/ast/ASTModifiers.java @@ -1,36 +1,40 @@ /* Generated By:JJTree: Do not edit this line. ASTModifiers.java */ package net.sourceforge.pmd.ast; public class ASTModifiers extends SimpleNode { public ASTModifiers(int id) { super(id); } public ASTModifiers(JavaParser p, int id) { super(p, id); } public boolean isDiscardable() { return true; } public void discardIfNecessary() { SimpleNode parent = (SimpleNode)jjtGetParent(); if (jjtGetNumChildren() > 0 && jjtGetChild(0) instanceof ASTAnnotation) { super.discardIfNecessary(); } else if (parent.jjtGetNumChildren() == 2) { parent.children = new Node[] {parent.children[1]}; + } else if (parent.jjtGetNumChildren() == 3) { + // AnnotationTypeMemberDeclaration with default value, like this: + // String defaultValue() default ""; + parent.children = new Node[] {parent.children[1], parent.children[2]}; } else if (parent.jjtGetNumChildren() == 4) { // JDK 1.5 forloop syntax parent.children = new Node[] {parent.children[1], parent.children[2], parent.children[3]}; } else { throw new RuntimeException("ASTModifiers.discardIfNecessary didn't see expected children"); } } /** Accept the visitor. **/ public Object jjtAccept(JavaParserVisitor visitor, Object data) { return visitor.visit(this, data); } }
true
true
public void discardIfNecessary() { SimpleNode parent = (SimpleNode)jjtGetParent(); if (jjtGetNumChildren() > 0 && jjtGetChild(0) instanceof ASTAnnotation) { super.discardIfNecessary(); } else if (parent.jjtGetNumChildren() == 2) { parent.children = new Node[] {parent.children[1]}; } else if (parent.jjtGetNumChildren() == 4) { // JDK 1.5 forloop syntax parent.children = new Node[] {parent.children[1], parent.children[2], parent.children[3]}; } else { throw new RuntimeException("ASTModifiers.discardIfNecessary didn't see expected children"); } }
public void discardIfNecessary() { SimpleNode parent = (SimpleNode)jjtGetParent(); if (jjtGetNumChildren() > 0 && jjtGetChild(0) instanceof ASTAnnotation) { super.discardIfNecessary(); } else if (parent.jjtGetNumChildren() == 2) { parent.children = new Node[] {parent.children[1]}; } else if (parent.jjtGetNumChildren() == 3) { // AnnotationTypeMemberDeclaration with default value, like this: // String defaultValue() default ""; parent.children = new Node[] {parent.children[1], parent.children[2]}; } else if (parent.jjtGetNumChildren() == 4) { // JDK 1.5 forloop syntax parent.children = new Node[] {parent.children[1], parent.children[2], parent.children[3]}; } else { throw new RuntimeException("ASTModifiers.discardIfNecessary didn't see expected children"); } }
diff --git a/src/com/sun/gi/framework/status/ReportUpdater.java b/src/com/sun/gi/framework/status/ReportUpdater.java index 65c5c630d..12c497ee2 100644 --- a/src/com/sun/gi/framework/status/ReportUpdater.java +++ b/src/com/sun/gi/framework/status/ReportUpdater.java @@ -1,121 +1,121 @@ /* * Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, California 95054, U.S.A. All rights reserved. * * Sun Microsystems, Inc. has intellectual property rights relating to * technology embodied in the product that is described in this * document. In particular, and without limitation, these intellectual * property rights may include one or more of the U.S. patents listed at * http://www.sun.com/patents and one or more additional patents or * pending patent applications in the U.S. and in other countries. * * U.S. Government Rights - Commercial software. Government users are * subject to the Sun Microsystems, Inc. standard license agreement and * applicable provisions of the FAR and its supplements. * * Use is subject to license terms. * * This distribution may include materials developed by third parties. * * Sun, Sun Microsystems, the Sun logo and Java are trademarks or * registered trademarks of Sun Microsystems, Inc. in the U.S. and other * countries. * * This product is covered and controlled by U.S. Export Control laws * and may be subject to the export or import laws in other countries. * Nuclear, missile, chemical biological weapons or nuclear maritime end * uses or end users, whether direct or indirect, are strictly * prohibited. Export or reexport to countries subject to U.S. embargo * or to entities identified on U.S. export exclusion lists, including, * but not limited to, the denied persons and specially designated * nationals lists is strictly prohibited. * * Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, California 95054, Etats-Unis. Tous droits réservés. * * Sun Microsystems, Inc. détient les droits de propriété intellectuels * relatifs à la technologie incorporée dans le produit qui est décrit * dans ce document. En particulier, et ce sans limitation, ces droits * de propriété intellectuelle peuvent inclure un ou plus des brevets * américains listés à l'adresse http://www.sun.com/patents et un ou les * brevets supplémentaires ou les applications de brevet en attente aux * Etats - Unis et dans les autres pays. * * L'utilisation est soumise aux termes de la Licence. * * Cette distribution peut comprendre des composants développés par des * tierces parties. * * Sun, Sun Microsystems, le logo Sun et Java sont des marques de * fabrique ou des marques déposées de Sun Microsystems, Inc. aux * Etats-Unis et dans d'autres pays. * * Ce produit est soumis à la législation américaine en matière de * contrôle des exportations et peut être soumis à la règlementation en * vigueur dans d'autres pays dans le domaine des exportations et * importations. Les utilisations, ou utilisateurs finaux, pour des * armes nucléaires,des missiles, des armes biologiques et chimiques ou * du nucléaire maritime, directement ou indirectement, sont strictement * interdites. Les exportations ou réexportations vers les pays sous * embargo américain, ou vers des entités figurant sur les listes * d'exclusion d'exportation américaines, y compris, mais de manière non * exhaustive, la liste de personnes qui font objet d'un ordre de ne pas * participer, d'une façon directe ou indirecte, aux exportations des * produits ou des services qui sont régis par la législation américaine * en matière de contrôle des exportations et la liste de ressortissants * spécifiquement désignés, sont rigoureusement interdites. */ package com.sun.gi.framework.status; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ReportUpdater { final ReportManager reportManager; long updateTime; long lastUpdate; List<StatusReport> reports = new ArrayList<StatusReport>(); Thread thread; public ReportUpdater(ReportManager mgr) { reportManager = mgr; updateTime = mgr.getReportTTL(); thread = new Thread(new Runnable() { public void run() { lastUpdate = System.currentTimeMillis(); while (true) { try { // update report when its 50% expired to ensure against delays in comm Thread.sleep(updateTime/2); } catch (InterruptedException ex) { ex.printStackTrace(); } long time = System.currentTimeMillis(); - if (time > (lastUpdate + updateTime)) { + if (time > (lastUpdate + (updateTime/2))) { lastUpdate = time; for (StatusReport report : reports) { try { reportManager.sendReport(report); } catch (IOException ex1) { ex1.printStackTrace(); } } } } } }); thread.start(); } /** * addReport * * @param installationReport the StatusReport to add */ public void addReport(StatusReport installationReport) { reports.add(installationReport); } }
true
true
public ReportUpdater(ReportManager mgr) { reportManager = mgr; updateTime = mgr.getReportTTL(); thread = new Thread(new Runnable() { public void run() { lastUpdate = System.currentTimeMillis(); while (true) { try { // update report when its 50% expired to ensure against delays in comm Thread.sleep(updateTime/2); } catch (InterruptedException ex) { ex.printStackTrace(); } long time = System.currentTimeMillis(); if (time > (lastUpdate + updateTime)) { lastUpdate = time; for (StatusReport report : reports) { try { reportManager.sendReport(report); } catch (IOException ex1) { ex1.printStackTrace(); } } } } } }); thread.start(); }
public ReportUpdater(ReportManager mgr) { reportManager = mgr; updateTime = mgr.getReportTTL(); thread = new Thread(new Runnable() { public void run() { lastUpdate = System.currentTimeMillis(); while (true) { try { // update report when its 50% expired to ensure against delays in comm Thread.sleep(updateTime/2); } catch (InterruptedException ex) { ex.printStackTrace(); } long time = System.currentTimeMillis(); if (time > (lastUpdate + (updateTime/2))) { lastUpdate = time; for (StatusReport report : reports) { try { reportManager.sendReport(report); } catch (IOException ex1) { ex1.printStackTrace(); } } } } } }); thread.start(); }