diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/src/java/org/codehaus/groovy/grails/commons/DefaultGrailsDomainClass.java b/src/java/org/codehaus/groovy/grails/commons/DefaultGrailsDomainClass.java index f5b9726ca..798391c1f 100644 --- a/src/java/org/codehaus/groovy/grails/commons/DefaultGrailsDomainClass.java +++ b/src/java/org/codehaus/groovy/grails/commons/DefaultGrailsDomainClass.java @@ -1,762 +1,776 @@ /* Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.commons; import static java.util.Collections.EMPTY_LIST; import static java.util.Collections.EMPTY_MAP; import static java.util.Collections.unmodifiableMap; import grails.util.GrailsNameUtils; +import groovy.lang.Closure; import groovy.lang.GroovyObject; import java.beans.PropertyDescriptor; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.groovy.grails.exceptions.GrailsDomainException; import org.codehaus.groovy.grails.exceptions.InvalidPropertyException; +import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.springframework.validation.Validator; /** * @author Graeme Rocher * @since 05-Jul-2005 */ public class DefaultGrailsDomainClass extends AbstractGrailsClass implements GrailsDomainClass { private GrailsDomainClassProperty identifier; private GrailsDomainClassProperty version; private GrailsDomainClassProperty[] properties; private GrailsDomainClassProperty[] persistentProperties; private Map<String, GrailsDomainClassProperty> propertyMap; private Map relationshipMap; private Map hasOneMap; private Map constraints; private Map mappedBy; private Validator validator; private String mappingStrategy = GrailsDomainClass.GORM; - private List owners = new ArrayList(); + private List<Class> owners = new ArrayList<Class>(); private boolean root = true; private Set subClasses = new HashSet(); private Collection embedded; private Map<String, Object> defaultConstraints; public DefaultGrailsDomainClass(Class clazz, Map<String, Object> defaultConstraints) { super(clazz, ""); PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(); if(!clazz.getSuperclass().equals( GroovyObject.class ) && !clazz.getSuperclass().equals(Object.class) && !Modifier.isAbstract(clazz.getSuperclass().getModifiers())) { this.root = false; } this.propertyMap = new LinkedHashMap<String, GrailsDomainClassProperty>(); this.relationshipMap = getAssociationMap(); this.embedded = getEmbeddedList(); this.defaultConstraints = defaultConstraints; // get mapping strategy by setting this.mappingStrategy = getStaticPropertyValue(GrailsDomainClassProperty.MAPPING_STRATEGY, String.class); if(this.mappingStrategy == null) { this.mappingStrategy = GORM; } // get any mappedBy settings this.mappedBy = getStaticPropertyValue(GrailsDomainClassProperty.MAPPED_BY, Map.class); this.hasOneMap = getStaticPropertyValue(GrailsDomainClassProperty.HAS_ONE, Map.class); if(hasOneMap == null) hasOneMap = EMPTY_MAP; if(this.mappedBy == null)this.mappedBy = EMPTY_MAP; // establish the owners of relationships establishRelationshipOwners(); // First go through the properties of the class and create domain properties // populating into a map populateDomainClassProperties(propertyDescriptors); // if no identifier property throw exception if(this.identifier == null) { throw new GrailsDomainException("Identity property not found, but required in domain class ["+getFullName()+"]" ); } // if no version property throw exception if(this.version == null) { throw new GrailsDomainException("Version property not found, but required in domain class ["+getFullName()+"]" ); } // set properties from map values this.properties = this.propertyMap.values().toArray( new GrailsDomainClassProperty[this.propertyMap.size()] ); // establish relationships establishRelationships(); // set persistent properties establishPersistentProperties(); } public DefaultGrailsDomainClass(Class clazz) { this(clazz, null); } public boolean hasSubClasses() { return getSubClasses().size() > 0; } /** * calculates the persistent properties from the evaluated properties */ private void establishPersistentProperties() { Collection<GrailsDomainClassProperty> tempList = new ArrayList<GrailsDomainClassProperty>(); for (Object o : this.propertyMap.values()) { GrailsDomainClassProperty currentProp = (GrailsDomainClassProperty) o; if (currentProp.getType() != Object.class && currentProp.isPersistent() && !currentProp.isIdentity() && !currentProp.getName().equals(GrailsDomainClassProperty.VERSION)) { tempList.add(currentProp); } } this.persistentProperties = tempList.toArray( new GrailsDomainClassProperty[tempList.size()]); } /** * Evaluates the belongsTo property to find out who owns who */ private void establishRelationshipOwners() { Class belongsTo = getStaticPropertyValue(GrailsDomainClassProperty.BELONGS_TO, Class.class); if(belongsTo == null) { List ownersProp = getStaticPropertyValue(GrailsDomainClassProperty.BELONGS_TO, List.class); if(ownersProp != null) { this.owners = ownersProp; } else { Map ownersMap = getStaticPropertyValue(GrailsDomainClassProperty.BELONGS_TO, Map.class); if(ownersMap!=null) { this.owners = new ArrayList(ownersMap.values()); } } } else { this.owners = new ArrayList(); this.owners.add(belongsTo); } } /** * Populates the domain class properties map * * @param propertyDescriptors The property descriptors */ private void populateDomainClassProperties(PropertyDescriptor[] propertyDescriptors) { for (PropertyDescriptor descriptor : propertyDescriptors) { // ignore certain properties if (GrailsDomainConfigurationUtil.isNotConfigurational(descriptor)) { GrailsDomainClassProperty property = new DefaultGrailsDomainClassProperty(this, descriptor); this.propertyMap.put(property.getName(), property); if (property.isIdentity()) { this.identifier = property; } else if (property.getName().equals(GrailsDomainClassProperty.VERSION)) { this.version = property; } } } } /** * Retrieves the association map */ public Map getAssociationMap() { if(this.relationshipMap == null) { relationshipMap = getStaticPropertyValue(GrailsDomainClassProperty.HAS_MANY, Map.class); if(relationshipMap == null) this.relationshipMap = new HashMap(); Class theClass = getClazz(); while(theClass != Object.class) { theClass = theClass.getSuperclass(); ClassPropertyFetcher propertyFetcher = ClassPropertyFetcher.forClass(theClass); Map superRelationshipMap = propertyFetcher.getStaticPropertyValue(GrailsDomainClassProperty.HAS_MANY, Map.class); if(superRelationshipMap != null && !superRelationshipMap.equals(relationshipMap)) { relationshipMap.putAll(superRelationshipMap); } } } return this.relationshipMap; } /** * Retrieves the list of known embedded component types * * @return A list of embedded components */ private Collection getEmbeddedList() { Collection potentialList = getStaticPropertyValue(GrailsDomainClassProperty.EMBEDDED, Collection.class); return potentialList != null ? potentialList : EMPTY_LIST; } /** * Calculates the relationship type based other types referenced * */ private void establishRelationships() { for (Object o : this.propertyMap.values()) { DefaultGrailsDomainClassProperty currentProp = (DefaultGrailsDomainClassProperty) o; if(!currentProp.isPersistent()) continue; Class currentPropType = currentProp.getType(); // establish if the property is a one-to-many // if it is a Set and there are relationships defined // and it is defined as persistent if (Collection.class.isAssignableFrom(currentPropType) || Map.class.isAssignableFrom(currentPropType)) { establishRelationshipForCollection(currentProp); } // otherwise if the type is a domain class establish relationship else if (DomainClassArtefactHandler.isDomainClass(currentPropType) && currentProp.isPersistent()) { establishDomainClassRelationship(currentProp); } else if (embedded.contains(currentProp.getName())) { establishDomainClassRelationship(currentProp); } } } /** * Establishes a relationship for a java.util.Set * * @param property The collection property */ private void establishRelationshipForCollection(DefaultGrailsDomainClassProperty property) { // is it a relationship Class relatedClassType = getRelatedClassType( property.getName() ); if(relatedClassType != null) { // set the referenced type in the property property.setReferencedPropertyType(relatedClassType); // if the related type is a domain class // then figure out what kind of relationship it is if(DomainClassArtefactHandler.isDomainClass(relatedClassType)) { // check the relationship defined in the referenced type // if it is also a Set/domain class etc. Map relatedClassRelationships = GrailsDomainConfigurationUtil.getAssociationMap(relatedClassType); Class relatedClassPropertyType = null; // First check whether there is an explicit relationship // mapping for this property (as provided by "mappedBy"). String mappingProperty = (String)this.mappedBy.get(property.getName()); if(!StringUtils.isBlank(mappingProperty)) { // First find the specified property on the related // class, if it exists. PropertyDescriptor pd = findProperty(GrailsClassUtils.getPropertiesOfType(relatedClassType, getClazz()), mappingProperty); // If a property of the required type does not exist, // search for any collection properties on the related // class. if(pd == null) pd = findProperty(GrailsClassUtils.getPropertiesAssignableToType(relatedClassType, Collection.class), mappingProperty); // We've run out of options. The given "mappedBy" // setting is invalid. if(pd == null) throw new GrailsDomainException("Non-existent mapping property ["+mappingProperty+"] specified for property ["+property.getName()+"] in class ["+getClazz()+"]"); // Tie the properties together. relatedClassPropertyType = pd.getPropertyType(); property.setReferencePropertyName(pd.getName()); } else { // if the related type has a relationships map it may be a many-to-many // figure out if there is a many-to-many relationship defined if( isRelationshipManyToMany(property, relatedClassType, relatedClassRelationships)) { String relatedClassPropertyName = null; Map relatedClassMappedBy = GrailsDomainConfigurationUtil.getMappedByMap(relatedClassType); // retrieve the relationship property for (Object o : relatedClassRelationships.keySet()) { String currentKey = (String) o; String mappedByProperty = (String) relatedClassMappedBy.get(currentKey); if(mappedByProperty != null && !mappedByProperty.equals(property.getName())) continue; Class currentClass = (Class) relatedClassRelationships.get(currentKey); if (currentClass.isAssignableFrom(getClazz())) { relatedClassPropertyName = currentKey; break; } } // if there is one defined get the type if(relatedClassPropertyName != null) { relatedClassPropertyType = GrailsClassUtils.getPropertyType( relatedClassType, relatedClassPropertyName); } } // otherwise figure out if there is a one-to-many relationship by retrieving any properties that are of the related type // if there is more than one property then (for the moment) ignore the relationship if(relatedClassPropertyType == null) { PropertyDescriptor[] descriptors = GrailsClassUtils.getPropertiesOfType(relatedClassType, getClazz()); if(descriptors.length == 1) { relatedClassPropertyType = descriptors[0].getPropertyType(); property.setReferencePropertyName(descriptors[0].getName()); } else if(descriptors.length > 1) { // try now to use the class name by convention String classPropertyName = getPropertyName(); PropertyDescriptor pd = findProperty(descriptors, classPropertyName); if(pd == null) { throw new GrailsDomainException("Property ["+property.getName()+"] in class ["+getClazz()+"] is a bidirectional one-to-many with two possible properties on the inverse side. "+ "Either name one of the properties on other side of the relationship ["+classPropertyName+"] or use the 'mappedBy' static to define the property " + "that the relationship is mapped with. Example: static mappedBy = ["+property.getName()+":'myprop']"); } relatedClassPropertyType = pd.getPropertyType(); property.setReferencePropertyName(pd.getName()); } } } establishRelationshipForSetToType(property,relatedClassPropertyType); // if its a many-to-many figure out the owning side of the relationship if(property.isManyToMany()) { establishOwnerOfManyToMany(property, relatedClassType); } } // otherwise set it to not persistent as you can't persist // relationships to non-domain classes else { property.setBasicCollectionType(true); } } else if(!Map.class.isAssignableFrom(property.getType())) { // no relationship defined for set. // set not persistent property.setPersistant(false); } } /** * Finds a property type is an array of descriptors for the given property name * * @param descriptors The descriptors * @param propertyName The property name * @return The Class or null */ private PropertyDescriptor findProperty(PropertyDescriptor[] descriptors, String propertyName) { PropertyDescriptor d = null; for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getName().equals(propertyName)) { d = descriptor; break; } } return d; } /** * Find out if the relationship is a many-to-many * * @param property The property * @param relatedClassType The related type * @param relatedClassRelationships The related types relationships * @return True if the relationship is a many-to-many */ private boolean isRelationshipManyToMany(DefaultGrailsDomainClassProperty property, Class relatedClassType, Map relatedClassRelationships) { return relatedClassRelationships != null && !relatedClassRelationships.isEmpty() && !relatedClassType.equals(property.getDomainClass().getClazz()); } /** * Inspects a related classes' ownership settings against this properties class' ownership * settings to find out who owns a many-to-many relationship * * @param property The property * @param relatedClassType The related type */ private void establishOwnerOfManyToMany(DefaultGrailsDomainClassProperty property, Class relatedClassType) { ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(relatedClassType); Object relatedBelongsTo = cpf.getPropertyValue(GrailsDomainClassProperty.BELONGS_TO); boolean owningSide = false; - boolean relatedOwner = this.owners.contains(relatedClassType); + boolean relatedOwner = isOwningSide(relatedClassType, this.owners); final Class propertyClass = property.getDomainClass().getClazz(); if(relatedBelongsTo instanceof Collection) { - owningSide = ((Collection)relatedBelongsTo).contains(propertyClass); + final Collection associatedOwners = (Collection)relatedBelongsTo; + owningSide = isOwningSide(propertyClass, associatedOwners); } - else if (relatedBelongsTo != null) { - owningSide = relatedBelongsTo.equals(propertyClass); + else if (relatedBelongsTo instanceof Class) { + final Collection associatedOwners = new ArrayList(); + associatedOwners.add(relatedBelongsTo); + owningSide = isOwningSide(propertyClass, associatedOwners); } property.setOwningSide(owningSide); if(relatedOwner && property.isOwningSide()) { throw new GrailsDomainException("Domain classes ["+propertyClass+"] and ["+relatedClassType+"] cannot own each other in a many-to-many relationship. Both contain belongsTo definitions that reference each other."); } else if(!relatedOwner && !property.isOwningSide() && !(property.isCircular() && property.isManyToMany())) { throw new GrailsDomainException("No owner defined between domain classes ["+propertyClass+"] and ["+relatedClassType+"] in a many-to-many relationship. Example: def belongsTo = "+relatedClassType.getName()); } } + private boolean isOwningSide(Class relatedClassType, Collection<Class> owners) { + boolean relatedOwner = false; + for (Class relatedClass : owners) { + if(relatedClass.isAssignableFrom(relatedClassType)) { + relatedOwner = true; break; + } + } + return relatedOwner; + } /** * Establishes whether the relationship is a bi-directional or uni-directional one-to-many * and applies the appropriate settings to the specified property * * @param property The property to apply settings to * @param relatedClassPropertyType The related type */ private void establishRelationshipForSetToType(DefaultGrailsDomainClassProperty property, Class relatedClassPropertyType) { if(relatedClassPropertyType == null) { // uni-directional one-to-many property.setOneToMany(true); property.setBidirectional(false); } else if( Collection.class.isAssignableFrom(relatedClassPropertyType) || Map.class.isAssignableFrom(relatedClassPropertyType) ){ // many-to-many property.setManyToMany(true); property.setBidirectional(true); } else if(DomainClassArtefactHandler.isDomainClass(relatedClassPropertyType)) { // bi-directional one-to-many property.setOneToMany( true ); property.setBidirectional( true ); } } /** * Establish relationship with related domain class * * @param property Establishes a relationship between this class and the domain class property */ private void establishDomainClassRelationship(DefaultGrailsDomainClassProperty property) { Class propType = property.getType(); if(embedded.contains(property.getName())) { property.setEmbedded(true); return; } // establish relationship to type Map relatedClassRelationships = GrailsDomainConfigurationUtil.getAssociationMap(propType); Map mappedBy = GrailsDomainConfigurationUtil.getMappedByMap(propType); Class relatedClassPropertyType = null; // if there is a relationships map use that to find out // whether it is mapped to a Set if( relatedClassRelationships != null && !relatedClassRelationships.isEmpty() ) { String relatedClassPropertyName = findOneToManyThatMatchesType(property, relatedClassRelationships); PropertyDescriptor[] descriptors = GrailsClassUtils.getPropertiesOfType(getClazz(), property.getType()); // if there is only one property on many-to-one side of the relationship then // try to establish if it is bidirectional if(descriptors.length == 1 && isNotMappedToDifferentProperty(property,relatedClassPropertyName, mappedBy)) { if(!StringUtils.isBlank(relatedClassPropertyName)) { property.setReferencePropertyName(relatedClassPropertyName); // get the type of the property relatedClassPropertyType = GrailsClassUtils.getPropertyType( propType, relatedClassPropertyName ); } } // if there is more than one property on the many-to-one side then we need to either // find out if there is a mappedBy property or whether a convention is used to decide // on the mapping property else if(descriptors.length > 1) { if(mappedBy.containsValue(property.getName())) { for (Object o : mappedBy.keySet()) { String mappedByPropertyName = (String) o; if (property.getName().equals(mappedBy.get(mappedByPropertyName))) { Class mappedByRelatedType = (Class) relatedClassRelationships.get(mappedByPropertyName); if (mappedByRelatedType != null && propType.isAssignableFrom(mappedByRelatedType)) relatedClassPropertyType = GrailsClassUtils.getPropertyType(propType, mappedByPropertyName); } } } else { String classNameAsProperty = GrailsNameUtils.getPropertyName(propType); if(property.getName().equals(classNameAsProperty) && !mappedBy.containsKey(relatedClassPropertyName)) { relatedClassPropertyType = GrailsClassUtils.getPropertyType( propType, relatedClassPropertyName ); } } } } // otherwise retrieve all the properties of the type from the associated class if(relatedClassPropertyType == null) { PropertyDescriptor[] descriptors = GrailsClassUtils.getPropertiesOfType(propType, getClazz()); // if there is only one then the association is established if(descriptors.length == 1) { relatedClassPropertyType = descriptors[0].getPropertyType(); } } // establish relationship based on this type establishDomainClassRelationshipToType( property, relatedClassPropertyType ); } private boolean isNotMappedToDifferentProperty(GrailsDomainClassProperty property, String relatedClassPropertyName, Map mappedBy) { String mappedByForRelation = (String)mappedBy.get(relatedClassPropertyName); if(mappedByForRelation == null) return true; else if(!property.getName().equals(mappedByForRelation)) return false; return true; } private String findOneToManyThatMatchesType(DefaultGrailsDomainClassProperty property, Map relatedClassRelationships) { String relatedClassPropertyName = null; for (Object o : relatedClassRelationships.keySet()) { String currentKey = (String) o; Class currentClass = (Class) relatedClassRelationships.get(currentKey); if (property.getDomainClass().getClazz().getName().equals(currentClass.getName())) { relatedClassPropertyName = currentKey; break; } } return relatedClassPropertyName; } private void establishDomainClassRelationshipToType(DefaultGrailsDomainClassProperty property, Class relatedClassPropertyType) { // uni-directional one-to-one if(relatedClassPropertyType == null) { if(hasOneMap.containsKey(property.getName())) { property.setHasOne(true); } property.setOneToOne(true); property.setBidirectional(false); } // bi-directional many-to-one else if(Collection.class.isAssignableFrom(relatedClassPropertyType)||Map.class.isAssignableFrom(relatedClassPropertyType)) { property.setManyToOne(true); property.setBidirectional(true); } // bi-directional one-to-one else if(DomainClassArtefactHandler.isDomainClass(relatedClassPropertyType)) { if(hasOneMap.containsKey(property.getName())) { property.setHasOne(true); } property.setOneToOne(true); if(!getClazz().equals(relatedClassPropertyType)) property.setBidirectional(true); } } public boolean isOwningClass(Class domainClass) { return this.owners.contains(domainClass); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.domain.GrailsDomainClass#getProperties() */ public GrailsDomainClassProperty[] getProperties() { return this.properties; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.domain.GrailsDomainClass#getIdentifier() */ public GrailsDomainClassProperty getIdentifier() { return this.identifier; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.domain.GrailsDomainClass#getVersion() */ public GrailsDomainClassProperty getVersion() { return this.version; } /** * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#getPersistantProperties() * @deprecated */ public GrailsDomainClassProperty[] getPersistantProperties() { return this.persistentProperties; } public GrailsDomainClassProperty[] getPersistentProperties() { return this.persistentProperties; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.domain.GrailsDomainClass#getPropertyByName(java.lang.String) */ public GrailsDomainClassProperty getPropertyByName(String name) { if(this.propertyMap.containsKey(name)) { return this.propertyMap.get(name); } else { throw new InvalidPropertyException("No property found for name ["+name+"] for class ["+getClazz()+"]"); } } /* (non-Javadoc) * @see org.codehaus.groovy.grails.domain.GrailsDomainClass#getFieldName(java.lang.String) */ public String getFieldName(String propertyName) { return getPropertyByName(propertyName).getFieldName(); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.AbstractGrailsClass#getName() */ public String getName() { return ClassUtils.getShortClassName(super.getName()); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.domain.GrailsDomainClass#isOneToMany(java.lang.String) */ public boolean isOneToMany(String propertyName) { return getPropertyByName(propertyName).isOneToMany(); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.domain.GrailsDomainClass#isManyToOne(java.lang.String) */ public boolean isManyToOne(String propertyName) { return getPropertyByName(propertyName).isManyToOne(); } protected Object getPropertyOrStaticPropertyOrFieldValue(String name, Class type) { return super.getPropertyOrStaticPropertyOrFieldValue(name,type); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#getRelationshipType(java.lang.String) */ public Class getRelatedClassType(String propertyName) { return (Class)this.relationshipMap.get(propertyName); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#getPropertyName() */ public String getPropertyName() { return GrailsNameUtils.getPropertyNameRepresentation(getClazz()); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#isBidirectional() */ public boolean isBidirectional(String propertyName) { return getPropertyByName(propertyName).isBidirectional(); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#getConstraints() */ public Map getConstrainedProperties() { if(this.constraints==null) { initializeConstraints(); } return unmodifiableMap(this.constraints); } private void initializeConstraints() { // process the constraints if(defaultConstraints != null) { this.constraints = GrailsDomainConfigurationUtil.evaluateConstraints(getClazz(), this.persistentProperties, defaultConstraints); } else { this.constraints = GrailsDomainConfigurationUtil.evaluateConstraints(getClazz(), this.persistentProperties); } } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#getValidator() */ public Validator getValidator() { return this.validator; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#setValidator(Validator validator) */ public void setValidator(Validator validator) { this.validator = validator; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.commons.GrailsDomainClass#getMappedBy() */ public String getMappingStrategy() { return this.mappingStrategy; } public boolean isRoot() { return this.root; } public Set getSubClasses() { return this.subClasses; } public void refreshConstraints() { if(defaultConstraints!=null) { this.constraints = GrailsDomainConfigurationUtil.evaluateConstraints(getClazz(), this.persistentProperties, defaultConstraints); } else { this.constraints = GrailsDomainConfigurationUtil.evaluateConstraints(getClazz(), this.persistentProperties); } // Embedded components have their own ComponentDomainClass // instance which won't be refreshed by the application. // So, we have to do it here. for (GrailsDomainClassProperty property : this.persistentProperties) { if (property.isEmbedded()) { property.getComponent().refreshConstraints(); } } } public Map getMappedBy() { return mappedBy; } public boolean hasPersistentProperty(String propertyName) { for (GrailsDomainClassProperty persistentProperty : persistentProperties) { if (persistentProperty.getName().equals(propertyName)) return true; } return false; } public void setMappingStrategy(String strategy) { this.mappingStrategy = strategy; } }
false
false
null
null
diff --git a/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersBaseAdapterWrapper.java b/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersBaseAdapterWrapper.java index db7f502..605e6df 100644 --- a/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersBaseAdapterWrapper.java +++ b/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersBaseAdapterWrapper.java @@ -1,588 +1,588 @@ /* Copyright 2013 Tonic Artos 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.tonicartos.widget.stickygridheaders; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.database.DataSetObserver; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Adapter wrapper to insert extra views and otherwise hack around GridView to * add sections and headers. * * @author Tonic Artos */ public class StickyGridHeadersBaseAdapterWrapper extends BaseAdapter { private static boolean sCurrentlySizingRow; private static final int sNumViewTypes = 2; protected static final int ID_FILLER = -0x02; protected static final int ID_HEADER = -0x01; protected static final int POSITION_FILLER = -0x01; protected static final int POSITION_HEADER = -0x02; protected static final int VIEW_TYPE_FILLER = 0x00; protected static final int VIEW_TYPE_HEADER = 0x01; private final StickyGridHeadersBaseAdapter mDelegate; private final Context mContext; private int mCount; private DataSetObserver mDataSetObserver = new DataSetObserver() { @Override public void onChanged() { updateCount(); notifyDataSetChanged(); } @Override public void onInvalidated() { mHeaderCache.clear(); notifyDataSetInvalidated(); } }; - private StickyGridHeadersGridView mDridView; + private StickyGridHeadersGridView mGridView; private final List<View> mHeaderCache = new ArrayList<View>(); private int mNumColumns = 1; private View[] mRowSiblings; public StickyGridHeadersBaseAdapterWrapper(Context context, StickyGridHeadersGridView gridView, StickyGridHeadersBaseAdapter delegate) { mContext = context; mDelegate = delegate; - mDridView = gridView; + mGridView = gridView; delegate.registerDataSetObserver(mDataSetObserver); } @Override public boolean areAllItemsEnabled() { return false; } @Override public int getCount() { mCount = 0; int numHeaders = mDelegate.getNumHeaders(); if (numHeaders == 0) { return mDelegate.getCount(); } for (int i = 0; i < numHeaders; i++) { // Pad count with space for header and trailing filler in header // group. mCount += mDelegate.getCountForHeader(i) + unFilledSpacesInHeaderGroup(i) + mNumColumns; } return mCount; } /** * Get the data item associated with the specified position in the data set. * <p> * Since this wrapper inserts fake entries to fill out items grouped by * header and also spaces to insert headers into some positions will return * null. * </p> * * @param position Position of the item whose data we want within the * adapter's data set. * @return The data at the specified position. */ @Override public Object getItem(int position) throws ArrayIndexOutOfBoundsException { Position adapterPosition = translatePosition(position); if (adapterPosition.mPosition == POSITION_FILLER || adapterPosition.mPosition == POSITION_HEADER) { // Fake entry in view. return null; } return mDelegate.getItem(adapterPosition.mPosition); } @Override public long getItemId(int position) { Position adapterPosition = translatePosition(position); if (adapterPosition.mPosition == POSITION_HEADER) { return ID_HEADER; } if (adapterPosition.mPosition == POSITION_FILLER) { return ID_FILLER; } return mDelegate.getItemId(adapterPosition.mPosition); } @Override public int getItemViewType(int position) { Position adapterPosition = translatePosition(position); if (adapterPosition.mPosition == POSITION_HEADER) { return VIEW_TYPE_HEADER; } if (adapterPosition.mPosition == POSITION_FILLER) { return VIEW_TYPE_FILLER; } int itemViewType = mDelegate.getItemViewType(adapterPosition.mPosition); if (itemViewType == IGNORE_ITEM_VIEW_TYPE) { return itemViewType; } return itemViewType + sNumViewTypes; } @Override public View getView(int position, View convertView, ViewGroup parent) { ReferenceView container = null; if (convertView instanceof ReferenceView) { // Unpack from reference view; container = (ReferenceView)convertView; convertView = container.getChildAt(0); } Position adapterPosition = translatePosition(position); if (adapterPosition.mPosition == POSITION_HEADER) { View v = getHeaderFillerView(adapterPosition.mHeader, convertView, parent); ((HeaderFillerView)v).setHeaderId(adapterPosition.mHeader); convertView = (View)v.getTag(); View header = mDelegate.getHeaderView(adapterPosition.mHeader, convertView, parent); v.setTag(header); convertView = v; } else if (adapterPosition.mPosition == POSITION_FILLER) { convertView = getFillerView(convertView, parent); } else { convertView = mDelegate.getView(adapterPosition.mPosition, convertView, parent); } // Wrap in reference view if not already. if (container == null) { container = new ReferenceView(mContext); } container.removeAllViews(); container.addView(convertView); container.setPosition(position); container.setNumColumns(mNumColumns); mRowSiblings[position % mNumColumns] = container; if (position % mNumColumns == 0) { sCurrentlySizingRow = true; for (int i = 1; i < mRowSiblings.length; i++) { mRowSiblings[i] = getView(position + i, null, parent); } sCurrentlySizingRow = false; } container.setRowSiblings(mRowSiblings); if (!sCurrentlySizingRow && (position % mNumColumns == (mNumColumns - 1) || position == getCount() - 1)) { // End of row or items. initRowSiblings(mNumColumns); } return container; } /** * @return the adapter wrapped by this adapter. */ public StickyGridHeadersBaseAdapter getWrappedAdapter() { return mDelegate; } @Override public int getViewTypeCount() { return mDelegate.getViewTypeCount() + sNumViewTypes; } @Override public boolean hasStableIds() { return mDelegate.hasStableIds(); } @Override public boolean isEmpty() { return mDelegate.isEmpty(); } @Override public boolean isEnabled(int position) { Position adapterPosition = translatePosition(position); if (adapterPosition.mPosition == POSITION_FILLER || adapterPosition.mPosition == POSITION_HEADER) { return false; } return mDelegate.isEnabled(adapterPosition.mPosition); } @Override public void registerDataSetObserver(DataSetObserver observer) { mDelegate.registerDataSetObserver(observer); } public void setNumColumns(int numColumns) { mNumColumns = numColumns; initRowSiblings(numColumns); // notifyDataSetChanged(); } @Override public void unregisterDataSetObserver(DataSetObserver observer) { mDelegate.unregisterDataSetObserver(observer); } private FillerView getFillerView(View convertView, ViewGroup parent) { FillerView fillerView = (FillerView)convertView; if (fillerView == null) { fillerView = new FillerView(mContext); } return fillerView; } private View getHeaderFillerView(int headerPosition, View convertView, ViewGroup parent) { HeaderFillerView headerFillerView = (HeaderFillerView)convertView; headerFillerView = new HeaderFillerView(mContext); - headerFillerView.setHeaderWidth(mDridView.getWidth()); + headerFillerView.setHeaderWidth(mGridView.getWidth()); return headerFillerView; } private void initRowSiblings(int numColumns) { mRowSiblings = new View[numColumns]; Arrays.fill(mRowSiblings, null); } /** * Counts the number of items that would be need to fill out the last row in * the group of items with the given header. * * @param header Header set of items are grouped by. * @return The count of unfilled spaces in the last row. */ private int unFilledSpacesInHeaderGroup(int header) { int remainder = mDelegate.getCountForHeader(header) % mNumColumns; return remainder == 0 ? 0 : mNumColumns - remainder; } protected long getHeaderId(int position) { return translatePosition(position).mHeader; } protected View getHeaderView(int position, View convertView, ViewGroup parent) { if (mDelegate.getNumHeaders() == 0) { return null; } return mDelegate.getHeaderView(translatePosition(position).mHeader, convertView, parent); } protected Position translatePosition(int position) { int numHeaders = mDelegate.getNumHeaders(); if (numHeaders == 0) { if (position >= mDelegate.getCount()) { return new Position(POSITION_FILLER, 0); } return new Position(position, 0); } // Translate GridView position to Adapter position. int adapterPosition = position; int place = position; int i; for (i = 0; i < numHeaders; i++) { int sectionCount = mDelegate.getCountForHeader(i); // Skip past fake items making space for header in front of // sections. if (place == 0) { // Position is first column where header will be. return new Position(POSITION_HEADER, i); } place -= mNumColumns; if (place < 0) { // Position is a fake so return null. return new Position(POSITION_FILLER, i); } adapterPosition -= mNumColumns; if (place < sectionCount) { return new Position(adapterPosition, i); } // Skip past section end of section row filler; int filler = unFilledSpacesInHeaderGroup(i); adapterPosition -= filler; place -= sectionCount + filler; } // Position is a fake. return new Position(POSITION_FILLER, i); } protected void updateCount() { mCount = 0; int numHeaders = mDelegate.getNumHeaders(); if (numHeaders == 0) { mCount = mDelegate.getCount(); return; } for (int i = 0; i < numHeaders; i++) { mCount += mDelegate.getCountForHeader(i) + mNumColumns; } } /** * Simple view to fill space in grid view. * * @author Tonic Artos */ protected class FillerView extends View { public FillerView(Context context) { super(context); } public FillerView(Context context, AttributeSet attrs) { super(context, attrs); } public FillerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } } /** * A view to hold the section header and measure the header row height * correctly. * * @author Tonic Artos */ protected class HeaderFillerView extends FrameLayout { private int mHeaderId; private int mHeaderWidth; public HeaderFillerView(Context context) { super(context); } public HeaderFillerView(Context context, AttributeSet attrs) { super(context, attrs); } public HeaderFillerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public int getHeaderId() { return mHeaderId; } /** * Set the adapter id for this header so we can easily pull it later. */ public void setHeaderId(int headerId) { mHeaderId = headerId; } public void setHeaderWidth(int width) { mHeaderWidth = width; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { View v = (View)getTag(); android.view.ViewGroup.LayoutParams params = v.getLayoutParams(); if (params == null) { v.setLayoutParams(generateDefaultLayoutParams()); } if (v.getVisibility() != View.GONE) { if (v.getMeasuredHeight() == 0) { v.measure(MeasureSpec.makeMeasureSpec(mHeaderWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec( 0, MeasureSpec.UNSPECIFIED)); } } setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), v.getMeasuredHeight()); } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } } protected class HeaderHolder { protected View mHeaderView; } protected class Position { protected int mHeader; protected int mPosition; protected Position(int position, int header) { mPosition = position; mHeader = header; } } /** * View to wrap adapter supplied views and ensure the row height is * correctly measured for the contents of all cells in the row. * <p> * Some mickymousing is required with the adapter wrapper. * <p> * Adopted and modified from code first detailed at <a * href="http://stackoverflow.com/a/13994344" * >http://stackoverflow.com/a/13994344</a> * * @author Anton Spaans, Tonic Artos */ protected class ReferenceView extends FrameLayout { private boolean mForceMeasureDisabled; private int mNumColumns; private int mPosition; private View[] mRowSiblings; public ReferenceView(Context context) { super(context); } public ReferenceView(Context context, AttributeSet attrs) { super(context, attrs); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public ReferenceView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public Object getTag() { return getChildAt(0).getTag(); } @Override public Object getTag(int key) { return getChildAt(0).getTag(key); } public View getView() { return getChildAt(0); } public void setNumColumns(int numColumns) { mNumColumns = numColumns; } public void setPosition(int position) { mPosition = position; } @SuppressLint("NewApi") public void setRowSiblings(View[] rowSiblings) { mRowSiblings = rowSiblings; } @Override public void setTag(int key, Object tag) { getChildAt(0).setTag(key, tag); } @Override public void setTag(Object tag) { getChildAt(0).setTag(tag); } /** * Forces measurement of entire row. Used to fix the case where the * first item in a row has been measured determining the row height for * scrolling upwards before any row siblings has been measured. * * @param widthMeasureSpec * @param heightMeasureSpec */ private void forceRowMeasurement(int widthMeasureSpec, int heightMeasureSpec) { if (mForceMeasureDisabled) { return; } mForceMeasureDisabled = true; for (View rowSibling : mRowSiblings) { rowSibling.measure(widthMeasureSpec, heightMeasureSpec); } mForceMeasureDisabled = false; } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (mNumColumns == 1 || StickyGridHeadersBaseAdapterWrapper.this.mRowSiblings == null) { return; } if (mPosition % mNumColumns == 0) { forceRowMeasurement(widthMeasureSpec, heightMeasureSpec); } int measuredHeight = getMeasuredHeight(); int maxHeight = measuredHeight; for (View rowSibling : mRowSiblings) { if (rowSibling != null) { maxHeight = Math.max(maxHeight, rowSibling.getMeasuredHeight()); } } if (maxHeight == measuredHeight) { return; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } }
false
false
null
null
diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java index 8002bb55f..a21e6a4cd 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java @@ -1,162 +1,163 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.compare.internal; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.viewers.Viewer; import org.eclipse.compare.*; import org.eclipse.compare.structuremergeviewer.*; import org.eclipse.compare.contentmergeviewer.IMergeViewerContentProvider; /** * Adapts any <code>ContentMergeViewer</code> to work on an <code>ICompareInput</code> * e.g. a <code>DiffNode</code>. */ public class MergeViewerContentProvider implements IMergeViewerContentProvider { private CompareConfiguration fCompareConfiguration; public MergeViewerContentProvider(CompareConfiguration cc) { fCompareConfiguration= cc; } public void dispose() { } public void inputChanged(Viewer v, Object o1, Object o2) { // we are not interested since we have no state } //---- ancestor public String getAncestorLabel(Object element) { return fCompareConfiguration.getAncestorLabel(element); } public Image getAncestorImage(Object element) { return fCompareConfiguration.getAncestorImage(element); } public Object getAncestorContent(Object element) { if (element instanceof ICompareInput) return ((ICompareInput) element).getAncestor(); return null; } public boolean showAncestor(Object element) { if (element instanceof ICompareInput) - return (((ICompareInput)element).getKind() & Differencer.DIRECTION_MASK) == Differencer.CONFLICTING; + return true; // fix for #45239: Show ancestor for incoming and outgoing changes + //return (((ICompareInput)element).getKind() & Differencer.DIRECTION_MASK) == Differencer.CONFLICTING; return false; } //---- left public String getLeftLabel(Object element) { return fCompareConfiguration.getLeftLabel(element); } public Image getLeftImage(Object element) { return fCompareConfiguration.getLeftImage(element); } public Object getLeftContent(Object element) { if (element instanceof ICompareInput) return ((ICompareInput) element).getLeft(); return null; } public boolean isLeftEditable(Object element) { if (element instanceof ICompareInput) { Object left= ((ICompareInput) element).getLeft(); if (left == null) { IDiffElement parent= ((IDiffElement)element).getParent(); if (parent instanceof ICompareInput) left= ((ICompareInput) parent).getLeft(); } if (left instanceof IEditableContent) return ((IEditableContent)left).isEditable(); } return false; } public void saveLeftContent(Object element, byte[] bytes) { if (element instanceof ICompareInput) { ICompareInput node= (ICompareInput) element; if (bytes != null) { ITypedElement left= node.getLeft(); // #9869: problem if left is null (because no resource exists yet) nothing is done! if (left == null) { node.copy(false); left= node.getLeft(); } if (left instanceof IEditableContent) ((IEditableContent)left).setContent(bytes); if (node instanceof ResourceCompareInput.MyDiffNode) ((ResourceCompareInput.MyDiffNode)node).fireChange(); } else { node.copy(false); } } } //---- right public String getRightLabel(Object element) { return fCompareConfiguration.getRightLabel(element); } public Image getRightImage(Object element) { return fCompareConfiguration.getRightImage(element); } public Object getRightContent(Object element) { if (element instanceof ICompareInput) return ((ICompareInput) element).getRight(); return null; } public boolean isRightEditable(Object element) { if (element instanceof ICompareInput) { Object right= ((ICompareInput) element).getRight(); if (right == null) { IDiffContainer parent= ((IDiffElement)element).getParent(); if (parent instanceof ICompareInput) right= ((ICompareInput) parent).getRight(); } if (right instanceof IEditableContent) return ((IEditableContent)right).isEditable(); } return false; } public void saveRightContent(Object element, byte[] bytes) { if (element instanceof ICompareInput) { ICompareInput node= (ICompareInput) element; if (bytes != null) { ITypedElement right= node.getRight(); // #9869: problem if right is null (because no resource exists yet) nothing is done! if (right == null) { node.copy(true); right= node.getRight(); } if (right instanceof IEditableContent) ((IEditableContent)right).setContent(bytes); if (node instanceof ResourceCompareInput.MyDiffNode) ((ResourceCompareInput.MyDiffNode)node).fireChange(); } else { node.copy(true); } } } } diff --git a/bundles/org.eclipse.compare/plugins/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java b/bundles/org.eclipse.compare/plugins/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java index 8002bb55f..a21e6a4cd 100644 --- a/bundles/org.eclipse.compare/plugins/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java +++ b/bundles/org.eclipse.compare/plugins/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeViewerContentProvider.java @@ -1,162 +1,163 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.compare.internal; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.viewers.Viewer; import org.eclipse.compare.*; import org.eclipse.compare.structuremergeviewer.*; import org.eclipse.compare.contentmergeviewer.IMergeViewerContentProvider; /** * Adapts any <code>ContentMergeViewer</code> to work on an <code>ICompareInput</code> * e.g. a <code>DiffNode</code>. */ public class MergeViewerContentProvider implements IMergeViewerContentProvider { private CompareConfiguration fCompareConfiguration; public MergeViewerContentProvider(CompareConfiguration cc) { fCompareConfiguration= cc; } public void dispose() { } public void inputChanged(Viewer v, Object o1, Object o2) { // we are not interested since we have no state } //---- ancestor public String getAncestorLabel(Object element) { return fCompareConfiguration.getAncestorLabel(element); } public Image getAncestorImage(Object element) { return fCompareConfiguration.getAncestorImage(element); } public Object getAncestorContent(Object element) { if (element instanceof ICompareInput) return ((ICompareInput) element).getAncestor(); return null; } public boolean showAncestor(Object element) { if (element instanceof ICompareInput) - return (((ICompareInput)element).getKind() & Differencer.DIRECTION_MASK) == Differencer.CONFLICTING; + return true; // fix for #45239: Show ancestor for incoming and outgoing changes + //return (((ICompareInput)element).getKind() & Differencer.DIRECTION_MASK) == Differencer.CONFLICTING; return false; } //---- left public String getLeftLabel(Object element) { return fCompareConfiguration.getLeftLabel(element); } public Image getLeftImage(Object element) { return fCompareConfiguration.getLeftImage(element); } public Object getLeftContent(Object element) { if (element instanceof ICompareInput) return ((ICompareInput) element).getLeft(); return null; } public boolean isLeftEditable(Object element) { if (element instanceof ICompareInput) { Object left= ((ICompareInput) element).getLeft(); if (left == null) { IDiffElement parent= ((IDiffElement)element).getParent(); if (parent instanceof ICompareInput) left= ((ICompareInput) parent).getLeft(); } if (left instanceof IEditableContent) return ((IEditableContent)left).isEditable(); } return false; } public void saveLeftContent(Object element, byte[] bytes) { if (element instanceof ICompareInput) { ICompareInput node= (ICompareInput) element; if (bytes != null) { ITypedElement left= node.getLeft(); // #9869: problem if left is null (because no resource exists yet) nothing is done! if (left == null) { node.copy(false); left= node.getLeft(); } if (left instanceof IEditableContent) ((IEditableContent)left).setContent(bytes); if (node instanceof ResourceCompareInput.MyDiffNode) ((ResourceCompareInput.MyDiffNode)node).fireChange(); } else { node.copy(false); } } } //---- right public String getRightLabel(Object element) { return fCompareConfiguration.getRightLabel(element); } public Image getRightImage(Object element) { return fCompareConfiguration.getRightImage(element); } public Object getRightContent(Object element) { if (element instanceof ICompareInput) return ((ICompareInput) element).getRight(); return null; } public boolean isRightEditable(Object element) { if (element instanceof ICompareInput) { Object right= ((ICompareInput) element).getRight(); if (right == null) { IDiffContainer parent= ((IDiffElement)element).getParent(); if (parent instanceof ICompareInput) right= ((ICompareInput) parent).getRight(); } if (right instanceof IEditableContent) return ((IEditableContent)right).isEditable(); } return false; } public void saveRightContent(Object element, byte[] bytes) { if (element instanceof ICompareInput) { ICompareInput node= (ICompareInput) element; if (bytes != null) { ITypedElement right= node.getRight(); // #9869: problem if right is null (because no resource exists yet) nothing is done! if (right == null) { node.copy(true); right= node.getRight(); } if (right instanceof IEditableContent) ((IEditableContent)right).setContent(bytes); if (node instanceof ResourceCompareInput.MyDiffNode) ((ResourceCompareInput.MyDiffNode)node).fireChange(); } else { node.copy(true); } } } }
false
false
null
null
diff --git a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java index 58da9fcf9..283df4e6c 100644 --- a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java +++ b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java @@ -1,428 +1,429 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.message; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.sip.B2buaHelper; import javax.servlet.sip.SipApplicationRoutingDirective; import javax.servlet.sip.SipServletMessage; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipSession; import javax.servlet.sip.UAMode; import javax.servlet.sip.SipSession.State; import javax.sip.ClientTransaction; import javax.sip.Dialog; import javax.sip.ServerTransaction; import javax.sip.Transaction; import javax.sip.TransactionState; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.ContentDispositionHeader; import javax.sip.header.ContentLengthHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.FromHeader; import javax.sip.header.Header; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.RecordRouteHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.core.SipApplicationDispatcherImpl; import org.mobicents.servlet.sip.core.session.SessionManager; import org.mobicents.servlet.sip.core.session.SipApplicationSessionImpl; import org.mobicents.servlet.sip.core.session.SipSessionImpl; import org.mobicents.servlet.sip.core.session.SipSessionKey; /** * Implementation of the B2BUA helper class. * * * @author mranga * @author Jean Deruelle */ public class B2buaHelperImpl implements B2buaHelper { private static Log logger = LogFactory.getLog(B2buaHelperImpl.class); protected static final HashSet<String> singletonHeadersNames = new HashSet<String>(); static { singletonHeadersNames.add(FromHeader.NAME); singletonHeadersNames.add(ToHeader.NAME); singletonHeadersNames.add(CSeqHeader.NAME); singletonHeadersNames.add(CallIdHeader.NAME); singletonHeadersNames.add(MaxForwardsHeader.NAME); singletonHeadersNames.add(ContentLengthHeader.NAME); singletonHeadersNames.add(ContentDispositionHeader.NAME); singletonHeadersNames.add(ContentTypeHeader.NAME); //TODO are there any other singleton headers ? } //FIXME @jean.deruelle session map is never cleaned up => could lead to memory leak //shall we have a thread scanning for invalid sessions and removing them accordingly ? //FIXME this is not a one to one mapping - B2BUA can link to more than one other sip session private Map<SipSessionImpl, SipSessionImpl> sessionMap = new ConcurrentHashMap<SipSessionImpl, SipSessionImpl>(); private SipFactoryImpl sipFactoryImpl; private SipServletRequestImpl sipServletRequest; /** * * @param sipFactoryImpl */ public B2buaHelperImpl(SipServletRequestImpl sipServletRequest) { this.sipServletRequest = sipServletRequest; this.sipFactoryImpl = sipServletRequest.sipFactoryImpl; } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#createRequest(javax.servlet.sip.SipServletRequest, boolean, java.util.Map) */ public SipServletRequest createRequest(SipServletRequest origRequest, boolean linked, Map<String, Set<String>> headerMap) throws IllegalArgumentException { try { SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest; Request newRequest = (Request) origRequestImpl.message.clone(); - newRequest.removeContent(); + //content should be copied too, so commented out +// newRequest.removeContent(); //removing the via header from original request ViaHeader viaHeader = (ViaHeader) newRequest .getHeader(ViaHeader.NAME); newRequest.removeHeader(ViaHeader.NAME); ((FromHeader) newRequest.getHeader(FromHeader.NAME)) .removeParameter("tag"); ((ToHeader) newRequest.getHeader(ToHeader.NAME)) .removeParameter("tag"); // Remove the route header ( will point to us ). newRequest.removeHeader(RouteHeader.NAME); String tag = Integer.toString((int) (Math.random()*1000)); ((FromHeader) newRequest.getHeader(FromHeader.NAME)).setParameter("tag", tag); // Remove the record route headers. This is a new call leg. newRequest.removeHeader(RecordRouteHeader.NAME); //For non-REGISTER requests, the Contact header field is not copied //but is populated by the container as usual newRequest.removeHeader(ContactHeader.NAME); //but If Contact header is present in the headerMap //then relevant portions of Contact header is to be used in the request created, //in accordance with section 4.1.3 of the specification. //They will be added later after the sip servlet request has been created Set<String> contactHeaderSet = new HashSet<String>(); if(headerMap != null) { for (String headerName : headerMap.keySet()) { if(!headerName.equalsIgnoreCase(ContactHeader.NAME)) { for (String value : headerMap.get(headerName)) { Header header = SipFactories.headerFactory.createHeader( headerName, value); if(! singletonHeadersNames.contains(header.getName())) { newRequest.addHeader(header); } else { newRequest.setHeader(header); } } } else { contactHeaderSet = headerMap.get(headerName); } } } SipSessionImpl originalSession = origRequestImpl.getSipSession(); SipApplicationSessionImpl appSession = originalSession .getSipApplicationSession(); SipSessionKey key = SessionManager.getSipSessionKey(originalSession.getKey().getApplicationName(), newRequest, false); SipSessionImpl session = sipFactoryImpl.getSessionManager().getSipSession(key, true, sipFactoryImpl, appSession); session.setHandler(originalSession.getHandler()); // appSession.setSipContext(session.getSipApplicationSession().getSipContext()); //since B2BUA is considered as an end point , it is normal to reinitialize //the via header chain ViaHeader newViaHeader = JainSipUtils.createViaHeader( sipFactoryImpl.getSipProviders(), viaHeader.getTransport(), null); newViaHeader.setParameter(SipApplicationDispatcherImpl.RR_PARAM_APPLICATION_NAME, session.getKey().getApplicationName()); newViaHeader.setParameter(SipApplicationDispatcherImpl.RR_PARAM_HANDLER_NAME, session.getHandler()); newRequest.setHeader(newViaHeader); SipServletRequestImpl newSipServletRequest = new SipServletRequestImpl( newRequest, sipFactoryImpl, session, null, null, JainSipUtils.dialogCreatingMethods.contains(newRequest.getMethod())); //JSR 289 Section 15.1.6 newSipServletRequest.setRoutingDirective(SipApplicationRoutingDirective.CONTINUE, origRequest); //If Contact header is present in the headerMap //then relevant portions of Contact header is to be used in the request created, //in accordance with section 4.1.3 of the specification. for (String contactHeaderValue : contactHeaderSet) { newSipServletRequest.addHeader(ContactHeader.NAME, contactHeaderValue); } if (linked) { sessionMap.put(originalSession, session); sessionMap.put(session, originalSession); } return newSipServletRequest; } catch (Exception ex) { logger.error("Unexpected exception ", ex); throw new IllegalArgumentException( "Illegal arg ecnountered while creatigng b2bua", ex); } } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#createRequest(javax.servlet.sip.SipSession, javax.servlet.sip.SipServletRequest, java.util.Map) */ public SipServletRequest createRequest(SipSession session, SipServletRequest origRequest, Map<String, Set<String>> headerMap) throws IllegalArgumentException { try { SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest; SipSessionImpl sessionImpl = (SipSessionImpl) session; Dialog dialog = sessionImpl.getSessionCreatingDialog(); Request newRequest = dialog.createRequest(((SipServletRequest) origRequest) .getMethod()); SipSessionImpl originalSession = origRequestImpl.getSipSession(); logger.info(origRequest.getSession()); logger.info(session); //For non-REGISTER requests, the Contact header field is not copied //but is populated by the container as usual newRequest.removeHeader(ContactHeader.NAME); //If Contact header is present in the headerMap //then relevant portions of Contact header is to be used in the request created, //in accordance with section 4.1.3 of the specification. //They will be added later after the sip servlet request has been created Set<String> contactHeaderSet = new HashSet<String>(); if(headerMap != null) { for (String headerName : headerMap.keySet()) { if(!headerName.equalsIgnoreCase(ContactHeader.NAME)) { for (String value : headerMap.get(headerName)) { Header header = SipFactories.headerFactory.createHeader( headerName, value); if(! singletonHeadersNames.contains(header.getName())) { newRequest.addHeader(header); } else { newRequest.setHeader(header); } } } else { contactHeaderSet = headerMap.get(headerName); } } } //we already have a dialog since it is a subsequent request SipServletRequestImpl newSipServletRequest = new SipServletRequestImpl( newRequest, sipFactoryImpl, session, sessionImpl.getSessionCreatingTransaction(), dialog, JainSipUtils.dialogCreatingMethods.contains(newRequest.getMethod())); //JSR 289 Section 15.1.6 newSipServletRequest.setRoutingDirective(SipApplicationRoutingDirective.CONTINUE, origRequest); //If Contact header is present in the headerMap //then relevant portions of Contact header is to be used in the request created, //in accordance with section 4.1.3 of the specification. for (String contactHeaderValue : contactHeaderSet) { newSipServletRequest.addHeader(ContactHeader.NAME, contactHeaderValue); } if(logger.isDebugEnabled()) { logger.debug("newRequest = " + newRequest); } sessionMap.put(originalSession, sessionImpl); sessionMap.put(sessionImpl, originalSession); return newSipServletRequest; } catch (Exception ex) { logger.error("Unexpected exception ", ex); throw new IllegalArgumentException( "Illegal arg ecnountered while creatigng b2bua", ex); } } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#createResponseToOriginalRequest(javax.servlet.sip.SipSession, int, java.lang.String) */ public SipServletResponse createResponseToOriginalRequest( SipSession session, int status, String reasonPhrase) { if (session == null) throw new NullPointerException("Null arg"); SipSessionImpl sipSession = (SipSessionImpl) session; Transaction trans = sipSession.getSessionCreatingTransaction(); if (!(trans instanceof ServerTransaction)) { throw new IllegalStateException( "Was expecting to find a server transaction "); } ServerTransaction st = (ServerTransaction) trans; Request request = st.getRequest(); try { Response response = SipFactories.messageFactory.createResponse( status, request); if (reasonPhrase != null) response.setReasonPhrase(reasonPhrase); ListIterator<RecordRouteHeader> recordRouteHeaders = request.getHeaders(RecordRouteHeader.NAME); while (recordRouteHeaders.hasNext()) { RecordRouteHeader recordRouteHeader = (RecordRouteHeader) recordRouteHeaders .next(); response.addHeader(recordRouteHeader); } if(status == Response.OK) { ContactHeader contactHeader = JainSipUtils.createContactForProvider(sipFactoryImpl.getSipProviders(), JainSipUtils.findTransport(request)); response.addHeader(contactHeader); } SipServletResponseImpl newSipServletResponse = new SipServletResponseImpl( response, sipFactoryImpl, st, sipSession, sipSession.getSessionCreatingDialog(), sipServletRequest); return newSipServletResponse; } catch (ParseException ex) { throw new IllegalArgumentException("bad input argument", ex); } } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#getLinkedSession(javax.servlet.sip.SipSession) */ public SipSession getLinkedSession(SipSession session) { if ( session == null )throw new NullPointerException("the argument is null"); if(!session.isValid()) { throw new IllegalArgumentException("the session is invalid"); } return this.sessionMap.get((SipSessionImpl) session ); } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#getLinkedSipServletRequest(javax.servlet.sip.SipServletRequest) */ public SipServletRequest getLinkedSipServletRequest(SipServletRequest req) { return ((SipServletRequestImpl)req).getLinkedRequest(); } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#getPendingMessages(javax.servlet.sip.SipSession, javax.servlet.sip.UAMode) */ public List<SipServletMessage> getPendingMessages(SipSession session, UAMode mode) { SipSessionImpl sipSessionImpl = (SipSessionImpl) session; List<SipServletMessage> retval = new ArrayList<SipServletMessage> (); if ( mode.equals(UAMode.UAC)) { for ( Transaction transaction: sipSessionImpl.getOngoingTransactions()) { if ( transaction instanceof ClientTransaction && transaction.getState() != TransactionState.TERMINATED) { TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); retval.add(tad.getSipServletMessage()); } } } else { for ( Transaction transaction: sipSessionImpl.getOngoingTransactions()) { if ( transaction instanceof ServerTransaction && transaction.getState() != TransactionState.TERMINATED) { TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); retval.add(tad.getSipServletMessage()); } } } return retval; } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#linkSipSessions(javax.servlet.sip.SipSession, javax.servlet.sip.SipSession) */ public void linkSipSessions(SipSession session1, SipSession session2) { if ( session1 == null )throw new NullPointerException("First argument is null"); if ( session2 == null )throw new NullPointerException("Second argument is null"); if(!session1.isValid() || !session2.isValid() || State.TERMINATED.equals(((SipSessionImpl)session1).getState()) || State.TERMINATED.equals(((SipSessionImpl)session2).getState()) || !session1.getApplicationSession().equals(session2.getApplicationSession()) || sessionMap.get(session1) != null || sessionMap.get(session2) != null) { throw new IllegalArgumentException("either of the specified sessions has been terminated " + "or the sessions do not belong to the same application session or " + "one or both the sessions are already linked with some other session(s)"); } this.sessionMap.put((SipSessionImpl)session1, (SipSessionImpl)session2); this.sessionMap.put((SipSessionImpl) session2, (SipSessionImpl) session1); } /* * (non-Javadoc) * @see javax.servlet.sip.B2buaHelper#unlinkSipSessions(javax.servlet.sip.SipSession) */ public void unlinkSipSessions(SipSession session) { if ( session == null )throw new NullPointerException("the argument is null"); if(!session.isValid() || State.TERMINATED.equals(((SipSessionImpl)session).getState()) || sessionMap.get(session) == null) { throw new IllegalArgumentException("the session is not currently linked to another session or it has been terminated"); } SipSessionImpl key = (SipSessionImpl) session; SipSessionImpl value = this.sessionMap.get(key); if ( value != null) this.sessionMap.remove(value); this.sessionMap.remove(key); } } diff --git a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletMessageImpl.java b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletMessageImpl.java index a0c2e370a..4d4b4d5ce 100644 --- a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletMessageImpl.java +++ b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletMessageImpl.java @@ -1,1488 +1,1491 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.message; import gov.nist.javax.sip.header.AddressParametersHeader; import gov.nist.javax.sip.header.SIPHeader; import gov.nist.javax.sip.header.ims.PathHeader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.security.Principal; import java.text.ParseException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Vector; import javax.servlet.sip.Address; import javax.servlet.sip.Parameterable; import javax.servlet.sip.ServletParseException; import javax.servlet.sip.SipApplicationSession; import javax.servlet.sip.SipServletMessage; import javax.servlet.sip.SipSession; import javax.sip.Dialog; import javax.sip.SipFactory; import javax.sip.Transaction; import javax.sip.header.AcceptLanguageHeader; import javax.sip.header.AlertInfoHeader; import javax.sip.header.AllowEventsHeader; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.CallInfoHeader; import javax.sip.header.ContactHeader; import javax.sip.header.ContentDispositionHeader; import javax.sip.header.ContentEncodingHeader; import javax.sip.header.ContentLanguageHeader; import javax.sip.header.ContentLengthHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.ErrorInfoHeader; import javax.sip.header.EventHeader; import javax.sip.header.ExpiresHeader; import javax.sip.header.FromHeader; import javax.sip.header.Header; import javax.sip.header.HeaderFactory; import javax.sip.header.RecordRouteHeader; import javax.sip.header.ReferToHeader; import javax.sip.header.ReplyToHeader; import javax.sip.header.RouteHeader; import javax.sip.header.SubjectHeader; import javax.sip.header.SupportedHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Message; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.catalina.realm.GenericPrincipal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.address.AddressImpl; import org.mobicents.servlet.sip.address.ParameterableHeaderImpl; import org.mobicents.servlet.sip.core.session.SessionManager; import org.mobicents.servlet.sip.core.session.SipApplicationSessionImpl; import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey; import org.mobicents.servlet.sip.core.session.SipSessionImpl; import org.mobicents.servlet.sip.core.session.SipSessionKey; import org.mobicents.servlet.sip.startup.SipContext; /** * Implementation of SipServletMessage * * @author mranga * */ public abstract class SipServletMessageImpl implements SipServletMessage { private static Log logger = LogFactory.getLog(SipServletMessageImpl.class .getCanonicalName()); private static final String CONTENT_TYPE_TEXT = "text"; protected Message message; protected SipFactoryImpl sipFactoryImpl; protected SipSessionImpl session; protected Map<String, Object> attributes = new HashMap<String, Object>(); private Transaction transaction; protected TransactionApplicationData transactionApplicationData; private static HeaderFactory headerFactory = SipFactories.headerFactory; protected String defaultEncoding = "UTF8"; protected HeaderForm headerForm = HeaderForm.DEFAULT; protected InetAddress localAddr = null; protected int localPort = -1; // IP address of the next upstream/downstream hop from which this message // was received. Applications can determine the actual IP address of the UA // that originated the message from the message Via header fields. // But for upstream - thats a proxy stuff, fun with ReqURI, RouteHeader protected InetAddress remoteAddr = null; protected int remotePort = -1; protected String transport = null; protected String currentApplicationName = null; protected Principal userPrincipal; /** * List of headers that ARE system at all times */ protected static final HashSet<String> systemHeaders = new HashSet<String>(); static { systemHeaders.add(FromHeader.NAME); systemHeaders.add(ToHeader.NAME); systemHeaders.add(CallIdHeader.NAME); systemHeaders.add(CSeqHeader.NAME); systemHeaders.add(ViaHeader.NAME); systemHeaders.add(RouteHeader.NAME); systemHeaders.add(RecordRouteHeader.NAME); systemHeaders.add(PathHeader.NAME); // This is system in messages other than REGISTER!!! ContactHeader.NAME // Contact is a system header field in messages other than REGISTER // requests and responses, 3xx and 485 responses, and 200/OPTIONS // responses. Additionally, for containers implementing the reliable // provisional responses extension, RAck and RSeq are considered system // headers also. } protected static final HashSet<String> addressHeadersNames = new HashSet<String>(); static { // The baseline SIP specification defines the following set of header // fields that conform to this grammar: From, To, Contact, Route, // Record-Route, Reply-To, Alert-Info, Call-Info, and Error-Info addressHeadersNames.add(FromHeader.NAME); addressHeadersNames.add(ToHeader.NAME); addressHeadersNames.add(ContactHeader.NAME); addressHeadersNames.add(RouteHeader.NAME); addressHeadersNames.add(RecordRouteHeader.NAME); addressHeadersNames.add(ReplyToHeader.NAME); addressHeadersNames.add(AlertInfoHeader.NAME); addressHeadersNames.add(CallInfoHeader.NAME); addressHeadersNames.add(ErrorInfoHeader.NAME); } protected static final HashMap<String, String> headerCompact2FullNamesMappings = new HashMap<String, String>(); { // http://www.iana.org/assignments/sip-parameters // Header Name compact Reference // ----------------- ------- --------- // Call-ID i [RFC3261] // From f [RFC3261] // To t [RFC3261] // Via v [RFC3261] // =========== NON SYSTEM HEADERS ======== // Contact m [RFC3261] <-- Possibly system header // Accept-Contact a [RFC3841] // Allow-Events u [RFC3265] // Content-Encoding e [RFC3261] // Content-Length l [RFC3261] // Content-Type c [RFC3261] // Event o [RFC3265] // Identity y [RFC4474] // Identity-Info n [RFC4474] // Refer-To r [RFC3515] // Referred-By b [RFC3892] // Reject-Contact j [RFC3841] // Request-Disposition d [RFC3841] // Session-Expires x [RFC4028] // Subject s [RFC3261] // Supported k [RFC3261] headerCompact2FullNamesMappings.put("i", CallIdHeader.NAME); headerCompact2FullNamesMappings.put("f", FromHeader.NAME); headerCompact2FullNamesMappings.put("t", ToHeader.NAME); headerCompact2FullNamesMappings.put("v", ViaHeader.NAME); headerCompact2FullNamesMappings.put("m", ContactHeader.NAME); // headerCompact2FullNamesMappings.put("a",); // Where is this header? headerCompact2FullNamesMappings.put("u", AllowEventsHeader.NAME); headerCompact2FullNamesMappings.put("e", ContentEncodingHeader.NAME); headerCompact2FullNamesMappings.put("l", ContentLengthHeader.NAME); headerCompact2FullNamesMappings.put("c", ContentTypeHeader.NAME); headerCompact2FullNamesMappings.put("o", EventHeader.NAME); // headerCompact2FullNamesMappings.put("y", IdentityHeader); // Where is // sthis header? // headerCompact2FullNamesMappings.put("n",IdentityInfoHeader ); headerCompact2FullNamesMappings.put("r", ReferToHeader.NAME); // headerCompact2FullNamesMappings.put("b", ReferedByHeader); // headerCompact2FullNamesMappings.put("j", RejectContactHeader); headerCompact2FullNamesMappings.put("d", ContentDispositionHeader.NAME); // headerCompact2FullNamesMappings.put("x", SessionExpiresHeader); headerCompact2FullNamesMappings.put("s", SubjectHeader.NAME); headerCompact2FullNamesMappings.put("k", SupportedHeader.NAME); } protected static final HashMap<String, String> headerFull2CompactNamesMappings = new HashMap<String, String>(); static { // http://www.iana.org/assignments/sip-parameters // Header Name compact Reference // ----------------- ------- --------- // Call-ID i [RFC3261] // From f [RFC3261] // To t [RFC3261] // Via v [RFC3261] // =========== NON SYSTEM HEADERS ======== // Contact m [RFC3261] <-- Possibly system header // Accept-Contact a [RFC3841] // Allow-Events u [RFC3265] // Content-Encoding e [RFC3261] // Content-Length l [RFC3261] // Content-Type c [RFC3261] // Event o [RFC3265] // Identity y [RFC4474] // Identity-Info n [RFC4474] // Refer-To r [RFC3515] // Referred-By b [RFC3892] // Reject-Contact j [RFC3841] // Request-Disposition d [RFC3841] // Session-Expires x [RFC4028] // Subject s [RFC3261] // Supported k [RFC3261] headerFull2CompactNamesMappings.put(CallIdHeader.NAME, "i"); headerFull2CompactNamesMappings.put(FromHeader.NAME, "f"); headerFull2CompactNamesMappings.put(ToHeader.NAME, "t"); headerFull2CompactNamesMappings.put(ViaHeader.NAME, "v"); headerFull2CompactNamesMappings.put(ContactHeader.NAME, "m"); // headerFull2CompactNamesMappings.put(,"a"); // Where is this header? headerFull2CompactNamesMappings.put(AllowEventsHeader.NAME, "u"); headerFull2CompactNamesMappings.put(ContentEncodingHeader.NAME, "e"); headerFull2CompactNamesMappings.put(ContentLengthHeader.NAME, "l"); headerFull2CompactNamesMappings.put(ContentTypeHeader.NAME, "c"); headerFull2CompactNamesMappings.put(EventHeader.NAME, "o"); // headerCompact2FullNamesMappings.put(IdentityHeader,"y"); // Where is // sthis header? // headerCompact2FullNamesMappings.put(IdentityInfoHeader ,"n"); headerFull2CompactNamesMappings.put(ReferToHeader.NAME, "r"); // headerCompact2FullNamesMappings.put(ReferedByHeader,"b"); // headerCompact2FullNamesMappings.put(RejectContactHeader,"j"); headerFull2CompactNamesMappings.put(ContentDispositionHeader.NAME, "d"); // headerCompact2FullNamesMappings.put(SessionExpiresHeader,"x"); headerFull2CompactNamesMappings.put(SubjectHeader.NAME, "s"); headerFull2CompactNamesMappings.put(SupportedHeader.NAME, "k"); } protected SipServletMessageImpl(Message message, SipFactoryImpl sipFactoryImpl, Transaction transaction, SipSession sipSession, Dialog dialog) { if (sipFactoryImpl == null) throw new NullPointerException("Null factory"); if (message == null) throw new NullPointerException("Null message"); // if (sipSession == null) // throw new NullPointerException("Null session"); this.sipFactoryImpl = sipFactoryImpl; this.message = message; this.transaction = transaction; this.session = (SipSessionImpl) sipSession; this.transactionApplicationData = new TransactionApplicationData(this); if(sipSession != null && dialog != null) { session.setSessionCreatingDialog(dialog); if(dialog.getApplicationData() == null) { dialog.setApplicationData(transactionApplicationData); } } // good behaviour, lets make some default - if (this.message.getContentEncoding() == null) - try { - this.message.addHeader(this.headerFactory - .createContentEncodingHeader(this.defaultEncoding)); - } catch (ParseException e) { - logger.debug("Couldnt add deafualt enconding..."); - e.printStackTrace(); - } + //seems like bad behavior finally + //check http://forums.java.net/jive/thread.jspa?messageID=260944 + // => commented out +// if (this.message.getContentEncoding() == null) +// try { +// this.message.addHeader(this.headerFactory +// .createContentEncodingHeader(this.defaultEncoding)); +// } catch (ParseException e) { +// logger.debug("Couldnt add deafualt enconding..."); +// e.printStackTrace(); +// } if (transaction != null && transaction.getApplicationData() == null) transaction.setApplicationData(transactionApplicationData); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#addAcceptLanguage(java.util.Locale) */ public void addAcceptLanguage(Locale locale) { AcceptLanguageHeader ach = headerFactory .createAcceptLanguageHeader(locale); message.addHeader(ach); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#addAddressHeader(java.lang.String, javax.servlet.sip.Address, boolean) */ public void addAddressHeader(String name, Address addr, boolean first) throws IllegalArgumentException { String hName = getFullHeaderName(name); if (logger.isDebugEnabled()) logger.debug("Adding address header [" + hName + "] as first [" + first + "] value [" + addr + "]"); if (!isAddressTypeHeader(hName)) { logger.error("Header [" + hName + "] is nto address type header"); throw new IllegalArgumentException("Header[" + hName + "] is not of an address type"); } if (isSystemHeader(hName)) { logger.error("Error, cant add ssytem header [" + hName + "]"); throw new IllegalArgumentException("Header[" + hName + "] is system header, cant add, modify it!!!"); } try { String nameToAdd = getCorrectHeaderName(hName); Header h = headerFactory.createHeader(nameToAdd, addr.toString()); if (first) { this.message.addFirst(h); } else { this.message.addLast(h); } } catch (Exception e) { throw new IllegalArgumentException("Error adding header", e); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#addHeader(java.lang.String, java.lang.String) */ public void addHeader(String name, String value) { String hName = getFullHeaderName(name); if (logger.isDebugEnabled()) logger.debug("Adding header under name [" + hName + "]"); if (isSystemHeader(hName)) { logger.error("Cant add system header [" + hName + "]"); throw new IllegalArgumentException("Header[" + hName + "] is system header, cant add,cant modify it!!!"); } String nameToAdd = getCorrectHeaderName(hName); try { Header header = SipFactories.headerFactory.createHeader(nameToAdd, value); this.message.addLast(header); } catch (Exception ex) { throw new IllegalArgumentException("Illegal args supplied ", ex); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#addParameterableHeader(java.lang.String, javax.servlet.sip.Parameterable, boolean) */ public void addParameterableHeader(String name, Parameterable param, boolean first) { try { String hName = getFullHeaderName(name); if (logger.isDebugEnabled()) logger.debug("Adding parametrable header under name [" + hName + "] as first [" + first + "] value [" + param + "]"); String body = param.toString(); String nameToAdd = getCorrectHeaderName(hName); Header header = SipFactories.headerFactory.createHeader(nameToAdd, body); if (first) this.message.addFirst(header); else this.message.addLast(header); } catch (Exception ex) { throw new IllegalArgumentException("Illegal args supplied"); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getAcceptLanguage() */ public Locale getAcceptLanguage() { AcceptLanguageHeader alh = (AcceptLanguageHeader) this.message .getHeader(AcceptLanguageHeader.NAME); if (alh == null) return null; else return alh.getAcceptLanguage(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getAcceptLanguages() */ public Iterator<Locale> getAcceptLanguages() { LinkedList<Locale> ll = new LinkedList<Locale>(); Iterator<Header> it = (Iterator<Header>) this.message .getHeaders(AcceptLanguageHeader.NAME); while (it.hasNext()) { AcceptLanguageHeader alh = (AcceptLanguageHeader) it.next(); ll.add(alh.getAcceptLanguage()); } return ll.iterator(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getAddressHeader(java.lang.String) */ @SuppressWarnings("unchecked") public Address getAddressHeader(String name) throws ServletParseException { if (name == null) throw new NullPointerException(); String hName = getFullHeaderName(name); if (logger.isDebugEnabled()) logger.debug("Fetching address header for name [" + hName + "]"); if (!isAddressTypeHeader(hName)) { logger.error("Header of name [" + hName + "] is not address type header!!!"); throw new ServletParseException("Header of type [" + hName + "] cant be parsed to address, wrong content type!!!"); } String nameToSearch = getCorrectHeaderName(hName); ListIterator<Header> headers = (ListIterator<Header>) this.message .getHeaders(nameToSearch); ListIterator<Header> lit = headers; if (lit != null) { Header first = lit.next(); if (first instanceof AddressParametersHeader) { try { return new AddressImpl((AddressParametersHeader) first); } catch (ParseException e) { throw new ServletParseException("Bad address " + first); } } } return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getAddressHeaders(java.lang.String) */ @SuppressWarnings("unchecked") public ListIterator<Address> getAddressHeaders(String name) throws ServletParseException { String hName = getFullHeaderName(name); if (isAddressTypeHeader(hName)) { throw new IllegalArgumentException( "Header is not address type header"); } LinkedList<Address> retval = new LinkedList<Address>(); String nameToSearch = getCorrectHeaderName(hName); for (Iterator<Header> it = this.message.getHeaders(nameToSearch); it .hasNext();) { Header header = (Header) it.next(); if (header instanceof AddressParametersHeader) { AddressParametersHeader aph = (AddressParametersHeader) header; try { AddressImpl addressImpl = new AddressImpl( (AddressParametersHeader) aph); retval.add(addressImpl); } catch (ParseException ex) { throw new ServletParseException("Bad header", ex); } } } return retval.listIterator(); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipServletMessage#getApplicationSession() */ public SipApplicationSession getApplicationSession() { return getApplicationSession(true); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipServletMessage#getApplicationSession(boolean) */ public SipApplicationSession getApplicationSession(boolean create) { if (this.session != null && this.session.getApplicationSession() != null) { return this.session.getApplicationSession(); } else if (create) { SipContext sipContext = sipFactoryImpl.getSipApplicationDispatcher().findSipApplication(currentApplicationName); SipApplicationSessionKey key = SessionManager.getSipApplicationSessionKey( currentApplicationName, ((CallIdHeader)message.getHeader((CallIdHeader.NAME))).getCallId()); SipApplicationSessionImpl applicationSession = sipFactoryImpl.getSessionManager().getSipApplicationSession(key, create, sipContext); if(this.session == null) { SipSessionKey sessionKey = SessionManager.getSipSessionKey(currentApplicationName, message, false); this.session = sipFactoryImpl.getSessionManager().getSipSession(sessionKey, create, sipFactoryImpl, applicationSession); this.session.setSessionCreatingTransaction(transaction); } // this.session.setSipApplicationSession(applicationSession); return this.session.getApplicationSession(); } return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getAttribute(java.lang.String) */ public Object getAttribute(String name) { if (name == null) throw new NullPointerException("Attribute name can not be null."); return this.attributes.get(name); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getAttributeNames() */ public Enumeration<String> getAttributeNames() { Vector<String> names = new Vector<String>(this.attributes.keySet()); return names.elements(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getCallId() */ public String getCallId() { CallIdHeader id = (CallIdHeader) this.message .getHeader(getCorrectHeaderName(CallIdHeader.NAME)); if (id != null) return id.getCallId(); else return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getCharacterEncoding() */ public String getCharacterEncoding() { if (this.message.getContentEncoding() != null) return this.message.getContentEncoding().getEncoding(); else return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getContent() */ public Object getContent() throws IOException, UnsupportedEncodingException { ContentTypeHeader contentTypeHeader = (ContentTypeHeader) this.message.getHeader(ContentTypeHeader.NAME); if(contentTypeHeader!= null && CONTENT_TYPE_TEXT.equals(contentTypeHeader.getContentType())) { String content = null; if(message.getRawContent() != null) { content = new String(message.getRawContent()); } else { content = new String(); } return content; } else { return this.message.getContent(); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getContent(java.lang.Class[]) */ public Object getContent(Class[] classes) throws IOException, UnsupportedEncodingException { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getContentLanguage() */ public Locale getContentLanguage() { if (this.message.getContentLanguage() != null) return this.message.getContentLanguage().getContentLanguage(); else return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getContentLength() */ public int getContentLength() { if (this.message.getContent() != null && this.message.getContentLength() != null) return this.message.getContentLength().getContentLength(); else return 0; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getContentType() */ public String getContentType() { ContentTypeHeader cth = (ContentTypeHeader) this.message .getHeader(getCorrectHeaderName(ContentTypeHeader.NAME)); if (cth != null) { String contentType = cth.getContentType(); String contentSubType = cth.getContentSubType(); if(contentSubType != null) return contentType + "/" + contentSubType; return contentType; } else return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getExpires() */ public int getExpires() { if (this.message.getExpires() != null) return this.message.getExpires().getExpires(); else return -1; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getFrom() */ public Address getFrom() { // AddressImpl enforces immutability!! FromHeader from = (FromHeader) this.message .getHeader(getCorrectHeaderName(FromHeader.NAME)); AddressImpl address = new AddressImpl(from.getAddress()); return address; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getHeader(java.lang.String) */ public String getHeader(String name) { String nameToSearch = getCorrectHeaderName(name); if (this.message.getHeader(nameToSearch) != null) return ((SIPHeader) this.message.getHeader(nameToSearch)) .getHeaderValue(); else return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getHeaderForm() */ public HeaderForm getHeaderForm() { return this.headerForm; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getHeaderNames() */ public Iterator<String> getHeaderNames() { return this.message.getHeaderNames(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getHeaders(java.lang.String) */ public ListIterator<String> getHeaders(String name) { String nameToSearch = getCorrectHeaderName(name); ArrayList<String> result = new ArrayList<String>(); try { ListIterator<Header> list = this.message.getHeaders(nameToSearch); while (list.hasNext()) { Header h = list.next(); result.add(h.toString()); } } catch (Exception e) { logger.fatal("Couldnt fetch headers, original name[" + name + "], name searched[" + nameToSearch + "]", e); return result.listIterator(); } return result.listIterator(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getLocalAddr() */ public String getLocalAddr() { if (this.localAddr == null) return null; else return this.localAddr.getHostAddress(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getLocalPort() */ public int getLocalPort() { return this.localPort; } /* * (non-Javadoc) * * @see javax.servlet.sip.SipServletMessage#getMethod() */ public String getMethod() { return message instanceof Request ? ((Request) message).getMethod() : ((CSeqHeader) message.getHeader(CSeqHeader.NAME)).getMethod(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getParameterableHeader(java.lang.String) */ public Parameterable getParameterableHeader(String name) throws ServletParseException { // FIXME:javadoc does not say that this object has to imply // immutability, thats wierds // as it suggests that its just a copy.... arghhhhhhhhhhh if (name == null) throw new NullPointerException( "Parametrable header name cant be null!!!"); String nameToSearch = getCorrectHeaderName(name); Header h = this.message.getHeader(nameToSearch); return createParameterable(h.toString(), getFullHeaderName(name)); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getParameterableHeaders(java.lang.String) */ public ListIterator<Parameterable> getParameterableHeaders(String name) throws ServletParseException { ListIterator<Header> headers = this.message .getHeaders(getCorrectHeaderName(name)); ArrayList<Parameterable> result = new ArrayList<Parameterable>(); while (headers.hasNext()) result.add(createParameterable(headers.next().toString(), getFullHeaderName(name))); return result.listIterator(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getProtocol() */ public String getProtocol() { // For this version of the SIP Servlet API this is always "SIP/2.0" return "SIP/2.0"; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getRawContent() */ public byte[] getRawContent() throws IOException { if (message != null) return message.getRawContent(); else return null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getRemoteAddr() */ public String getRemoteAddr() { // FIXME: Ambigious description!!!! // But: that originated the message from the message Via header fields. // or we have to play in proxy stuff - but thats insane!!!! - we will // stick to Via only... ;/ // So for reqeust it will be top via // For response Via ontop of local host ? if (this.remoteAddr == null) { // If its null it means that transport level info has not been // set... ;/ if (this.message instanceof Response) { // FIXME:.... return null; } else { // isntanceof Reqeust ListIterator<ViaHeader> vias = this.message .getHeaders(getCorrectHeaderName(ViaHeader.NAME)); if (vias.hasNext()) { ViaHeader via = vias.next(); return via.getHost(); } else { // those ethods return null; } } } else { return this.remoteAddr.getHostAddress(); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getRemotePort() */ public int getRemotePort() { return this.remotePort; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getRemoteUser() */ public String getRemoteUser() { // This method returns non-null only if the user is authenticated if(this.userPrincipal != null) return this.userPrincipal.getName(); return null; } /* * (non-Javadoc) * * @see javax.servlet.sip.SipServletMessage#getSession() */ public SipSession getSession() { return getSession(true); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipServletMessage#getSession(boolean) */ public SipSession getSession(boolean create) { if (this.session == null && create) { SipSessionKey sessionKey = SessionManager.getSipSessionKey(currentApplicationName, message, false); this.session = sipFactoryImpl.getSessionManager().getSipSession(sessionKey, create, sipFactoryImpl, (SipApplicationSessionImpl)getApplicationSession(create)); this.session.setSessionCreatingTransaction(transaction); } return this.session; } /** * Retrieve the sip session implementation * @return the sip session implementation */ public SipSessionImpl getSipSession() { return session; } /** * @param session the session to set */ public void setSipSession(SipSessionImpl session) { this.session = session; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getTo() */ public Address getTo() { return new AddressImpl(((ToHeader) this.message .getHeader(getCorrectHeaderName(ToHeader.NAME))).getAddress()); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getTransport() */ public String getTransport() { return this.transport; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#getUserPrincipal() */ public Principal getUserPrincipal() { if(this.userPrincipal == null) { if(this.getSipSession() != null) { this.userPrincipal = this.getSipSession().getUserPrincipal(); } } return this.userPrincipal; } public void setUserPrincipal(Principal principal) { this.userPrincipal = principal; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#isCommitted() */ public boolean isCommitted() { return this.transaction.getState() != null; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#isSecure() */ public boolean isSecure() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#isUserInRole(java.lang.String) */ public boolean isUserInRole(String role) { if(this.userPrincipal != null) { return ((GenericPrincipal)this.userPrincipal).hasRole(role); } return false; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { this.attributes.remove(name); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#removeHeader(java.lang.String) */ public void removeHeader(String name) { String hName = getFullHeaderName(name); if (isSystemHeader(hName)) { throw new IllegalArgumentException("Cant remove system header[" + hName + "]"); } String nameToSearch = getCorrectHeaderName(hName); this.message.removeHeader(nameToSearch); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#send() */ public abstract void send(); /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setAcceptLanguage(java.util.Locale) */ public void setAcceptLanguage(Locale locale) { AcceptLanguageHeader alh = headerFactory .createAcceptLanguageHeader(locale); this.message.addHeader(alh); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setAddressHeader(java.lang.String, javax.servlet.sip.Address) */ public void setAddressHeader(String name, Address addr) { String hName = getFullHeaderName(name); if (logger.isDebugEnabled()) logger.debug("Setting address header [" + name + "] to value [" + addr + "]"); if (isSystemHeader(hName)) { logger.error("Error, cant remove system header [" + hName + "]"); throw new IllegalArgumentException( "Cant set system header, it is maintained by container!!"); } if (!isAddressTypeHeader(hName)) { logger.error("Error, set header, its not address type header [" + hName + "]!!"); throw new IllegalArgumentException( "This header is not address type header"); } Header h; String headerNameToAdd = getCorrectHeaderName(hName); try { h = SipFactories.headerFactory.createHeader(headerNameToAdd, addr .toString()); this.message.setHeader(h); } catch (ParseException e) { logger.error("Parsing problem while setting address header with name " + name + " and address "+ addr, e); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setAttribute(java.lang.String, java.lang.Object) */ public void setAttribute(String name, Object o) { if (name == null) throw new NullPointerException("Attribute name can not be null."); this.attributes.put(name, o); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setCharacterEncoding(java.lang.String) */ public void setCharacterEncoding(String enc) { try { this.message.setContentEncoding(SipFactories.headerFactory .createContentEncodingHeader(ContentEncodingHeader.NAME + ":" + enc)); } catch (Exception ex) { throw new IllegalArgumentException("Unsupported encoding", ex); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setContent(java.lang.Object, java.lang.String) */ public void setContent(Object content, String contentType) throws UnsupportedEncodingException { if(contentType != null && contentType.length() > 0) { String type = contentType.split("/")[0]; String subtype = contentType.split("/")[1]; try { ContentTypeHeader contentTypeHeader = SipFactories.headerFactory.createContentTypeHeader(type, subtype); this.message.setContent(content, contentTypeHeader); } catch (Exception e) { throw new RuntimeException("Parse error reading content type", e); } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setContentLanguage(java.util.Locale) */ public void setContentLanguage(Locale locale) { ContentLanguageHeader contentLanguageHeader = SipFactories.headerFactory.createContentLanguageHeader(locale); this.message.setContentLanguage(contentLanguageHeader); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setContentLength(int) */ public void setContentLength(int len) { // this.message.setContentLength(new ContentLength(len)); String name = getCorrectHeaderName(ContentLengthHeader.NAME); this.message.removeHeader(name); try { Header h = headerFactory.createHeader(name, len + ""); this.message.addHeader(h); } catch (ParseException e) { // Shouldnt happen ? logger.error("Error while setting content length header !!!", e); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setContentType(java.lang.String) */ public void setContentType(String type) { String name = getCorrectHeaderName(ContentTypeHeader.NAME); try { Header h = headerFactory.createHeader(name, type); this.message .removeHeader(getCorrectHeaderName(ContentTypeHeader.NAME)); this.message.addHeader(h); } catch (ParseException e) { logger.error("Error while setting content type header !!!", e); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setExpires(int) */ public void setExpires(int seconds) { try { ExpiresHeader expiresHeader = SipFactories.headerFactory.createExpiresHeader(seconds); expiresHeader.setExpires(seconds); this.message.setExpires(expiresHeader); } catch (Exception e) { throw new RuntimeException("Error setting expiration header!", e); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setHeader(java.lang.String, java.lang.String) */ public void setHeader(String name, String value) { try { Header header = SipFactory.getInstance().createHeaderFactory() .createHeader(name, value); this.message.setHeader(header); } catch (Exception e) { throw new RuntimeException("Error creating header!", e); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setHeaderForm(javax.servlet.sip.SipServletMessage.HeaderForm) */ public void setHeaderForm(HeaderForm form) { // When form changes to HeaderForm.COMPACT or HeaderForm.LONG - all // names must transition, if it is changed to HeaderForm.DEFAULT, no // action is performed if(form == HeaderForm.DEFAULT) return; if(form == HeaderForm.COMPACT) { //TODO If header has compact name - we must change name to compact, if not, its left as it is. } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#setParameterableHeader(java.lang.String, javax.servlet.sip.Parameterable) */ public void setParameterableHeader(String name, Parameterable param) { // TODO Auto-generated method stub } /** * Applications must not add, delete, or modify so-called "system" headers. * These are header fields that the servlet container manages: From, To, * Call-ID, CSeq, Via, Route (except through pushRoute), Record-Route. * Contact is a system header field in messages other than REGISTER requests * and responses, 3xx and 485 responses, and 200/OPTIONS responses. * Additionally, for containers implementing the reliable provisional * responses extension, RAck and RSeq are considered system headers also. * * This method should return true if passed name - full or compact is name * of system header in context of this message. Each subclass has to * implement it in the manner that it conforms to semantics of wrapping * class * * @param headerName - * either long or compact header name * @return */ public abstract boolean isSystemHeader(String headerName); /** * This method checks if passed name is name of address type header - * according to rfc 3261 * * @param headerName - * name of header - either full or compact * @return */ public static boolean isAddressTypeHeader(String headerName) { return addressHeadersNames.contains(getFullHeaderName(headerName)); } /** * This method tries to resolve header name - meaning if it is compact - it * returns full name, if its not, it returns passed value. * * @param headerName * @return */ public static String getFullHeaderName(String headerName) { String fullName = null; if (headerCompact2FullNamesMappings.containsKey(headerName)) { fullName = headerCompact2FullNamesMappings.get(headerName); } else { fullName = headerName; } if (logger.isDebugEnabled()) logger.debug("Fetching full header name for [" + headerName + "] returning [" + fullName + "]"); return fullName; } /** * This method tries to determine compact header name - if passed value is * compact form it is returned, otherwise method tries to find compact name - * if it is found, string rpresenting compact name is returned, otherwise * null!!! * * @param headerName * @return */ public static String getCompactName(String headerName) { String compactName = null; if (headerCompact2FullNamesMappings.containsKey(headerName)) { compactName = headerCompact2FullNamesMappings.get(headerName); } else { // This can be null if there is no mapping!!! compactName = headerFull2CompactNamesMappings.get(headerName); } if (logger.isDebugEnabled()) logger.debug("Fetching compact header name for [" + headerName + "] returning [" + compactName + "]"); return compactName; } public String getCorrectHeaderName(String name) { // Mostly irritating - why this doesnt work? // switch(this._headerForm) // { // case HeaderForm.DEFAULT: // return name; // break;; // } return this.getCorrectHeaderName(name, this.headerForm); } public String getCorrectHeaderName(String name, HeaderForm form) { if (form == HeaderForm.DEFAULT) { return name; } else if (form == HeaderForm.COMPACT) { String compact = getCompactName(name); if (compact != null) return compact; else return name; } else if (form == HeaderForm.LONG) { return getFullHeaderName(name); } else { // ERROR ? - this shouldnt happen throw new IllegalStateException( "No default form of a header set!!!"); } } public Transaction getTransaction() { return this.transaction; } /* * (non-Javadoc) * @see java.lang.Object#clone() */ @Override protected Object clone() throws CloneNotSupportedException { // FIXME return super.clone(); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return this.message.toString(); } protected void setTransactionApplicationData( TransactionApplicationData applicationData) { this.transactionApplicationData = applicationData; } public TransactionApplicationData getTransactionApplicationData() { return this.transactionApplicationData; } public Message getMessage() { return message; } public Dialog getDialog() { if (this.transaction != null) return this.transaction.getDialog(); else return null; } /** * @param transaction * the transaction to set */ public void setTransaction(Transaction transaction) { this.transaction = transaction; } // TRANSPORT LEVEL, TO BE SET WHEN THIS IS RECEIVED public void setLocalAddr(InetAddress localAddr) { this.localAddr = localAddr; } public void setLocalPort(int localPort) { this.localPort = localPort; } public void setRemoteAddr(InetAddress remoteAddr) { this.remoteAddr = remoteAddr; } public void setRemotePort(int remotePort) { this.remotePort = remotePort; } public void setTransport(String transport) { this.transport = transport; } private Parameterable createParameterable(String whole, String hName) throws ServletParseException { // FIXME: Not sure if this is correct ;/ Ranga? if (logger.isDebugEnabled()) logger.debug("Creating parametrable for [" + hName + "] from [" + whole + "]"); // Remove name String stringHeader = whole.substring(whole.indexOf(":") + 1).trim(); if (!stringHeader.contains("<") || !stringHeader.contains(">") || !isParameterable(getFullHeaderName(hName))) { logger .error("Cant create parametrable - argument doesnt contain uri part, which it has to have!!!"); throw new ServletParseException("Header[" + hName + "] is not parametrable"); } // FIXME: This can be wrong ;/ Couldnt find list of parameterable // headers stringHeader.replace("<", ""); String[] split = stringHeader.split(">"); String value = split[0]; Map<String, String> paramMap = new HashMap<String, String>(); if (split[1].contains(";")) { // repleace first ";" with "" split[1] = split[1].replaceFirst(";", ""); split = split[1].split(";"); for (String pair : split) { String[] vals = pair.split("="); if (vals.length != 2) { logger .error("Wrong parameter format, expected value and name, got [" + pair + "]"); throw new ServletParseException( "Wrong parameter format, expected value or name[" + pair + "]"); } paramMap.put(vals[0], vals[1]); } } ParameterableHeaderImpl parameterable = new ParameterableHeaderImpl( value, paramMap); return parameterable; } public static boolean isParameterable(String hName) { // FIXME: Add cehck? return true; } /** * @return the currentApplicationName */ public String getCurrentApplicationName() { return currentApplicationName; } /** * @param currentApplicationName the currentApplicationName to set */ public void setCurrentApplicationName(String currentApplicationName) { this.currentApplicationName = currentApplicationName; } }
false
false
null
null
diff --git a/spring-bootstrap-service/src/main/java/org/springframework/bootstrap/service/shutdown/ShutdownEndpoint.java b/spring-bootstrap-service/src/main/java/org/springframework/bootstrap/service/shutdown/ShutdownEndpoint.java index 2ae1acc4b0..095062287e 100644 --- a/spring-bootstrap-service/src/main/java/org/springframework/bootstrap/service/shutdown/ShutdownEndpoint.java +++ b/spring-bootstrap-service/src/main/java/org/springframework/bootstrap/service/shutdown/ShutdownEndpoint.java @@ -1,94 +1,98 @@ /* * Copyright 2012-2013 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.springframework.bootstrap.service.shutdown; import java.util.Collections; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.bootstrap.service.properties.ContainerProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.support.ServletRequestHandledEvent; /** * @author Dave Syer * */ @Controller public class ShutdownEndpoint implements ApplicationContextAware, ApplicationListener<ServletRequestHandledEvent> { private static Log logger = LogFactory.getLog(ShutdownEndpoint.class); private ConfigurableApplicationContext context; @Autowired private ContainerProperties configuration = new ContainerProperties(); + private boolean shuttingDown = false; + @RequestMapping(value = "${endpoints.shutdown.path:/shutdown}", method = RequestMethod.POST) @ResponseBody public Map<String, Object> shutdown() { if (this.configuration.isAllowShutdown()) { + this.shuttingDown = true; return Collections.<String, Object> singletonMap("message", "Shutting down, bye..."); } else { return Collections.<String, Object> singletonMap("message", "Shutdown not enabled, sorry."); } } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { if (context instanceof ConfigurableApplicationContext) { this.context = (ConfigurableApplicationContext) context; } } @Override public void onApplicationEvent(ServletRequestHandledEvent event) { - if (this.context != null && this.configuration.isAllowShutdown()) { + if (this.context != null && this.configuration.isAllowShutdown() + && this.shuttingDown) { new Thread(new Runnable() { @Override public void run() { logger.info("Shutting down Spring in response to admin request"); ConfigurableApplicationContext context = ShutdownEndpoint.this.context; ApplicationContext parent = context.getParent(); context.close(); if (parent != null && parent instanceof ConfigurableApplicationContext) { context = (ConfigurableApplicationContext) parent; context.close(); parent = context.getParent(); } } }).start(); } } }
false
false
null
null
diff --git a/modules/org.restlet/src/org/restlet/engine/io/NbChannelInputStream.java b/modules/org.restlet/src/org/restlet/engine/io/NbChannelInputStream.java index 27c60ee37..1b7ace766 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/NbChannelInputStream.java +++ b/modules/org.restlet/src/org/restlet/engine/io/NbChannelInputStream.java @@ -1,267 +1,268 @@ /** * Copyright 2005-2011 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the * "Licenses"). You can select the license that you prefer but you may not use * this file except in compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.engine.io; import java.io.IOException; import java.io.InputStream; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.logging.Level; import org.restlet.Context; import org.restlet.util.SelectionListener; import org.restlet.util.SelectionRegistration; // [excludes gwt] /** * Input stream connected to a non-blocking readable channel. * * @author Jerome Louvel */ public class NbChannelInputStream extends InputStream implements BufferProcessor { /** The internal byte buffer. */ private final Buffer buffer; /** The channel to read from. */ private final ReadableByteChannel channel; /** Indicates if further reads can be attempted. */ private volatile boolean endReached; /** The optional selectable channel to read from. */ private final SelectableChannel selectableChannel; /** The optional selection channel to read from. */ private final SelectionChannel selectionChannel; /** The registered selection registration. */ private volatile SelectionRegistration selectionRegistration; /** * Constructor. * * @param channel * The channel to read from. */ public NbChannelInputStream(ReadableByteChannel channel) { this.channel = channel; if (channel instanceof ReadableSelectionChannel) { this.selectionChannel = (ReadableSelectionChannel) channel; this.selectableChannel = null; } else if (channel instanceof SelectableChannel) { this.selectionChannel = null; this.selectableChannel = (SelectableChannel) channel; } else if (channel instanceof SelectionChannel) { this.selectionChannel = (SelectionChannel) channel; this.selectableChannel = null; } else { this.selectionChannel = null; this.selectableChannel = null; } this.buffer = new Buffer(IoUtils.BUFFER_SIZE); this.endReached = false; this.selectionRegistration = null; } /** * Indicates if the processing loop can continue. * * @return True if the processing loop can continue. */ public boolean canLoop() { return true; } /** * Indicates if the buffer could be filled again. * * @return True if the buffer could be filled again. */ public boolean couldFill() { return !this.endReached; } /** * Returns the internal byte buffer. * * @return The internal byte buffer. */ protected Buffer getBuffer() { return buffer; } /** * Drains the byte buffer by returning available bytes as * {@link InputStream} bytes. * * @param buffer * The IO buffer to drain. * @param args * The optional arguments to pass back to the callbacks. + * @return The number of bytes drained. * @throws IOException */ public int onDrain(Buffer buffer, Object... args) throws IOException { int result = 0; if (args.length == 1) { // Let's return the next one - result = getBuffer().drain(); - args[0] = result; + args[0] = getBuffer().drain(); + result = 1; } else if (args.length == 3) { byte[] targetArray = (byte[]) args[0]; int offset = ((Integer) args[1]).intValue(); int length = ((Integer) args[2]).intValue(); result = Math.min(length, getBuffer().remaining()); // Let's return the next ones getBuffer().drain(targetArray, offset, result); } return result; } /** * Fills the byte buffer by reading the source channel. * * @param buffer * The IO buffer to drain. * @param args * The optional arguments to pass back to the callbacks. * @throws IOException */ public int onFill(Buffer buffer, Object... args) throws IOException { int result = buffer.fill(this.channel); if (result == 0) { // No bytes were read, try to register // a select key to get more if (selectionChannel != null) { try { if (this.selectionRegistration == null) { this.selectionRegistration = this.selectionChannel .getRegistration(); this.selectionRegistration .setInterestOperations(SelectionKey.OP_READ); this.selectionRegistration .setListener(new SelectionListener() { public void onSelected() { if (Context.getCurrentLogger() .isLoggable(Level.FINER)) { Context.getCurrentLogger() .log(Level.FINER, "NbChannelInputStream selected"); } // Stop listening at this point selectionRegistration.suspend(); // Unblock the user thread selectionRegistration.unblock(); } }); } else { this.selectionRegistration.resume(); } // Block until new content arrives or a timeout occurs this.selectionRegistration.block(); // Attempt to read more content result = buffer.fill(this.channel); } catch (Exception e) { Context.getCurrentLogger() .log(Level.FINE, "Exception while registering or waiting for new content", e); } } else if (selectableChannel != null) { Selector selector = null; SelectionKey selectionKey = null; try { selector = SelectorFactory.getSelector(); if (selector != null) { selectionKey = this.selectableChannel.register( selector, SelectionKey.OP_READ); selector.select(IoUtils.TIMEOUT_MS); } } finally { NioUtils.release(selector, selectionKey); } result = buffer.fill(this.channel); } } if (result == -1) { this.endReached = true; if (this.selectionRegistration != null) { this.selectionRegistration.setCanceling(true); this.selectionRegistration.setListener(null); } } return result; } @Override public int read() throws IOException { int result = 0; Object[] args = new Object[1]; int bytesDrained = getBuffer().process(this, args); if (bytesDrained == -1) { result = -1; } else if (bytesDrained == 1) { result = ((Integer) args[0]).intValue(); } else { Context.getCurrentLogger().warning( "Too much bytes drained. Only one byte was needed."); } return result; } @Override public int read(byte[] targetArray, int offset, int length) throws IOException { return getBuffer().process(this, targetArray, offset, length); } } \ No newline at end of file
false
false
null
null
diff --git a/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java b/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java index fa6645432..14103da5c 100644 --- a/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java +++ b/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java @@ -1,58 +1,59 @@ package hudson.util; import org.apache.commons.codec.binary.Base64; import java.io.DataInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * Filter InputStream that decodes base64 without doing any buffering. * * <p> * This is slower implementation, but it won't consume unnecessary bytes from the underlying {@link InputStream}, * allowing the reader to switch between the unencoded bytes and base64 bytes. * * @author Kohsuke Kawaguchi * @since 1.349 */ public class UnbufferedBase64InputStream extends FilterInputStream { private byte[] encoded = new byte[4]; private byte[] decoded; private int pos; private final DataInputStream din; public UnbufferedBase64InputStream(InputStream in) { super(in); din = new DataInputStream(in); // initial placement to force the decoding in the next read() pos = 4; decoded = encoded; } @Override public int read() throws IOException { if (decoded.length==0) return -1; // EOF if (pos==decoded.length) { din.readFully(encoded); decoded = Base64.decodeBase64(encoded); + if (decoded.length==0) return -1; // EOF pos = 0; } return (decoded[pos++])&0xFF; } @Override public int read(byte[] b, int off, int len) throws IOException { int i; for (i=0; i<len; i++) { int ch = read(); if (ch<0) break; b[off+i] = (byte)ch; } return i==0 ? -1 : i; } }
true
true
public int read() throws IOException { if (decoded.length==0) return -1; // EOF if (pos==decoded.length) { din.readFully(encoded); decoded = Base64.decodeBase64(encoded); pos = 0; } return (decoded[pos++])&0xFF; }
public int read() throws IOException { if (decoded.length==0) return -1; // EOF if (pos==decoded.length) { din.readFully(encoded); decoded = Base64.decodeBase64(encoded); if (decoded.length==0) return -1; // EOF pos = 0; } return (decoded[pos++])&0xFF; }
diff --git a/bisbat/RecieveGameOutput.java b/bisbat/RecieveGameOutput.java index 6ed1e2c..7784cf4 100755 --- a/bisbat/RecieveGameOutput.java +++ b/bisbat/RecieveGameOutput.java @@ -1,127 +1,116 @@ package bisbat; import java.io.*; import java.net.SocketException; import java.util.Vector; import java.util.regex.*; public class RecieveGameOutput extends Thread { private BufferedReader reader; private Bisbat bisbat; public RecieveGameOutput (Bisbat bisbat, InputStreamReader i) { this.bisbat = bisbat; reader = new BufferedReader(i); } public void run(){ String line = "Starting PrintSteam"; String buffer = ""; while (line != null){ try { line = reader.readLine(); if(line == null) { return; // done reading lines game output is closed } else if(!line.equals("")) { line = decolor(line); if(line.matches(bisbat.getPromptMatch())) { //Handle the buffer then clear it. - //System.out.println("Found the prompt! Handling contents of buffer."); // debugger + //Bisbat.debug("Found the prompt! Handling contents of buffer."); // debugger + //Bisbat.debug(buffer); handleOutput(buffer); buffer = ""; } else { buffer += line + "\n"; //System.out.println("Line(' " + line + " ' != '" + bisbat.getPromptMatch()+ "'."); // debugger } //System.out.println("<-" + line); //print game output } } catch (SocketException e) { System.err.println("Socket failed"); e.printStackTrace(); return; } catch (IOException e) { System.err.println("PrintSteam failed"); e.printStackTrace(); return; } } } /** * Eliminates color information sent from the game. * @param string: string to be de-colored */ public String decolor(String string) { char ESCAPE = '\033'; string = string.replaceAll(ESCAPE + "\\[[01];[0-9][0-9]m", ""); return string; } /** * Dispatch the output from the game to a room, data for * bisbat to see, or the failure of a commands like move. * @param string The output from the game. */ public void handleOutput(String string) { Pattern roomPattern = Pattern.compile(".*<>(.*)<>(.*)Exits:([^\\.]*)\\.(.*)$" , Pattern.MULTILINE | Pattern.DOTALL); Matcher roomMatcher = roomPattern.matcher(string); if(roomMatcher.matches()) { //Bisbat.debug("~~~~~ Found a Room! ~~~~~"); String title = roomMatcher.group(1); String description =roomMatcher.group(2); String exits = roomMatcher.group(3); String beingsAndObjects = roomMatcher.group(4); String[] roomOccupants = beingsAndObjects.split("\n"); //System.out.println("Beings and objects = '" + beingsAndObjects + "'."); // debugger Vector<Being> beings = new Vector<Being>(); Vector<Item> items = new Vector<Item>(); for(String occupant : roomOccupants) { if(occupant.startsWith("M:")) { Being b = new Being(occupant.substring(2)); beings.add(b); bisbat.addKnowledgeOf(b); } else if(occupant.startsWith("I:")) { Item i = new Item(occupant.substring(2)); items.add(i); bisbat.addKnowledgeOf(i); } } Room recentlyDiscoveredRoom = new Room(title, description, exits, beings, items); bisbat.foundRoom(recentlyDiscoveredRoom); } else { //System.out.println("~~~~~ Not a Room! ~~~~~"); // debugger string = string.trim(); - System.out.println("'<--" + string + "'"); // print non-room recieved game information + // print non-room recieved game information if(string.contains("You are too tired to go there now.")) { - - try{ - // BEWARE, this blocks the receive gameoutput thread, when it should be done in Bisbat (just not sure how to do that right now) - - Bisbat.print("Bisbat is sleeping because he was too tired to move right now."); - bisbat.toDoList.add(new Pair<String,Object>("sleep",20)); bisbat.roomFindingThread.failure(); - - - //throw new Exception("testing"); - - } catch(Exception e) { - e.printStackTrace(); - } + } else if(string.length() < 1) { - - } - - bisbat.resultQueue.add(string); + } else { + System.out.println("'<--" + string + "'"); + bisbat.resultQueue.add(string); + } } //Bisbat.print("Done handling output."); // debugger } }
false
false
null
null
diff --git a/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TabletFakePlayer.java b/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TabletFakePlayer.java index 1d7e9790..bea7972b 100644 --- a/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TabletFakePlayer.java +++ b/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TabletFakePlayer.java @@ -1,88 +1,86 @@ /** * This class was created by <Vazkii>. It's distributed as * part of the ThaumicTinkerer Mod. * * ThaumicTinkerer is Open Source and distributed under a * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License * (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB) * * ThaumicTinkerer is a Derivative Work on Thaumcraft 4. * Thaumcraft 4 (c) Azanor 2012 * (http://www.minecraftforum.net/topic/1585216-) * * File Created @ [9 Sep 2013, 15:54:36 (GMT)] */ package vazkii.tinkerer.common.block.tile.tablet; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; import net.minecraftforge.common.FakePlayer; +import thaumcraft.common.lib.FakeThaumcraftPlayer; import vazkii.tinkerer.common.lib.LibBlockNames; -public class TabletFakePlayer extends FakePlayer { +public class TabletFakePlayer extends FakeThaumcraftPlayer { TileAnimationTablet tablet; public TabletFakePlayer(TileAnimationTablet tablet) { super(tablet.worldObj, "tile." + LibBlockNames.ANIMATION_TABLET + ".name"); this.tablet = tablet; } @Override public void setDead() { inventory.clearInventory(-1, -1); super.setDead(); } @Override public void openGui(Object mod, int modGuiId, World world, int x, int y, int z) { // NO-OP } - @Override - public void sendContainerToPlayer(Container par1Container) { - // NO-OP - } + @Override public void onUpdate() { capabilities.isCreativeMode = false; posX = tablet.xCoord + 0.5; posY = tablet.yCoord + 1.6; posZ = tablet.zCoord + 0.5; if(riddenByEntity != null) riddenByEntity.ridingEntity = null; if(ridingEntity != null) ridingEntity.riddenByEntity = null; riddenByEntity = null; ridingEntity = null; motionX = motionY = motionZ = 0; setHealth(20); isDead = false; int meta = tablet.getBlockMetadata() & 7; int rotation = meta == 2 ? 180 : meta == 3 ? 0 : meta == 4 ? 90 : -90; rotationYaw = rotationYawHead = rotation; rotationPitch = -15; for(int i = 0; i < inventory.getSizeInventory(); i++) { if(i != inventory.currentItem) { ItemStack stack = inventory.getStackInSlot(i); if(stack != null) { dropPlayerItem(stack); inventory.setInventorySlotContents(i, null); } } } } @Override public ChunkCoordinates getPlayerCoordinates() { return new ChunkCoordinates(tablet.xCoord, tablet.yCoord, tablet.zCoord); } } \ No newline at end of file diff --git a/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TileAnimationTablet.java b/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TileAnimationTablet.java index 32de87e6..4453a304 100644 --- a/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TileAnimationTablet.java +++ b/src/main/java/vazkii/tinkerer/common/block/tile/tablet/TileAnimationTablet.java @@ -1,583 +1,586 @@ /** * This class was created by <Vazkii>. It's distributed as * part of the ThaumicTinkerer Mod. * * ThaumicTinkerer is Open Source and distributed under a * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License * (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB) * * ThaumicTinkerer is a Derivative Work on Thaumcraft 4. * Thaumcraft 4 (c) Azanor 2012 * (http://www.minecraftforum.net/topic/1585216-) * * File Created @ [9 Sep 2013, 15:51:34 (GMT)] */ package vazkii.tinkerer.common.block.tile.tablet; import appeng.api.movable.IMovableTile; import cpw.mods.fml.common.network.PacketDispatcher; import dan200.computer.api.IComputerAccess; import dan200.computer.api.ILuaContext; import dan200.computer.api.IPeripheral; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.INetworkManager; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.Packet132TileEntityData; import net.minecraft.network.packet.Packet3Chat; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ChatMessageComponent; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.common.FakePlayer; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.event.Event; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; +import thaumcraft.common.lib.FakeThaumcraftPlayer; import vazkii.tinkerer.common.block.ModBlocks; import vazkii.tinkerer.common.lib.LibBlockNames; import java.util.ArrayList; import java.util.List; public class TileAnimationTablet extends TileEntity implements IInventory, IPeripheral, IMovableTile { private static final String TAG_LEFT_CLICK = "leftClick"; private static final String TAG_REDSTONE = "redstone"; private static final String TAG_PROGRESS = "progress"; private static final String TAG_MOD = "mod"; private static final int[][] LOC_INCREASES = new int[][] { { 0, -1 }, { 0, +1 }, { -1, 0 }, { +1, 0 } }; private static final ForgeDirection[] SIDES = new ForgeDirection[] { ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.WEST, ForgeDirection.EAST }; private static final int SWING_SPEED = 3; private static final int MAX_DEGREE = 45; List<Entity> detectedEntities = new ArrayList(); ItemStack[] inventorySlots = new ItemStack[1]; public double ticksExisted = 0; public boolean leftClick = true; public boolean redstone = false; public int swingProgress = 0; private int swingMod = 0; private boolean isBreaking = false; private int initialDamage = 0; private int curblockDamage = 0; private int durabilityRemainingOnBlock; - FakePlayer player; + FakeThaumcraftPlayer player; @Override public void updateEntity() { player = new TabletFakePlayer(this); player.onUpdate(); ticksExisted++; ItemStack stack = getStackInSlot(0); if(stack != null) { if(swingProgress >= MAX_DEGREE) swingHit(); swingMod = swingProgress <= 0 ? 0 : swingProgress >= MAX_DEGREE ? -SWING_SPEED : swingMod; swingProgress += swingMod; if(swingProgress < 0) swingProgress = 0; } else { swingMod = 0; swingProgress = 0; if(isBreaking) stopBreaking(); } boolean detect = detect(); if(!detect) stopBreaking(); if(detect && isBreaking) continueBreaking(); if((!redstone || isBreaking) && detect && swingProgress == 0) { initiateSwing(); worldObj.addBlockEvent(xCoord, yCoord, zCoord, ModBlocks.animationTablet.blockID, 0, 0); } } public void initiateSwing() { swingMod = SWING_SPEED; swingProgress = 1; } public void swingHit() { ChunkCoordinates coords = getTargetLoc(); ItemStack stack = getStackInSlot(0); Item item = stack.getItem(); int id = worldObj.getBlockId(coords.posX, coords.posY, coords.posZ); player.setCurrentItemOrArmor(0, stack); boolean done = false; if(leftClick) { Entity entity = detectedEntities.isEmpty() ? null : detectedEntities.get(worldObj.rand.nextInt(detectedEntities.size())); if(entity != null) { player.getAttributeMap().applyAttributeModifiers(stack.getAttributeModifiers()); // Set attack strenght player.attackTargetEntityWithCurrentItem(entity); done = true; } else if(!isBreaking){ if(id != 0 && !Block.blocksList[id].isAirBlock(worldObj, coords.posX, coords.posY, coords.posZ) && Block.blocksList[id].getBlockHardness(worldObj, coords.posX, coords.posY, coords.posZ) >= 0) { isBreaking = true; startBreaking(Block.blocksList[id], worldObj.getBlockMetadata(coords.posX, coords.posY, coords.posZ)); done = true; } } } else { int side = SIDES[(getBlockMetadata() & 7) - 2].getOpposite().ordinal(); if(!(id != 0 && !Block.blocksList[id].isAirBlock(worldObj, coords.posX, coords.posY, coords.posZ))) { coords.posY -= 1; side = ForgeDirection.UP.ordinal(); id = worldObj.getBlockId(coords.posX, coords.posY, coords.posZ); } try { ForgeEventFactory.onPlayerInteract(player, Action.RIGHT_CLICK_AIR, coords.posX, coords.posY, coords.posZ, side); Entity entity = detectedEntities.isEmpty() ? null : detectedEntities.get(worldObj.rand.nextInt(detectedEntities.size())); done = entity != null && entity instanceof EntityLiving && (item.itemInteractionForEntity(stack, player, (EntityLivingBase) entity) || (entity instanceof EntityAnimal ? ((EntityAnimal) entity).interact(player) : true)); if(!done) item.onItemUseFirst(stack, player, worldObj, coords.posX, coords.posY, coords.posZ, side, 0F, 0F, 0F); if(!done) done = Block.blocksList[id] != null && Block.blocksList[id].onBlockActivated(worldObj, coords.posX, coords.posY, coords.posZ, player, side, 0F, 0F, 0F); if(!done) done = item.onItemUse(stack, player, worldObj, coords.posX, coords.posY, coords.posZ, side, 0F, 0F, 0F); if(!done) { stack = item.onItemRightClick(stack, worldObj, player); done = true; } + } catch(Throwable e) { e.printStackTrace(); Packet3Chat packet = new Packet3Chat(new ChatMessageComponent().addText(EnumChatFormatting.RED + "Something went wrong with a Tool Dynamism Tablet! Check your FML log.")); Packet3Chat packet1 = new Packet3Chat(new ChatMessageComponent().addText(EnumChatFormatting.RED + "" + EnumChatFormatting.ITALIC + e.getMessage())); PacketDispatcher.sendPacketToAllAround(xCoord, yCoord, zCoord, 16, worldObj.provider.dimensionId, packet); PacketDispatcher.sendPacketToAllAround(xCoord, yCoord, zCoord, 16, worldObj.provider.dimensionId, packet1); } } if(done) { - stack = getStackInSlot(0); + stack = player.getCurrentEquippedItem(); if(stack == null || stack.stackSize == 0) setInventorySlotContents(0, null); PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket()); } + onInventoryChanged(); } // Copied from ItemInWorldManager, seems to do the trick. private void stopBreaking() { isBreaking = false; ChunkCoordinates coords = getTargetLoc(); worldObj.destroyBlockInWorldPartially(player.entityId, coords.posX, coords.posY, coords.posZ, -1); } // Copied from ItemInWorldManager, seems to do the trick. private void startBreaking(Block block, int meta) { int side = SIDES[(getBlockMetadata() & 7) - 2].getOpposite().ordinal(); ChunkCoordinates coords = getTargetLoc(); PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract(player, Action.LEFT_CLICK_BLOCK, coords.posX, coords.posY, coords.posZ, side); if (event.isCanceled()) { stopBreaking(); return; } initialDamage = curblockDamage; float var5 = 1F; if (block != null) { if (event.useBlock != Event.Result.DENY) block.onBlockClicked(worldObj, coords.posX, coords.posY, coords.posZ, player); var5 = block.getPlayerRelativeBlockHardness(player, worldObj, coords.posX, coords.posY, coords.posZ); } if (event.useItem == Event.Result.DENY) { stopBreaking(); return; } if(var5 >= 1F) { tryHarvestBlock(coords.posX, coords.posY, coords.posZ); stopBreaking(); } else { int var7 = (int) (var5 * 10); worldObj.destroyBlockInWorldPartially(player.entityId, coords.posX, coords.posY, coords.posZ, var7); durabilityRemainingOnBlock = var7; } } // Copied from ItemInWorldManager, seems to do the trick. private void continueBreaking() { ++curblockDamage; int var1; float var4; int var5; ChunkCoordinates coords = getTargetLoc(); var1 = curblockDamage - initialDamage; int var2 = worldObj.getBlockId(coords.posX, coords.posY, coords.posZ); if (var2 == 0) stopBreaking(); else { Block var3 = Block.blocksList[var2]; var4 = var3.getPlayerRelativeBlockHardness(player, worldObj,coords.posX, coords.posY, coords.posZ) * var1; var5 = (int) (var4 * 10); if (var5 != durabilityRemainingOnBlock) { worldObj.destroyBlockInWorldPartially(player.entityId, coords.posX, coords.posY, coords.posZ, var5); durabilityRemainingOnBlock = var5; } if (var4 >= 1F) { tryHarvestBlock(coords.posX, coords.posY, coords.posZ); stopBreaking(); } } } // Copied from ItemInWorldManager, seems to do the trick. public boolean tryHarvestBlock(int par1, int par2, int par3) { ItemStack stack = getStackInSlot(0); if (stack != null && stack.getItem().onBlockStartBreak(stack, par1, par2, par3, player)) return false; int var4 = worldObj.getBlockId(par1, par2, par3); int var5 = worldObj.getBlockMetadata(par1, par2, par3); worldObj.playAuxSFXAtEntity(player, 2001, par1, par2, par3, var4 + (var5 << 12)); boolean var6 = false; boolean var8 = false; Block block = Block.blocksList[var4]; if (block != null) var8 = block.canHarvestBlock(player, var5); worldObj.loadedEntityList.size(); if (stack != null) stack.onBlockDestroyed(worldObj, var4, par1, par2, par3, player); var6 = removeBlock(par1, par2, par3); if (var6 && var8) Block.blocksList[var4].harvestBlock(worldObj, player, par1, par2, par3, var5); return var6; } // Copied from ItemInWorldManager, seems to do the trick. private boolean removeBlock(int par1, int par2, int par3) { Block var4 = Block.blocksList[worldObj.getBlockId(par1, par2, par3)]; int var5 = worldObj.getBlockMetadata(par1, par2, par3); if (var4 != null) var4.onBlockHarvested(worldObj, par1, par2, par3, var5, player); boolean var6 = var4 != null && var4.removeBlockByPlayer(worldObj, player, par1, par2, par3); if (var4 != null && var6) var4.onBlockDestroyedByPlayer(worldObj, par1, par2, par3, var5); return var6; } public boolean detect() { ChunkCoordinates coords = getTargetLoc(); findEntities(coords); return !worldObj.isAirBlock(coords.posX, coords.posY, coords.posZ) || !detectedEntities.isEmpty(); } public void findEntities(ChunkCoordinates coords) { AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(coords.posX, coords.posY, coords.posZ, coords.posX + 1, coords.posY + 1, coords.posZ + 1); detectedEntities = worldObj.getEntitiesWithinAABB(Entity.class, boundingBox); } public ChunkCoordinates getTargetLoc() { ChunkCoordinates coords = new ChunkCoordinates(xCoord, yCoord, zCoord); int meta = getBlockMetadata(); int[] increase = LOC_INCREASES[(meta & 7) - 2]; coords.posX += increase[0]; coords.posZ += increase[1]; return coords; } public boolean getIsBreaking() { return isBreaking; } @Override public boolean receiveClientEvent(int par1, int par2) { if(par1 == 0) { initiateSwing(); return true; } return tileEntityInvalid; } @Override public void readFromNBT(NBTTagCompound par1NBTTagCompound) { super.readFromNBT(par1NBTTagCompound); swingProgress = par1NBTTagCompound.getInteger(TAG_PROGRESS); swingMod = par1NBTTagCompound.getInteger(TAG_MOD); readCustomNBT(par1NBTTagCompound); } @Override public void writeToNBT(NBTTagCompound par1NBTTagCompound) { super.writeToNBT(par1NBTTagCompound); par1NBTTagCompound.setInteger(TAG_PROGRESS, swingProgress); par1NBTTagCompound.setInteger(TAG_MOD, swingMod); writeCustomNBT(par1NBTTagCompound); } public void readCustomNBT(NBTTagCompound par1NBTTagCompound) { leftClick = par1NBTTagCompound.getBoolean(TAG_LEFT_CLICK); redstone = par1NBTTagCompound.getBoolean(TAG_REDSTONE); NBTTagList var2 = par1NBTTagCompound.getTagList("Items"); inventorySlots = new ItemStack[getSizeInventory()]; for (int var3 = 0; var3 < var2.tagCount(); ++var3) { NBTTagCompound var4 = (NBTTagCompound)var2.tagAt(var3); byte var5 = var4.getByte("Slot"); if (var5 >= 0 && var5 < inventorySlots.length) inventorySlots[var5] = ItemStack.loadItemStackFromNBT(var4); } } public void writeCustomNBT(NBTTagCompound par1NBTTagCompound) { par1NBTTagCompound.setBoolean(TAG_LEFT_CLICK, leftClick); par1NBTTagCompound.setBoolean(TAG_REDSTONE, redstone); NBTTagList var2 = new NBTTagList(); for (int var3 = 0; var3 < inventorySlots.length; ++var3) { if (inventorySlots[var3] != null) { NBTTagCompound var4 = new NBTTagCompound(); var4.setByte("Slot", (byte)var3); inventorySlots[var3].writeToNBT(var4); var2.appendTag(var4); } } par1NBTTagCompound.setTag("Items", var2); } @Override public int getSizeInventory() { return inventorySlots.length; } @Override public ItemStack getStackInSlot(int i) { return inventorySlots[i]; } @Override public ItemStack decrStackSize(int par1, int par2) { if (inventorySlots[par1] != null) { ItemStack stackAt; if (inventorySlots[par1].stackSize <= par2) { stackAt = inventorySlots[par1]; inventorySlots[par1] = null; if(!worldObj.isRemote) PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket()); return stackAt; } else { stackAt = inventorySlots[par1].splitStack(par2); if (inventorySlots[par1].stackSize == 0) inventorySlots[par1] = null; if(!worldObj.isRemote) PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket()); return stackAt; } } return null; } @Override public ItemStack getStackInSlotOnClosing(int i) { return getStackInSlot(i); } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { inventorySlots[i] = itemstack; if(!worldObj.isRemote) PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket()); } @Override public String getInvName() { return LibBlockNames.ANIMATION_TABLET; } @Override public boolean isInvNameLocalized() { return false; } @Override public int getInventoryStackLimit() { return 64; } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return true; } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this ? false : entityplayer.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64; } @Override public void openChest() { // NO-OP } @Override public void closeChest() { // NO-OP } @Override public Packet getDescriptionPacket() { NBTTagCompound nbttagcompound = new NBTTagCompound(); writeCustomNBT(nbttagcompound); return new Packet132TileEntityData(xCoord, yCoord, zCoord, -999, nbttagcompound); } @Override public void onDataPacket(INetworkManager manager, Packet132TileEntityData packet) { super.onDataPacket(manager, packet); readCustomNBT(packet.data); } @Override public String getType() { return "tt_animationTablet"; } @Override public String[] getMethodNames() { return new String[]{ "getRedstone", "setRedstone", "getLeftClick", "setLeftClick", "getRotation", "setRotation", "hasItem", "trigger" }; } @Override public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { switch(method) { case 0 : return new Object[]{ redstone }; case 1 : { boolean redstone = (Boolean) arguments[0]; this.redstone = redstone; PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket()); return null; } case 2 : return new Object[]{ leftClick }; case 3 : { boolean leftClick = (Boolean) arguments[0]; this.leftClick = leftClick; PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket()); return null; } case 4 : return new Object[] { getBlockMetadata() - 2 }; case 5 : { int rotation = (int) ((Double) arguments[0]).doubleValue(); if(rotation > 3) throw new Exception("Invalid value: " + rotation + "."); worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, rotation + 2, 1 | 2); return null; } case 6 : return new Object[] { getStackInSlot(0) != null }; case 7 : { if(swingProgress != 0) return new Object[] { false }; findEntities(getTargetLoc()); initiateSwing(); worldObj.addBlockEvent(xCoord, yCoord, zCoord, ModBlocks.animationTablet.blockID, 0, 0); return new Object[] { true }; } } return null; } @Override public boolean canAttachToSide(int side) { return true; } @Override public void attach(IComputerAccess computer) { // NO-OP } @Override public void detach(IComputerAccess computer) { // NO-OP } @Override public boolean prepareToMove() { stopBreaking(); return true; } @Override public void doneMoving() { } } diff --git a/src/main/java/vazkii/tinkerer/common/lib/LibMisc.java b/src/main/java/vazkii/tinkerer/common/lib/LibMisc.java index d3cd8cc3..ce170747 100644 --- a/src/main/java/vazkii/tinkerer/common/lib/LibMisc.java +++ b/src/main/java/vazkii/tinkerer/common/lib/LibMisc.java @@ -1,30 +1,30 @@ /** * This class was created by <Vazkii>. It's distributed as * part of the ThaumicTinkerer Mod. * * ThaumicTinkerer is Open Source and distributed under a * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License * (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB) * * ThaumicTinkerer is a Derivative Work on Thaumcraft 4. * Thaumcraft 4 (c) Azanor 2012 * (http://www.minecraftforum.net/topic/1585216-) * * File Created @ [4 Sep 2013, 16:02:26 (GMT)] */ package vazkii.tinkerer.common.lib; public final class LibMisc { public static final String MOD_ID = "ThaumicTinkerer"; public static final String MOD_NAME = "Thaumic Tinkerer"; public static final String VERSION = "${version}"; public static final String NETWORK_CHANNEL = MOD_ID; - public static final String DEPENDENCIES = "required-after:Thaumcraft@[4.1,];before:MagicBees;before:advthaum;after:IC2;after:ThaumicTinkererKami;after:Waila"; + public static final String DEPENDENCIES = "required-after:Thaumcraft@[4.1.0f,];before:MagicBees;before:advthaum;after:IC2;after:ThaumicTinkererKami;after:Waila"; public static final String COMMON_PROXY = "vazkii.tinkerer.common.core.proxy.TTCommonProxy"; public static final String CLIENT_PROXY = "vazkii.tinkerer.client.core.proxy.TTClientProxy"; }
false
false
null
null
diff --git a/src/com/beecub/execute/Profile.java b/src/com/beecub/execute/Profile.java index ae69a40..8160ebf 100644 --- a/src/com/beecub/execute/Profile.java +++ b/src/com/beecub/execute/Profile.java @@ -1,137 +1,138 @@ package com.beecub.execute; import java.util.HashMap; import org.bukkit.entity.Player; import org.json.JSONException; import org.json.JSONObject; import com.beecub.glizer.glizer; import com.beecub.util.bChat; import com.beecub.util.bConnector; import com.beecub.util.bMessageManager; import com.beecub.util.bPermissions; public class Profile { public static boolean profile(String command, Player player, String[] args) { if(bPermissions.checkPermission(player, command)) { if(args.length == 1) { String recipient = args[0]; showProfile(player, recipient); return true; } bChat.sendMessageToPlayer(player, bMessageManager.messageWrongCommandUsage); bChat.sendMessageToPlayer(player, "&6/profile&e [playername]"); return true; } return true; } public static boolean editprofile(String command, Player player, String[] args) { if(bPermissions.checkPermission(player, command)) { if(args.length >= 2) { String field = args[0]; String message = ""; for(int i = 1; i < args.length; i++) { message += args[i] + " "; } if(editProfile(player, field, message)) { bChat.sendMessageToPlayer(player, "&6Done"); + return true; } else { return true; } } bChat.sendMessageToPlayer(player, bMessageManager.messageWrongCommandUsage); bChat.sendMessageToPlayer(player, "&6/editprofile&e [field] [value]"); return true; } return true; } public static boolean clearprofile(String command, Player player, String[] args) { bChat.sendMessageToPlayer(player, "&6Not available in this version of glizer"); return true; } public static boolean editProfile(Player player, String field, String value) { String ip = bConnector.getPlayerIPAddress(player); HashMap<String, String> url_items = new HashMap<String, String>(); url_items.put("exec", "profile"); url_items.put("do", "edit"); url_items.put("account", player.getName()); url_items.put("ip", ip); url_items.put("name", player.getName()); url_items.put("field", field); url_items.put("value", value); JSONObject result = bConnector.hdl_com(url_items); String check = bConnector.checkResult(result); if(check.equalsIgnoreCase("ok")) { if(glizer.D) bChat.log("Profile edit action done"); return true; } else if(check.equalsIgnoreCase("not allowed")) { if(glizer.D) bChat.log("Profile edit cant be done, its not allowed to edit this profile field"); bChat.sendMessageToPlayer(player, "&6Error, its not allowed to edit this profile field"); return false; } else if(check.equalsIgnoreCase("wrong data type")) { if(glizer.D) bChat.log("Profile edit cant be done, wrong data type sent"); bChat.sendMessageToPlayer(player, "&6Error, wrong data type"); return false; } return true; /* bChat.log(result.toString()); //{"name":"beecub","realname":"","email":"","age":"0","status":"","mehr":"","lastip":"91.11.230.223", //"reputation":"-1","userreputation":"0","lastserver":"1","lastseen":"1306603729","developer":"0"} try { if(result.getString("response").equalsIgnoreCase("ok")) { return "ok"; } } catch (JSONException e) { if(glizer.D) e.printStackTrace(); } return "error"; */ } public static String showProfile(Player player, String recipient) { String ip = bConnector.getPlayerIPAddress(player); HashMap<String, String> url_items = new HashMap<String, String>(); url_items.put("exec", "profile"); url_items.put("do", "list"); url_items.put("account", player.getName()); url_items.put("ip", ip); url_items.put("name", recipient); JSONObject result = bConnector.hdl_com(url_items); //{"name":"beecub","realname":"","email":"","age":"0","status":"","mehr":"","lastip":"91.11.230.223", //"reputation":"-1","userreputation":"0","lastserver":"1","lastseen":"1306603729","developer":"0"} try { bChat.sendMessageToPlayer(player, "&6 --- Profile --- "); bChat.sendMessageToPlayer(player, "&6Name: &e" + result.getString("name")); bChat.sendMessageToPlayer(player, "&6Realname: &e" + result.getString("realname")); bChat.sendMessageToPlayer(player, "&6Age: &e" + result.getString("age")); bChat.sendMessageToPlayer(player, "&6Last Server: &e" + result.getString("lastserverurl") + ":" + result.getString("lastserverport")); bChat.sendMessageToPlayer(player, "&6Status: &e" + result.getString("status")); } catch (JSONException e) { if(glizer.D) e.printStackTrace(); } return "Ok"; } } diff --git a/src/com/beecub/glizer/glizerPlayerListener.java b/src/com/beecub/glizer/glizerPlayerListener.java index 87ccc9f..5a532ec 100644 --- a/src/com/beecub/glizer/glizerPlayerListener.java +++ b/src/com/beecub/glizer/glizerPlayerListener.java @@ -1,100 +1,104 @@ package com.beecub.glizer; import java.util.HashMap; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerPreLoginEvent; +import org.bukkit.event.player.PlayerLoginEvent; import org.json.JSONException; import org.json.JSONObject; import com.beecub.util.bBackupManager; import com.beecub.util.bChat; import com.beecub.util.bConfigManager; import com.beecub.util.bConnector; public class glizerPlayerListener extends PlayerListener { @SuppressWarnings("unused") private final glizer plugin; public glizerPlayerListener(glizer instance) { plugin = instance; } public void onPlayerPreLogin(PlayerPreLoginEvent event) { } + public void onPlayerLogin(PlayerLoginEvent event) { + + } public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); Boolean kick = true; String ip = bConnector.getPlayerIPAddress(player); HashMap<String, String> url_items = new HashMap<String, String>(); url_items.put("exec", "login"); url_items.put("ip", "1.1.1.1"); url_items.put("account", "server"); url_items.put("username", player.getName()); url_items.put("userip", ip); JSONObject result = bConnector.hdl_com(url_items); // check whitelist if(bConfigManager.usewhitelist) { try { int check = result.getInt("whitelisted"); if(check == 1) { kick = false; } } catch(Exception e) { //e.printStackTrace(); } } // check ban boolean ok = true; try { ok = result.getBoolean("banned"); if(!ok) { if(glizer.D) bChat.log("Player " + player.getName() + " logged into glizer."); kick = false; } else { bChat.log("Player " + player.getName() + " is banned from this server. Kick", 2); kick = true; } } catch (JSONException e) { if(glizer.D) e.printStackTrace(); bChat.log("Unable to check player " + player.getName() + "!", 2); if(!bBackupManager.checkBanList(player.getName())) { kick = false; } } // check developer try { int check = result.getInt("developer"); if(check == 1) { bChat.broadcastMessage("&6Player &2" + player.getName() + "&6 is a &2glizer &6developer"); kick = false; } } catch(Exception e) { //e.printStackTrace(); } if(bBackupManager.checkBanWhiteList(player.getName())) { kick = false; } if(kick) { player.kickPlayer("You are banned from this server. Check glizer.net"); } bChat.sendMessageToPlayer(player, "&6This server is running &2glizer - the Minecraft Globalizer&6"); } }
false
false
null
null
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java index f6a629a40..12ddd91c6 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java @@ -1,285 +1,285 @@ /******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.ui.wizards; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.team.internal.ccvs.core.CVSTag; import org.eclipse.team.internal.ccvs.ui.CVSUIMessages; import org.eclipse.team.internal.ccvs.ui.IHelpContextIds; import org.eclipse.team.internal.ccvs.ui.tags.TagContentAssistProcessor; import org.eclipse.team.internal.ccvs.ui.tags.TagRefreshButtonArea; import org.eclipse.team.internal.ccvs.ui.tags.TagSelectionArea; import org.eclipse.team.internal.ccvs.ui.tags.TagSelectionDialog; import org.eclipse.team.internal.ccvs.ui.tags.TagSource; import org.eclipse.team.internal.ui.PixelConverter; import org.eclipse.team.internal.ui.SWTUtils; import org.eclipse.ui.PlatformUI; public class MergeWizardPage extends CVSWizardPage { private Text endTagField; private Button endTagBrowseButton; private TagSource tagSource; private Text startTagField; private Button startTagBrowseButton; private TagRefreshButtonArea tagRefreshArea; private CVSTag startTag; private CVSTag endTag; private Button previewButton; private Button noPreviewButton; protected boolean preview = true; public MergeWizardPage(String pageName, String title, ImageDescriptor titleImage, String description, TagSource tagSource) { super(pageName, title, titleImage, description); this.tagSource = tagSource; } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent); final Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_DEFAULT)); // set F1 help PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.MERGE_WIZARD_PAGE); final Composite mainArea = new Composite(composite, SWT.NONE); mainArea.setLayoutData(SWTUtils.createHFillGridData()); mainArea.setLayout(SWTUtils.createGridLayout(2, converter, SWTUtils.MARGINS_NONE)); createEndTagArea(mainArea); createStartTagArea(mainArea); SWTUtils.equalizeControls(converter, new Button [] { endTagBrowseButton, startTagBrowseButton } ); createPreviewOptionArea(composite, converter); createTagRefreshArea(composite); Dialog.applyDialogFont(composite); setControl(composite); } private void createPreviewOptionArea(Composite parent, PixelConverter converter) { final Composite composite= new Composite(parent, SWT.NONE); composite.setLayoutData(SWTUtils.createHFillGridData()); composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); previewButton = SWTUtils.createRadioButton(composite, CVSUIMessages.MergeWizardPage_0); //$NON-NLS-1$ noPreviewButton = SWTUtils.createRadioButton(composite, CVSUIMessages.MergeWizardPage_1); //$NON-NLS-1$ SelectionAdapter selectionAdapter = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { preview = previewButton.getSelection(); updateEnablements(); } }; previewButton.setSelection(preview); noPreviewButton.setSelection(!preview); previewButton.addSelectionListener(selectionAdapter); noPreviewButton.addSelectionListener(selectionAdapter); } private void createTagRefreshArea(Composite composite) { tagRefreshArea = new TagRefreshButtonArea(getShell(), getTagSource(), null); tagRefreshArea.setRunnableContext(getContainer()); tagRefreshArea.createArea(composite); } private void createEndTagArea(Composite parent) { SWTUtils.createLabel(parent, CVSUIMessages.MergeWizardPage_2, 2); //$NON-NLS-1$ endTagField = SWTUtils.createText(parent); endTagField.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateEndTag(endTagField.getText()); } }); final int endTagIncludeFlags = TagSelectionArea.INCLUDE_VERSIONS | TagSelectionArea.INCLUDE_BRANCHES | TagSelectionArea.INCLUDE_HEAD_TAG; TagContentAssistProcessor.createContentAssistant(endTagField, tagSource, endTagIncludeFlags); endTagBrowseButton = createPushButton(parent, CVSUIMessages.MergeWizardPage_3); //$NON-NLS-1$ endTagBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TagSelectionDialog dialog = new TagSelectionDialog(getShell(), getTagSource(), CVSUIMessages.MergeWizardPage_4, //$NON-NLS-1$ CVSUIMessages.MergeWizardPage_5, //$NON-NLS-1$ endTagIncludeFlags, false, IHelpContextIds.MERGE_END_PAGE); if (dialog.open() == Dialog.OK) { CVSTag selectedTag = dialog.getResult(); setEndTag(selectedTag); } } }); } private void createStartTagArea(Composite parent) { SWTUtils.createLabel(parent, CVSUIMessages.MergeWizardPage_6, 2); //$NON-NLS-1$ startTagField = SWTUtils.createText(parent); startTagField.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateStartTag(startTagField.getText()); } }); TagContentAssistProcessor.createContentAssistant(startTagField, tagSource, TagSelectionArea.INCLUDE_VERSIONS); startTagBrowseButton = createPushButton(parent, CVSUIMessages.MergeWizardPage_7); //$NON-NLS-1$ startTagBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TagSelectionDialog dialog = new TagSelectionDialog(getShell(), getTagSource(), CVSUIMessages.MergeWizardPage_8, //$NON-NLS-1$ CVSUIMessages.MergeWizardPage_9, //$NON-NLS-1$ TagSelectionDialog.INCLUDE_VERSIONS, false, IHelpContextIds.MERGE_START_PAGE); if (dialog.open() == Dialog.OK) { CVSTag selectedTag = dialog.getResult(); setStartTag(selectedTag); } } }); } protected void updateEndTag(String text) { if (endTag == null || !endTag.getName().equals(text)) { CVSTag tag = getTagFor(text, false); setEndTag(tag); } updateEnablements(); } protected void updateStartTag(String text) { if (startTag == null || !startTag.getName().equals(text)) { CVSTag tag = getTagFor(text, true); setStartTag(tag); } updateEnablements(); } private CVSTag getTagFor(String text, boolean versionsOnly) { if (text.equals(CVSTag.DEFAULT.getName())) { if (versionsOnly) return null; return CVSTag.DEFAULT; } if (text.equals(CVSTag.BASE.getName())) { if (versionsOnly) return null; return CVSTag.BASE; } CVSTag[] tags; if (versionsOnly) { tags = tagSource.getTags(new int[] { CVSTag.VERSION, CVSTag.DATE }); } else { tags = tagSource.getTags(new int[] { CVSTag.VERSION, CVSTag.BRANCH, CVSTag.DATE }); } for (int i = 0; i < tags.length; i++) { CVSTag tag = tags[i]; if (tag.getName().equals(text)) { return tag; } } return null; } protected void setEndTag(CVSTag selectedTag) { if (selectedTag == null || endTag == null || !endTag.equals(selectedTag)) { endTag = selectedTag; if (endTagField != null) { String name = endTagField.getText(); if (endTag != null) name = endTag.getName(); if (!endTagField.getText().equals(name)) endTagField.setText(name); if (startTag == null && endTag != null && endTag.getType() == CVSTag.BRANCH) { CVSTag tag = findCommonBaseTag(endTag); if (tag != null) { setStartTag(tag); } } } updateEnablements(); } } protected void setStartTag(CVSTag selectedTag) { - if (selectedTag == null || startTag != null || !endTag.equals(selectedTag)) { + if (selectedTag == null || startTag != null || endTag == null || !endTag.equals(selectedTag)) { startTag = selectedTag; if (startTagField != null) { String name = startTagField.getText(); if (startTag != null) name = startTag.getName(); if (!startTagField.getText().equals(name)) startTagField.setText(name); } updateEnablements(); } } private CVSTag findCommonBaseTag(CVSTag tag) { CVSTag[] tags = tagSource.getTags(CVSTag.VERSION); for (int i = 0; i < tags.length; i++) { CVSTag potentialMatch = tags[i]; if (potentialMatch.getName().indexOf(tag.getName()) != -1) { return potentialMatch; } } return null; } private void updateEnablements() { if (endTag == null && endTagField.getText().length() > 0) { setErrorMessage(CVSUIMessages.MergeWizardPage_10); //$NON-NLS-1$ } else if (startTag == null && startTagField.getText().length() > 0) { setErrorMessage(CVSUIMessages.MergeWizardPage_11); //$NON-NLS-1$ } else if (endTag != null && startTag != null && startTag.equals(endTag)) { setErrorMessage(CVSUIMessages.MergeWizardPage_12); //$NON-NLS-1$ } else if (startTag == null && endTag != null && preview) { setErrorMessage(CVSUIMessages.MergeWizardPage_13); //$NON-NLS-1$ } else { setErrorMessage(null); } setPageComplete((startTag != null || !preview) && endTag != null && (startTag == null || !startTag.equals(endTag))); } protected TagSource getTagSource() { return tagSource; } private Button createPushButton(Composite parent, String label) { final Button button = new Button(parent, SWT.PUSH); button.setText(label); button.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); return button; } public CVSTag getStartTag() { return startTag; } public CVSTag getEndTag() { return endTag; } public boolean isPreview() { return preview; } }
true
false
null
null
diff --git a/quicksort/QuickSort.java b/quicksort/QuickSort.java index 7788930..b83108c 100644 --- a/quicksort/QuickSort.java +++ b/quicksort/QuickSort.java @@ -1,130 +1,130 @@ package quicksort; import java.util.Random; /** * Efficient implementation of an in-place quicksort. Probably a bit more - * complex that necessary, but not as much as it seems. In-place quicksort with + * complex than necessary, but not as much as it seems. In-place quicksort with * proper handling of pivot element (not fixed, possibly multiple occurrences) * is not easy! * * @author Michael Borgwardt */ public class QuickSort { private static final Random baseRnd = new Random(); /** Used for choosing pivot element */ private final Random rnd; public QuickSort() { rnd = baseRnd; } public QuickSort(Random r) { rnd = r; } /** - * Performa in-place quicksort (ascending order) of the array. + * Perform in-place quicksort (ascending order) of the array. */ public void quicksort(int[] array) { if (array.length < 2) { return; } quicksort(array, 0, array.length - 1); } /** * Perform the quicksort. Pivot elements are collected at the start of the * slice and swapped to the center before recursing. */ private void quicksort(int[] array, int start, int end) { assert start <= end; assert start >= 0; assert end < array.length; switch (end - start) { case 0: // termination conditions return; case 1: // save some recursions if (array[start] > array[end]) { swap(array, start, end); } break; default: // here it gets difficult // Points at end of collected pivot elements int pivotIndex = rnd.nextInt(end - start) + start; // pivot element value int pivot = array[pivotIndex]; swap(array, pivotIndex, start); pivotIndex = start; // points at end of section that contains elements smaller than // pivot int lowerIndex = start + 1; // points at start of section that contains elements bigger than // pivot int higherIndex = end; while (lowerIndex <= higherIndex) { if (array[lowerIndex] <= pivot) { if (array[lowerIndex] == pivot) { swap(array, lowerIndex, pivotIndex + 1); pivotIndex++; } lowerIndex++; continue; } if (array[higherIndex] >= pivot) { if (array[higherIndex] == pivot) { swap(array, higherIndex, pivotIndex + 1); pivotIndex++; } else { higherIndex--; } continue; } swap(array, lowerIndex, higherIndex); switch (higherIndex - lowerIndex) { case 1: break; case 2: if (array[lowerIndex + 1] <= pivot) { lowerIndex++; } else { higherIndex--; } default: lowerIndex++; higherIndex--; } } lowerIndex--; // swap pivot elements back towards middle of slice int pivotBegin = start; while (lowerIndex > pivotIndex && pivotBegin <= pivotIndex) { swap(array, pivotBegin++, lowerIndex--); } // Now do recursions if (pivotBegin > pivotIndex) { quicksort(array, start, lowerIndex); } else { quicksort(array, start, pivotBegin); } quicksort(array, higherIndex, end); } } private void swap(int[] array, int index1, int index2) { int tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } }
false
false
null
null
diff --git a/src/web/org/openmrs/web/controller/user/UserFormController.java b/src/web/org/openmrs/web/controller/user/UserFormController.java index 4eeb3c66..059d65b7 100644 --- a/src/web/org/openmrs/web/controller/user/UserFormController.java +++ b/src/web/org/openmrs/web/controller/user/UserFormController.java @@ -1,260 +1,274 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.controller.user; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Person; import org.openmrs.PersonName; import org.openmrs.Role; import org.openmrs.User; import org.openmrs.api.PasswordException; import org.openmrs.api.UserService; import org.openmrs.api.context.Context; import org.openmrs.messagesource.MessageSourceService; import org.openmrs.propertyeditor.RoleEditor; import org.openmrs.util.OpenmrsConstants; import org.openmrs.util.OpenmrsUtil; import org.openmrs.validator.UserValidator; import org.openmrs.web.WebConstants; import org.openmrs.web.user.UserProperties; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; +import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.request.WebRequest; /** * Used for creating/editing User */ @Controller public class UserFormController { protected static final Log log = LogFactory.getLog(UserFormController.class); @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Role.class, new RoleEditor()); } // the personId attribute is called person_id so that spring MVC doesn't try to bind it to the personId property of user @ModelAttribute("user") public User formBackingObject(WebRequest request, @RequestParam(required=false, value="person_id") Integer personId) { String userId = request.getParameter("userId"); User u = null; try { u = Context.getUserService().getUser(Integer.valueOf(userId)); } catch (Exception ex) { } if (u == null) { u = new User(); } if (personId != null) { u.setPerson(Context.getPersonService().getPerson(personId)); } else if (u.getPerson() == null) { Person p = new Person(); p.addName(new PersonName()); u.setPerson(p); } return u; } @ModelAttribute("allRoles") public List<Role> getRoles(WebRequest request) { List<Role> roles = Context.getUserService().getAllRoles(); if (roles == null) roles = new Vector<Role>(); for (String s : OpenmrsConstants.AUTO_ROLES()) { Role r = new Role(s); roles.remove(r); } return roles; } @RequestMapping(value="/admin/users/user.form", method=RequestMethod.GET) public String showForm(@RequestParam(required=false, value="userId") Integer userId, @RequestParam(required=false, value="createNewPerson") String createNewPerson, @ModelAttribute("user") User user, ModelMap model) { // the formBackingObject method above sets up user, depending on userId and personId parameters model.addAttribute("isNewUser", isNewUser(user)); if (isNewUser(user) || Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) model.addAttribute("modifyPasswords", true); if (createNewPerson != null) model.addAttribute("createNewPerson", createNewPerson); if(!isNewUser(user)) model.addAttribute("changePassword",new UserProperties(user.getUserProperties()).isSupposedToChangePassword()); // not using the default view name because I'm converting from an existing form return "admin/users/userForm"; } /** * @should work for an example */ @RequestMapping(value="/admin/users/user.form", method=RequestMethod.POST) public String handleSubmission(WebRequest request, HttpSession httpSession, ModelMap model, @RequestParam(required=false, value="action") String action, @RequestParam(required=false, value="userFormPassword") String password, @RequestParam(required=false, value="confirm") String confirm, @RequestParam(required=false, value="forcePassword") Boolean forcePassword, @RequestParam(required=false, value="roleStrings") String[] roles, @RequestParam(required=false, value="createNewPerson") String createNewPerson, @ModelAttribute("user") User user, BindingResult errors) { UserService us = Context.getUserService(); MessageSourceService mss = Context.getMessageSourceService(); if (!Context.isAuthenticated()) { errors.reject("auth.invalid"); } else if (mss.getMessage("User.assumeIdentity").equals(action)) { Context.becomeUser(user.getSystemId()); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success"); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName()); return "redirect:/index.htm"; } else if (mss.getMessage("User.delete").equals(action)) { try { Context.getUserService().purgeUser(user); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success"); } catch (Exception ex) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.failure"); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, ex.getMessage()); log.error("Failed to delete user", ex); } return "redirect:/index.htm"; - } else { + } else if (mss.getMessage("User.retire").equals(action)) { + String retireReason = request.getParameter("retireReason"); + if (!(StringUtils.hasText(retireReason))) { + errors.rejectValue("retireReason", "general.retiredReason.empty"); + return showForm(user.getUserId(), createNewPerson, user, model); + } else { + us.retireUser(user, retireReason); + httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage"); + } + + } else if(mss.getMessage("User.unRetire").equals(action)) { + us.unretireUser(user); + httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage"); + }else { // check if username is already in the database if (us.hasDuplicateUsername(user)) errors.rejectValue("username", "error.username.taken"); // check if password and password confirm are identical if (password == null || password.equals("XXXXXXXXXXXXXXX")) password = ""; if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX")) confirm = ""; if (!password.equals(confirm)) errors.reject("error.password.match"); if (password.length() == 0 && isNewUser(user)) errors.reject("error.password.weak"); //check password strength if (password.length() > 0) { try { OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId()); } catch (PasswordException e) { errors.reject(e.getMessage()); } } Set<Role> newRoles = new HashSet<Role>(); if (roles != null) { for (String r : roles) { // Make sure that if we already have a detached instance of this role in the // user's roles, that we don't fetch a second copy of that same role from // the database, or else hibernate will throw a NonUniqueObjectException. Role role = null; if (user.getRoles() != null) for (Role test : user.getRoles()) if (test.getRole().equals(r)) role = test; if (role == null) { role = us.getRole(r); user.addRole(role); } newRoles.add(role); } } if (user.getRoles() == null) newRoles.clear(); else user.getRoles().retainAll(newRoles); String[] keys = request.getParameterValues("property"); String[] values = request.getParameterValues("value"); if (keys != null && values != null) { for (int x = 0; x < keys.length; x++) { String key = keys[x]; String val = values[x]; user.setUserProperty(key, val); } } new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword); UserValidator uv = new UserValidator(); uv.validate(user, errors); if (errors.hasErrors()) { return showForm(user.getUserId(), createNewPerson, user, model); } if (isNewUser(user)) us.saveUser(user, password); else { us.saveUser(user, null); if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) { if (log.isDebugEnabled()) log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser()); us.changePassword(user, password); } } httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved"); } return "redirect:user.list"; } /** * Superficially determines if this form is being filled out for a new user (basically just * looks for a primary key (user_id) * * @param user * @return true/false if this user is new */ private Boolean isNewUser(User user) { return user == null ? true : user.getUserId() == null; } }
false
false
null
null
diff --git a/src/com/cesarandres/ps2link/FragmentMemberList.java b/src/com/cesarandres/ps2link/FragmentMemberList.java index 5fecda9..54083c5 100644 --- a/src/com/cesarandres/ps2link/FragmentMemberList.java +++ b/src/com/cesarandres/ps2link/FragmentMemberList.java @@ -1,539 +1,537 @@ package com.cesarandres.ps2link; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.os.AsyncTask; 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.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.ToggleButton; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import com.cesarandres.ps2link.base.BaseFragment; import com.cesarandres.ps2link.module.ObjectDataSource; import com.cesarandres.ps2link.soe.SOECensus; import com.cesarandres.ps2link.soe.SOECensus.Game; import com.cesarandres.ps2link.soe.SOECensus.Verb; import com.cesarandres.ps2link.soe.content.Member; import com.cesarandres.ps2link.soe.content.Outfit; import com.cesarandres.ps2link.soe.content.response.Outfit_member_response; import com.cesarandres.ps2link.soe.util.Collections.PS2Collection; import com.cesarandres.ps2link.soe.util.QueryString; import com.cesarandres.ps2link.soe.util.QueryString.QueryCommand; import com.cesarandres.ps2link.soe.util.QueryString.SearchModifier; import com.cesarandres.ps2link.soe.volley.GsonRequest; /** * Created by cesar on 6/16/13. */ public class FragmentMemberList extends BaseFragment { private boolean isCached; private boolean shownOffline = false;; private ObjectDataSource data; private int outfitSize; private String outfitId; private String outfitName; private ArrayList<AsyncTask> taskList; - private RequestQueue volley; private FragmentMemberList tag = this; public static final int SUCCESS = 0; public static final int FAILED = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); taskList = new ArrayList<AsyncTask>(); data = new ObjectDataSource(getActivity()); - volley = Volley.newRequestQueue(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_member_list, container, false); ListView listRoot = (ListView) root .findViewById(R.id.listViewMemberList); listRoot.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) { Intent intent = new Intent(); intent.setClass(getActivity(), ActivityProfile.class); intent.putExtra("profileId", ((Member) myAdapter .getItemAtPosition(myItemInt)).getCharacter_id()); startActivity(intent); } }); ImageButton updateButton = (ImageButton) root .findViewById(R.id.buttonFragmentUpdate); ToggleButton viewOffline = (ToggleButton) root .findViewById(R.id.toggleShowOffline); viewOffline.setVisibility(View.VISIBLE); viewOffline .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { shownOffline = isChecked; updateContent(); } }); updateButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { downloadOutfitMembers(outfitId); } }); ToggleButton append = ((ToggleButton) root .findViewById(R.id.buttonFragmentAppend)); append.setVisibility(View.VISIBLE); append.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { CacheOutfit task = new CacheOutfit(); taskList.add(task); task.execute(outfitId); } else { UnCacheOutfit task = new UnCacheOutfit(); taskList.add(task); task.execute(outfitId); } } }); root.findViewById(R.id.buttonFragmentUpdate) .setVisibility(View.VISIBLE); root.findViewById(R.id.toggleShowOffline).setVisibility(View.VISIBLE); root.findViewById(R.id.buttonFragmentStar).setVisibility(View.VISIBLE); ((Button) root.findViewById(R.id.buttonFragmentTitle)).setText(""); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); data.open(); if (savedInstanceState == null) { UpdateOutfitFromTable task = new UpdateOutfitFromTable(); taskList.add(task); task.execute(getActivity().getIntent().getExtras() .getString("outfit_id")); } else { this.outfitSize = savedInstanceState.getInt("outfitSize", 0); this.outfitId = savedInstanceState.getString("outfitId"); this.outfitName = savedInstanceState.getString("outfitName"); this.shownOffline = savedInstanceState.getBoolean("showOffline"); } ((Button) getActivity().findViewById(R.id.buttonFragmentTitle)) .setText(outfitName); ((ToggleButton) getActivity().findViewById(R.id.buttonFragmentStar)) .setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (outfitId != null && outfitName != null) { SharedPreferences settings = getActivity() .getSharedPreferences("PREFERENCES", 0); SharedPreferences.Editor editor = settings.edit(); if (isChecked) { editor.putString("preferedOutfit", outfitId); editor.putString("preferedOutfitName", outfitName); } else { editor.putString("preferedOutfit", ""); editor.putString("preferedOutfitName", ""); } editor.commit(); } } }); } @Override public void onResume() { super.onResume(); if (outfitId != null) { updateContent(); } } @Override public void onPause() { super.onPause(); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putInt("outfitSize", outfitSize); savedInstanceState.putString("outfitId", outfitId); savedInstanceState.putString("outfitName", outfitName); savedInstanceState.putBoolean("showOffline", shownOffline); } @Override public void onDestroyView() { for (AsyncTask task : taskList) { task.cancel(true); } data.close(); super.onDestroy(); } private void downloadOutfitMembers(String outfit_id) { setUpdateButton(false); setAppendButtonVisibility(false); URL url; try { url = SOECensus .generateGameDataRequest( Verb.GET, Game.PS2, PS2Collection.OUTFIT, "", QueryString .generateQeuryString() .AddComparison("id", SearchModifier.EQUALS, outfit_id) .AddCommand(QueryCommand.RESOLVE, "member_online_status,member,member_character(name,type.faction)")); Listener<Outfit_member_response> success = new Response.Listener<Outfit_member_response>() { @Override public void onResponse(Outfit_member_response response) { UpdateMembers task = new UpdateMembers(); taskList.add(task); task.execute(response.getOutfit_list().get(0).getMembers()); } }; ErrorListener error = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.equals(new Object()); setUpdateButton(true); } }; GsonRequest<Outfit_member_response> gsonOject = new GsonRequest<Outfit_member_response>( url.toString(), Outfit_member_response.class, null, success, error); gsonOject.setTag(tag); - volley.add(gsonOject); + ApplicationPS2Link.volley.add(gsonOject); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static class MemberItemAdapter extends BaseAdapter { private LayoutInflater mInflater; private Cursor cursor; private int size; /* * private int size; private int cacheFirst; private int cacheSize; * private ArrayList<Member> cacheA; private ArrayList<Member> cacheB; */ public MemberItemAdapter(Context context, int size, String outfitId, ObjectDataSource data, boolean isCache, boolean showOffline) { // Cache the LayoutInflate to avoid asking for a new one each time. this.mInflater = LayoutInflater.from(context); this.size = data.countAllMembers(outfitId, showOffline); this.cursor = data .getMembersCursor(outfitId, !isCache, showOffline); /* * this.size = size; this.cacheFirst = 0; this.cacheSize = 2 * * this.size; this.cacheA = new ArrayList<Member>(size); this.cacheB * = new ArrayList<Member>(size); */ } @Override public int getCount() { return this.size; } @Override public Member getItem(int position) { return ObjectDataSource.cursorToMember(ObjectDataSource .cursorToPosition(cursor, position)); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater .inflate(R.layout.member_item_list, null); holder = new ViewHolder(); holder.memberName = (TextView) convertView .findViewById(R.id.textViewMemberListName); holder.memberStatus = (TextView) convertView .findViewById(R.id.textViewMemberListStatus); holder.memberRank = (TextView) convertView .findViewById(R.id.textViewMemberListRank); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.memberName.setText(getItem(position).getName().getFirst()); holder.memberRank.setText(getItem(position).getRank()); if (getItem(position).getOnline_status().equals("0")) { holder.memberStatus.setText("Offline"); holder.memberStatus.setTextColor(Color.RED); } else { holder.memberStatus.setText("Online"); holder.memberStatus.setTextColor(Color.GREEN); } return convertView; } static class ViewHolder { TextView memberName; TextView memberStatus; TextView memberRank; } } private void setUpdateButton(boolean enabled) { getActivity().findViewById(R.id.buttonFragmentUpdate).setEnabled( enabled); getActivity().findViewById(R.id.toggleShowOffline).setEnabled(enabled); getActivity().findViewById(R.id.buttonFragmentStar).setEnabled(enabled); getActivity().findViewById(R.id.buttonFragmentAppend).setEnabled( enabled); } private void setAppendButtonVisibility(boolean visible) { ToggleButton star = (ToggleButton) getActivity().findViewById( R.id.buttonFragmentStar); SharedPreferences settings = getActivity().getSharedPreferences( "PREFERENCES", 0); String preferedOutfitId = settings.getString("preferedOutfit", ""); if (preferedOutfitId.equals(outfitId)) { star.setChecked(true); } else { star.setChecked(false); } getActivity().findViewById(R.id.buttonFragmentAppend).setEnabled( visible); star.setEnabled(visible); } private void updateContent() { if (this.outfitId != null) { ListView listRoot = (ListView) getActivity().findViewById( R.id.listViewMemberList); listRoot.setAdapter(new MemberItemAdapter(getActivity(), outfitSize, outfitId, data, isCached, shownOffline)); } } private class UpdateOutfitFromTable extends AsyncTask<String, Integer, Outfit> { @Override protected void onPreExecute() { setAppendButtonVisibility(false); setUpdateButton(false); } @Override protected Outfit doInBackground(String... args) { Log.d("UpdateOutfitFromTable", "STARTING"); Outfit outfit = null; try { outfit = data.getOutfit(args[0]); isCached = outfit.isCached(); } catch (Exception e) { Log.d("UpdateOutfitFromTable", "ENDED BY EXCEPTION"); } Log.d("UpdateOutfitFromTable", "END"); return outfit; } @Override protected void onPostExecute(Outfit result) { if (!this.isCancelled()) { if (result == null) { setUpdateButton(false); } else { outfitId = result.getId(); outfitName = result.getName(); outfitSize = result.getMember_count(); ((Button) getActivity().findViewById( R.id.buttonFragmentTitle)).setText(outfitName); setUpdateButton(false); updateContent(); downloadOutfitMembers(outfitId); } } taskList.remove(this); } } private class UpdateMembers extends AsyncTask<ArrayList<Member>, Integer, Integer> { @Override protected void onPreExecute() { setAppendButtonVisibility(false); setUpdateButton(false); } @Override protected Integer doInBackground(ArrayList<Member>... members) { Log.d("UpdateMembers", "STARTING"); ArrayList<Member> newMembers = members[0]; try { for (Member member : newMembers) { if (data.getMember(member.getCharacter_id(), !isCached) == null) { data.insertMember(member, outfitId, !isCached); } else { data.updateMember(member, !isCached); } } } catch (Exception e) { Log.d("UpdateMembers", "ENDED BY EXCEPTION"); } Log.d("UpdateMembers", "END"); return null; } @Override protected void onPostExecute(Integer result) { if (!this.isCancelled()) { setUpdateButton(true); updateContent(); } taskList.remove(this); } } private class CacheOutfit extends AsyncTask<String, Integer, Integer> { @Override protected void onPreExecute() { setAppendButtonVisibility(false); setUpdateButton(false); - volley.cancelAll(tag); + ApplicationPS2Link.volley.cancelAll(tag); } @Override protected Integer doInBackground(String... args) { Log.d("CacheOutfit", "STARTING"); Outfit outfit = data.getOutfit(args[0]); try { data.updateOutfit(outfit, false); isCached = true; } catch (Exception e) { Log.d("CacheOutfit", "ENDED BY EXCEPTION"); return FAILED; } Log.d("CacheOutfit", "END"); return SUCCESS; } @Override protected void onPostExecute(Integer result) { if (!this.isCancelled()) { if (isCached) { updateContent(); } setUpdateButton(true); } taskList.remove(this); } } private class UnCacheOutfit extends AsyncTask<String, Integer, Integer> { @Override protected void onPreExecute() { setAppendButtonVisibility(false); setUpdateButton(false); - volley.cancelAll(tag); + ApplicationPS2Link.volley.cancelAll(tag); } @Override protected Integer doInBackground(String... args) { Log.d("UnCacheOutfit", "STARTING"); try { Outfit outfit = data.getOutfit(args[0]); data.updateOutfit(outfit, true); isCached = false; } catch (Exception e) { Log.d("UnCacheOutfit", "ENDED BY EXCEPTION"); return FAILED; } Log.d("UnCacheOutfit", "End"); return SUCCESS; } @Override protected void onPostExecute(Integer result) { if (!this.isCancelled()) { if (!isCached) { updateContent(); } setUpdateButton(true); } taskList.remove(this); } } }
false
false
null
null
diff --git a/ted/ui/addshowdialog/AddShowDialog.java b/ted/ui/addshowdialog/AddShowDialog.java index 05d4dc7..777b9ec 100644 --- a/ted/ui/addshowdialog/AddShowDialog.java +++ b/ted/ui/addshowdialog/AddShowDialog.java @@ -1,604 +1,607 @@ package ted.ui.addshowdialog; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.w3c.dom.Element; import ted.BrowserLauncher; import ted.Lang; import ted.TedIO; import ted.TedLog; import ted.TedMainDialog; import ted.TedSerie; import ted.TedSystemInfo; import ted.TedXMLParser; import ted.datastructures.SimpleTedSerie; import ted.datastructures.StandardStructure; import ted.interfaces.EpisodeChooserListener; import ted.ui.TableRenderer; import ted.ui.editshowdialog.EditShowDialog; import ted.ui.editshowdialog.FeedPopupItem; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class AddShowDialog extends JDialog implements ActionListener, MouseListener, EpisodeChooserListener, KeyListener { /** * */ private static final long serialVersionUID = 1006862655927988046L; private JTable showsTable; private JButton cancelButton; private JButton okButton; private JScrollPane showsScrollPane; private ShowsTableModel showsTableModel; private TedSerie selectedSerie; private TedMainDialog tedMain; private JTextPane showInfoPane; private JTextField jSearchField; private JLabel showNameLabel; private JLabel selectShowLabel; private JLabel selectEpisodeLabel; private JButton jHelpButton; private JScrollPane showInfoScrollPane; private JLabel buyDVDLabel; private JButton buttonAddEmptyShow; private Vector<SimpleTedSerie> allShows; private SimpleTedSerie selectedShow; private EpisodeChooserPanel episodeChooserPanel = new EpisodeChooserPanel(this); private SubscribeOptionsPanel subscribeOptionsPanel = new SubscribeOptionsPanel(this); public AddShowDialog() { this.initGUI(); } public AddShowDialog(TedMainDialog main) { this.setModal(true); this.tedMain = main; this.initGUI(); } private void initGUI() { try { // Set the name of the dialog this.setTitle(Lang.getString("TedAddShowDialog.Title")); this.episodeChooserPanel.setActivityStatus(false); FormLayout thisLayout = new FormLayout( "max(p;5dlu), 68dlu:grow, max(p;68dlu), 10dlu, 250px, max(p;100px), 5dlu, 150px, max(p;5dlu)", "max(p;5dlu), max(p;15dlu), 5dlu, 50dlu:grow, 5dlu, max(p;15dlu), 5dlu, bottom:130dlu, 5dlu, max(p;15dlu), 5dlu, max(p;15dlu), max(p;5dlu)"); getContentPane().setLayout(thisLayout); episodeChooserPanel.setVisible(false); subscribeOptionsPanel.setVisible(true); showsTableModel = new ShowsTableModel(); showsTable = new JTable(); //getContentPane().add(showsTable, new CellConstraints("4, 3, 1, 1, default, default")); getShowsScrollPane().setViewportView(showsTable); getContentPane().add(getShowsScrollPane(), new CellConstraints("2, 4, 2, 5, fill, fill")); getContentPane().add(episodeChooserPanel, new CellConstraints("5, 4, 4, 1, fill, fill")); getContentPane().add(subscribeOptionsPanel, new CellConstraints("5, 8, 4, 1, fill, fill")); getContentPane().add(getOkButton(), new CellConstraints("8, 12, 1, 1, default, default")); getContentPane().add(getCancelButton(), new CellConstraints("6, 12, 1, 1, default, default")); getContentPane().add(getShowInfoScrollPane(), new CellConstraints("5, 4, 4, 1, fill, fill")); getContentPane().add(getJHelpButton(), new CellConstraints("2, 12, 1, 1, left, default")); getContentPane().add(getSelectShowLabel(), new CellConstraints("2, 2, 2, 1, left, fill")); getContentPane().add(getSelectEpisodeLabel(), new CellConstraints("5, 6, 4, 1, left, bottom")); getContentPane().add(getShowNameLabel(), new CellConstraints("5, 2, 4, 1, left, fill")); getContentPane().add(getButtonAddEmptyShow(), new CellConstraints("2, 10, 2, 1, left, default")); getContentPane().add(getBuyDVDLabel(), new CellConstraints("5, 10, 4, 1, left, default")); getContentPane().add(getJSearchField(), new CellConstraints("3, 2, 1, 1, default, fill")); showsTable.setModel(showsTableModel); showsTableModel.setSeries(this.readShowNames()); showsTable.setAutoCreateColumnsFromModel(true); showsTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); showsTable.setEditingRow(0); showsTable.setFont(new java.awt.Font("Dialog",0,15)); showsTable.setRowHeight(showsTable.getRowHeight()+10); TableRenderer tr = new TableRenderer(); showsTable.setDefaultRenderer(Object.class, tr); // disable horizontal lines in table showsTable.setShowHorizontalLines(false); showsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); showsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { showsTableSelectionChanged(); }}); // Get the screen size Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); this.setSize((int)(screenSize.width*0.75), (int)(screenSize.height*0.90)); //Calculate the frame location int x = (screenSize.width - this.getWidth()) / 2; int y = (screenSize.height - this.getHeight()) / 2; //Set the new frame location this.setLocation(x, y); this.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Read the shownames from the xml file * @return Vector with names */ private Vector readShowNames() { Vector<SimpleTedSerie> names = new Vector<SimpleTedSerie>(); TedXMLParser parser = new TedXMLParser(); Element shows = parser.readXMLFromFile(TedIO.XML_SHOWS_FILE); //$NON-NLS-1$ if(shows!=null) { names = parser.getNames(shows); allShows = names; } else + { + this.getShowInfoPane().setText((Lang.getString("TedEpisodeDialog.ShowXmlNotFound"))); TedLog.error(Lang.getString("TedEpisodeDialog.LogXmlNotFound")); //$NON-NLS-1$ + } return names; } private JScrollPane getShowsScrollPane() { if (showsScrollPane == null) { showsScrollPane = new JScrollPane(); } return showsScrollPane; } /** * Called whenever the selection of a show is changed in the dialog */ private void showsTableSelectionChanged() { // disable ok button this.okButton.setEnabled(false); // get the selected show int selectedRow = showsTable.getSelectedRow(); if (selectedRow >= 0) { // get the simple info of the show SimpleTedSerie selectedShow = this.showsTableModel.getSerieAt(selectedRow); if (this.selectedShow == null || !(this.selectedShow.getName().equals(selectedShow.getName()))) { this.selectedShow = selectedShow; this.showNameLabel.setText(selectedShow.getName()); this.episodeChooserPanel.setVisible(false); // get the details of the show TedXMLParser parser = new TedXMLParser(); Element series = parser.readXMLFromFile(TedIO.XML_SHOWS_FILE); //$NON-NLS-1$ TedSerie selectedSerie = parser.getSerie(series, selectedShow.getName()); buyDVDLabel.setText("<html><u>"+ Lang.getString("TedAddShowDialog.LabelSupportTed1")+ " " + selectedSerie.getName() +" " + Lang.getString("TedAddShowDialog.LabelSupportTed2") +"</u></html>"); // create a new infoPane to (correctly) show the information showInfoPane = null; showInfoScrollPane.setViewportView(this.getShowInfoPane()); // add auto-generated search based feeds to the show Vector<FeedPopupItem> items = new Vector<FeedPopupItem>(); items = parser.getAutoFeedLocations(series); selectedSerie.generateFeedLocations(items); // retrieve the show info and the episodes from the web ShowInfoThread sit = new ShowInfoThread(this.getShowInfoPane(), selectedSerie); //sit.setPriority( Thread.NORM_PRIORITY + 1 ); EpisodeParserThread ept = new EpisodeParserThread(this.episodeChooserPanel, selectedSerie, this.subscribeOptionsPanel); //ept.setPriority( Thread.NORM_PRIORITY - 1 ); sit.start(); ept.start(); // set the selected show this.setSelectedSerie(selectedSerie); } } } private JButton getOkButton() { if (okButton == null) { okButton = new JButton(); okButton.setText(Lang.getString("TedGeneral.ButtonAdd")); okButton.setActionCommand("OK"); okButton.addActionListener(this); this.getRootPane().setDefaultButton(okButton); this.okButton.setEnabled(false); } return okButton; } private JButton getCancelButton() { if (cancelButton == null) { cancelButton = new JButton(); cancelButton.setText(Lang.getString("TedGeneral.ButtonCancel")); cancelButton.setActionCommand("Cancel"); cancelButton.addActionListener(this); } return cancelButton; } public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("OK")) { this.addShow(); } else if (command.equals("Cancel")) { this.close(); } else if (command.equals("Help")) { try { // open the help page of ted BrowserLauncher.openURL("http://www.ted.nu/wiki/index.php/Add_show"); //$NON-NLS-1$ } catch (Exception err) { } } else if (command.equals("addempty")) { // create an edit show dialog with an empty show and hide add show dialog TedSerie temp = new TedSerie(); // assume user wants to add the show he searched for temp.setName(getJSearchField().getText()); this.close(); new EditShowDialog(tedMain, temp, true); } else if (command.equals("search")) { this.searchShows(getJSearchField().getText()); } else if (command.equals("switch")) { episodeChooserPanel.setVisible(!episodeChooserPanel.isVisible()); } else if (command.equals("")) { // possible a reset on the search box // check (even though this is a little ugly, i dont know a better // way to do this) if (event.getSource().toString().contains("cancel")) { this.getJSearchField().setText(""); this.searchShows(getJSearchField().getText()); } } } /** * Add the selected show with the selected season/episode to teds show list */ private void addShow() { // add show if (selectedSerie != null) { StandardStructure selectedEpisode = this.subscribeOptionsPanel.getSelectedEpisode(); selectedSerie.setCurrentEpisode(selectedEpisode); selectedSerie.updateShowStatus(); // add the serie tedMain.addSerie(selectedSerie); this.close(); } } private void close() { this.showsTableModel.removeSeries(); this.episodeChooserPanel.clear(); // close the dialog this.setVisible(false); this.dispose(); // call garbage collector to cleanup dirt Runtime.getRuntime().gc(); } public void setSelectedSerie(TedSerie selectedSerie2) { this.selectedSerie = selectedSerie2; } private JScrollPane getShowInfoScrollPane() { if (showInfoScrollPane == null) { showInfoScrollPane = new JScrollPane(); showInfoScrollPane.setViewportView(getShowInfoPane()); showInfoScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); } return showInfoScrollPane; } private JTextPane getShowInfoPane() { if (showInfoPane == null) { showInfoPane = new JTextPane(); showInfoPane.setContentType( "text/html" ); showInfoPane.setEditable( false ); String startHTML = "<html><font face=\"Arial, Helvetica, sans-serif\">"; String endHTML = "</font></html>"; showInfoPane.setText(startHTML+ Lang.getString("TedAddShowDialog.ShowInfo.PickAShow") +endHTML); showInfoPane.setPreferredSize(new java.awt.Dimension(475, 128)); // Set up the JEditorPane to handle clicks on hyperlinks showInfoPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { // Handle clicks; ignore mouseovers and other link-related events if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { // Get the HREF of the link and display it. try { BrowserLauncher.openURL(e.getDescription()); } catch (IOException e1) { // TODO Auto-generated catch block } } } }); } return showInfoPane; } private JButton getJHelpButton() { if (jHelpButton == null) { jHelpButton = new JButton(); jHelpButton.setActionCommand("Help"); if (!TedSystemInfo.osIsMacLeopardOrBetter()) { jHelpButton.setIcon(new ImageIcon(getClass().getClassLoader() .getResource("icons/help.png"))); } jHelpButton.setBounds(11, 380, 28, 28); jHelpButton.addActionListener(this); jHelpButton.putClientProperty("JButton.buttonType", "help"); jHelpButton.setToolTipText(Lang.getString("TedGeneral.ButtonHelpToolTip")); } return jHelpButton; } private JLabel getSelectShowLabel() { if (selectShowLabel == null) { selectShowLabel = new JLabel(); selectShowLabel.setText(Lang.getString("TedAddShowDialog.LabelSelectShow")); } return selectShowLabel; } private JLabel getSelectEpisodeLabel() { if (selectEpisodeLabel == null) { selectEpisodeLabel = new JLabel(); selectEpisodeLabel .setText(Lang.getString("TedAddShowDialog.LabelSelectEpisode")); } return selectEpisodeLabel; } private JLabel getShowNameLabel() { if (showNameLabel == null) { showNameLabel = new JLabel(); showNameLabel.setFont(new java.awt.Font("Dialog",1,25)); } return showNameLabel; } private JButton getButtonAddEmptyShow() { if (buttonAddEmptyShow == null) { buttonAddEmptyShow = new JButton(); buttonAddEmptyShow.setText(Lang.getString("TedAddShowDialog.ButtonAddCustomShow")); buttonAddEmptyShow.addActionListener(this); buttonAddEmptyShow.setActionCommand("addempty"); } return buttonAddEmptyShow; } private JLabel getBuyDVDLabel() { if (buyDVDLabel == null) { buyDVDLabel = new JLabel(); buyDVDLabel.setText(""); buyDVDLabel.setForeground(Color.BLUE); buyDVDLabel.setFont(new java.awt.Font("Dialog",1,12)); buyDVDLabel.addMouseListener(this); buyDVDLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } return buyDVDLabel; } public void mouseClicked(MouseEvent arg0) { // clicked on label to buy dvd this.tedMain.openBuyLink(this.selectedSerie.getName()); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } public void episodeSelectionChanged() { StandardStructure selectedStructure = episodeChooserPanel.getSelectedStructure(); this.subscribeOptionsPanel.setCustomEpisode(selectedStructure); } /* (non-Javadoc) * @see ted.interfaces.EpisodeChooserListener#doubleClickOnEpisodeList() */ public void doubleClickOnEpisodeList() { // add show this.addShow(); } private JTextField getJSearchField() { if(jSearchField == null) { jSearchField = new SearchTextField(); jSearchField.addKeyListener(this); jSearchField.putClientProperty("JTextField.Search.CancelAction", this); } return jSearchField; } private void searchShows(String searchString) { // Only search if we've entered a search term if (!searchString.equals("<SEARCH>")) { Vector<SimpleTedSerie> tempShows = new Vector<SimpleTedSerie>(); // If we've entered a search term filter the list, otherwise // display all shows if (!searchString.equals("")) { // Do the filtering for (int show = 0; show < allShows.size(); ++show) { SimpleTedSerie serie = allShows.get(show); if (serie.getName().toLowerCase().contains(searchString.toLowerCase())) { tempShows.add(serie); } } // Update the table showsTableModel.setSeries(tempShows); if (tempShows.size() == 1) { // if only a single show is left: select it ListSelectionModel selectionModel = showsTable.getSelectionModel(); selectionModel.setSelectionInterval(0, 0); } } else { showsTableModel.setSeries(allShows); } // Let the table know that there's new information showsTableModel.fireTableDataChanged(); } } public void keyPressed (KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { searchShows(jSearchField.getText()); } public void keyTyped (KeyEvent arg0) { } public void subscribeOptionChanged() { // called when episode selection is changed. // check if episode and show selected if (selectedSerie != null && this.subscribeOptionsPanel.getSelectedEpisode() != null) { // enable add button this.okButton.setEnabled(true); } else { this.okButton.setEnabled(false); } } public void setEpisodeChooserVisible(boolean b) { this.episodeChooserPanel.setVisible(b); } }
false
false
null
null
diff --git a/org/python/util/PythonObjectInputStream.java b/org/python/util/PythonObjectInputStream.java index a8c8b97b..bc7e40dc 100644 --- a/org/python/util/PythonObjectInputStream.java +++ b/org/python/util/PythonObjectInputStream.java @@ -1,41 +1,41 @@ package org.python.util; import java.io.*; import org.python.core.*; public class PythonObjectInputStream extends ObjectInputStream { public PythonObjectInputStream(InputStream istr) throws IOException { super(istr); } protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { String clsName = v.getName(); //System.out.println(clsName); if (clsName.startsWith("org.python.proxies")) { int idx = clsName.lastIndexOf('$'); if (idx > 19) clsName = clsName.substring(19, idx); //System.out.println("new:" + clsName); Class cls = (Class) PyClass.serializableProxies.get(clsName); if (cls != null) return cls; } try { return super.resolveClass(v); } catch (ClassNotFoundException exc) { - PyObject m = imp.load(clsName); + PyObject m = imp.load(clsName.intern()); //System.out.println("m:" + m); Object cls = m.__tojava__(Class.class); //System.out.println("cls:" + cls); if (cls != null && cls != Py.NoConversion) return (Class) cls; throw exc; } } } \ No newline at end of file
true
false
null
null
diff --git a/Enduro/src/sort/NullTime.java b/Enduro/src/sort/NullTime.java index fb84e0e..888650b 100644 --- a/Enduro/src/sort/NullTime.java +++ b/Enduro/src/sort/NullTime.java @@ -1,29 +1,34 @@ package sort; public class NullTime extends Time { public NullTime() { super(0); } @Override public String toString() { return "--.--.--"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; return true; } - + + @Override + public int compareTo(Time time){ + return 1; + } + @Override public Time difference(Time t) { return t; } }
true
false
null
null
diff --git a/src/java/se/idega/idegaweb/commune/childcare/data/ChildCareApplicationBMPBean.java b/src/java/se/idega/idegaweb/commune/childcare/data/ChildCareApplicationBMPBean.java index 218b4d25..cac1d2d7 100644 --- a/src/java/se/idega/idegaweb/commune/childcare/data/ChildCareApplicationBMPBean.java +++ b/src/java/se/idega/idegaweb/commune/childcare/data/ChildCareApplicationBMPBean.java @@ -1,1206 +1,1206 @@ /* * $Id:$ * * Copyright (C) 2002 Idega hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. * */ package se.idega.idegaweb.commune.childcare.data; import java.sql.Date; import java.util.Collection; import javax.ejb.FinderException; import se.idega.idegaweb.commune.childcare.check.data.GrantedCheck; import com.idega.block.contract.data.Contract; import com.idega.block.process.data.AbstractCaseBMPBean; import com.idega.block.process.data.Case; import com.idega.block.process.data.CaseStatus; import com.idega.block.school.data.School; import com.idega.core.file.data.ICFile; import com.idega.data.IDOException; import com.idega.data.IDOQuery; import com.idega.user.data.User; /** * This class does something very clever..... * * @author palli * @version 1.0 */ public class ChildCareApplicationBMPBean extends AbstractCaseBMPBean implements ChildCareApplication, Case { public final static String ENTITY_NAME = "comm_childcare"; private final static String CASE_CODE_KEY = "MBANBOP"; private final static String CASE_CODE_KEY_DESC = "Application for child care"; public final static String PROVIDER_ID = "provider_id"; public final static String FROM_DATE = "from_date"; public final static String CHILD_ID = "child_id"; public final static String QUEUE_DATE = "queue_date"; public final static String METHOD = "method"; public final static String CARE_TIME = "care_time"; public final static String CHOICE_NUMBER = "choice_number"; public final static String CHECK_ID = "check_id"; public final static String CONTRACT_ID = "contract_id"; public final static String CONTRACT_FILE_ID = "contract_file_id"; public final static String OFFER_VALID_UNTIL = "offer_valid_until"; public final static String REJECTION_DATE = "rejection_date"; public final static String PROGNOSIS = "prognosis"; public final static String PRESENTATION = "presentation"; public final static String CC_MESSAGE = "cc_message"; public final static String QUEUE_ORDER = "queue_order"; public final static String APPLICATION_STATUS = "application_status"; public final static String HAS_PRIORITY = "has_priority"; public final static String HAS_DATE_SET = "has_date_set"; public final static String HAS_QUEUE_PRIORITY = "has_queue_priority"; public final static String PRESCHOOL = "preschool"; public final static String LAST_REPLY_DATE = "last_reply_date"; protected final static String EXTRA_CONTRACT = "extra_contract"; protected final static String EXTRA_CONTRACT_MESSAGE = "extra_contract_message"; protected final static String EXTRA_CONTRACT_OTHER = "extra_contract_other"; protected final static String EXTRA_CONTRACT_OTHER_MESSAGE = "extra_contract_message_other"; protected final int SORT_DATE_OF_BIRTH = 1; protected final int SORT_QUEUE_DATE = 2; protected final int SORT_PLACEMENT_DATE = 3; /** * @see com.idega.block.process.data.AbstractCaseBMPBean#getCaseCodeKey() */ public String getCaseCodeKey() { return CASE_CODE_KEY; } /** * @see com.idega.block.process.data.AbstractCaseBMPBean#getCaseCodeDescription() */ public String getCaseCodeDescription() { return CASE_CODE_KEY_DESC; } /** * @see com.idega.data.IDOLegacyEntity#getEntityName() */ public String getEntityName() { return ENTITY_NAME; } /** * @see com.idega.data.IDOLegacyEntity#initializeAttributes() */ public void initializeAttributes() { addAttribute(getIDColumnName()); addAttribute(FROM_DATE,"",true,true,java.sql.Date.class); addAttribute(QUEUE_DATE,"",true,true,java.sql.Date.class); addAttribute(METHOD,"",true,true,java.lang.Integer.class); addAttribute(CARE_TIME,"",true,true,java.lang.Integer.class); addAttribute(CHOICE_NUMBER,"",true,true,java.lang.Integer.class); addAttribute(REJECTION_DATE,"",true,true,java.sql.Date.class); addAttribute(OFFER_VALID_UNTIL,"",true,true,java.sql.Date.class); addAttribute(PROGNOSIS,"",true,true,java.lang.String.class,1000); addAttribute(PRESENTATION,"",true,true,java.lang.String.class,1000); addAttribute(CC_MESSAGE,"",true,true,java.lang.String.class,1000); addAttribute(QUEUE_ORDER,"",true,true,java.lang.Integer.class); addAttribute(APPLICATION_STATUS,"",true,true,java.lang.String.class,1); addAttribute(HAS_PRIORITY,"",true,true,java.lang.Boolean.class); addAttribute(HAS_DATE_SET,"",true,true,java.lang.Boolean.class); addAttribute(HAS_QUEUE_PRIORITY,"",true,true,java.lang.Boolean.class); addAttribute(PRESCHOOL,"",true,true,java.lang.String.class); addAttribute(LAST_REPLY_DATE,"",true,true,java.sql.Date.class); addAttribute(EXTRA_CONTRACT,"",true,true,java.lang.Boolean.class); addAttribute(EXTRA_CONTRACT_MESSAGE,"",true,true,java.lang.String.class); addAttribute(EXTRA_CONTRACT_OTHER,"",true,true,java.lang.Boolean.class); addAttribute(EXTRA_CONTRACT_OTHER_MESSAGE,"",true,true,java.lang.String.class); addManyToOneRelationship(PROVIDER_ID,School.class); addManyToOneRelationship(CHILD_ID,User.class); addManyToOneRelationship(CHECK_ID,GrantedCheck.class); addManyToOneRelationship(CONTRACT_ID,Contract.class); addManyToOneRelationship(CONTRACT_FILE_ID,ICFile.class); } public int getProviderId() { return getIntColumnValue(PROVIDER_ID); } public School getProvider() { return (School)getColumnValue(PROVIDER_ID); } public Date getFromDate() { return (Date)getColumnValue(FROM_DATE); } public int getChildId() { return getIntColumnValue(CHILD_ID); } public User getChild() { return (User) getColumnValue(CHILD_ID); } public Date getQueueDate() { return (Date)getColumnValue(QUEUE_DATE); } public int getMethod() { return getIntColumnValue(METHOD); } public int getCareTime() { return getIntColumnValue(CARE_TIME); } public int getChoiceNumber() { return getIntColumnValue(CHOICE_NUMBER); } public int getCheckId() { return getIntColumnValue(CHECK_ID); } public GrantedCheck getCheck() { return (GrantedCheck)getColumnValue(CHECK_ID); } public Date getRejectionDate() { return (Date)getColumnValue(REJECTION_DATE); } public Date getOfferValidUntil() { return (Date)getColumnValue(OFFER_VALID_UNTIL); } public Date getLastReplyDate() { return (Date)getColumnValue(LAST_REPLY_DATE); } public int getContractId() { return getIntColumnValue(CONTRACT_ID); } public Contract getContract() { return (Contract)getColumnValue(CONTRACT_ID); } public int getContractFileId() { return getIntColumnValue(CONTRACT_FILE_ID); } public ICFile getContractFile() { return (ICFile) getColumnValue(CONTRACT_FILE_ID); } public String getPrognosis() { return getStringColumnValue(PROGNOSIS); } public String getPresentation() { return getStringColumnValue(PRESENTATION); } public String getPreSchool() { return getStringColumnValue(PRESCHOOL); } public String getMessage() { return getStringColumnValue(CC_MESSAGE); } public int getQueueOrder() { return getIntColumnValue(QUEUE_ORDER); } public char getApplicationStatus() { String status = this.getStringColumnValue(APPLICATION_STATUS); if (status != null) return status.charAt(0); else return 'A'; } public boolean getHasPriority() { return getBooleanColumnValue(HAS_PRIORITY, false); } public boolean getHasDateSet() { return getBooleanColumnValue(HAS_DATE_SET, false); } public boolean getHasQueuePriority() { return getBooleanColumnValue(HAS_QUEUE_PRIORITY, false); } public boolean getHasExtraContract() { return getBooleanColumnValue(EXTRA_CONTRACT, false); } public String getExtraContractMessage() { return getStringColumnValue(EXTRA_CONTRACT_MESSAGE); } public boolean getHasExtraContractOther() { return getBooleanColumnValue(EXTRA_CONTRACT_OTHER, false); } public String getExtraContractMessageOther() { return getStringColumnValue(EXTRA_CONTRACT_OTHER_MESSAGE); } public void setProviderId(int id) { setColumn(PROVIDER_ID,id); } public void setProvider(School provider) { setColumn(PROVIDER_ID,provider); } public void setFromDate(Date date) { setColumn(FROM_DATE,date); } public void setChildId(int id) { setColumn(CHILD_ID,id); } public void setChild(User child) { setColumn(CHILD_ID,child); } public void setQueueDate(Date date) { setColumn(QUEUE_DATE,date); } public void setMethod(int method) { setColumn(METHOD,method); } public void setCareTime(int careTime) { setColumn(CARE_TIME,careTime); } public void setChoiceNumber(int number) { setColumn(CHOICE_NUMBER,number); } public void setCheckId(int checkId) { setColumn(CHECK_ID,checkId); } public void setCheck(GrantedCheck check) { setColumn(CHECK_ID,check); } public void setRejectionDate(Date date) { setColumn(REJECTION_DATE,date); } public void setOfferValidUntil(Date date) { setColumn(OFFER_VALID_UNTIL,date); } public void setLastReplyDate(Date date) { setColumn(LAST_REPLY_DATE,date); } public void setContractId(int id) { setColumn(CONTRACT_ID,id); } public void setContractId(Integer id) { setColumn(CONTRACT_ID,id); } public void setContractFileId(int id) { setColumn(CONTRACT_FILE_ID,id); } public void setContractFileId(Integer id) { setColumn(CONTRACT_FILE_ID,id); } public void setPrognosis(String prognosis) { setColumn(PROGNOSIS,prognosis); } public void setPresentation(String presentation) { setColumn(PRESENTATION,presentation); } public void setPreSchool(java.lang.String preSchool){ setColumn(PRESCHOOL, preSchool); } public void setMessage(String message) { setColumn(CC_MESSAGE,message); } public void setQueueOrder(int order) { setColumn(QUEUE_ORDER,order); } public void setApplicationStatus(char status) { setColumn(APPLICATION_STATUS,String.valueOf(status)); } public void setHasPriority(boolean hasPriority) { setColumn(HAS_PRIORITY, hasPriority); } public void setHasDateSet(boolean hasDateSet) { setColumn(HAS_DATE_SET, hasDateSet); } public void setHasQueuePriority(boolean hasPriority) { setColumn(HAS_QUEUE_PRIORITY, hasPriority); } public void setRejectionDateAsNull(boolean setAsNull) { if (setAsNull) removeFromColumn(ENTITY_NAME); } public void setHasExtraContract(boolean hasExtraContract) { setColumn(EXTRA_CONTRACT, hasExtraContract); } public void setExtraContractMessage(String message) { setColumn(EXTRA_CONTRACT_MESSAGE, message); } public void setHasExtraContractOther(boolean hasExtraContractOther) { setColumn(EXTRA_CONTRACT_OTHER, hasExtraContractOther); } public void setExtraContractMessageOther(String message) { setColumn(EXTRA_CONTRACT_OTHER_MESSAGE, message); } public Collection ejbFindAll() throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this); return idoFindPKsBySQL(sql.toString()); } public Collection ejbFindAllCasesByProviderAndStatus(int providerId, CaseStatus caseStatus) throws FinderException { return ejbFindAllCasesByProviderStatus(providerId, caseStatus.getStatus()); } public Collection ejbFindAllCasesByProviderAndStatus(School provider, String caseStatus) throws FinderException { return ejbFindAllCasesByProviderStatus(((Integer)provider.getPrimaryKey()).intValue(), caseStatus); } public Collection ejbFindAllCasesByProviderAndStatus(School provider, CaseStatus caseStatus) throws FinderException { return ejbFindAllCasesByProviderStatus(((Integer)provider.getPrimaryKey()).intValue(), caseStatus.getStatus()); } public Collection ejbFindAllCasesByProviderStatus(int providerId, String caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerId); sql.appendAnd().appendEqualsQuoted("p.case_status",caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendOrderBy("c."+QUEUE_DATE+",c."+QUEUE_ORDER); return idoFindPKsBySQL(sql.toString()); } public Collection ejbFindAllChildCasesByProvider(int providerId) throws FinderException { StringBuffer sql = new StringBuffer( "select m.* from msg_letter_message m, proc_case p, comm_childcare c" + " where m.msg_letter_message_id = p.proc_case_id and " + " c.provider_id = " + providerId + " and " + " p.parent_case_id in (select proc_case_id from proc_case where p.proc_case_id = c.comm_childcare_id)"); return idoFindPKsBySQL(sql.toString()); } public Collection ejbFindAllCasesByProviderAndStatus(int providerId, String caseStatus, int numberOfEntries, int startingEntry) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerId); sql.appendAnd().appendEqualsQuoted("p.case_status",caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendOrderBy("c."+QUEUE_ORDER); return idoFindPKsBySQL(sql.toString(), numberOfEntries, startingEntry); } public Collection ejbFindAllCasesByProviderAndNotInStatus(int providerId, String[] caseStatus, int numberOfEntries, int startingEntry) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerId); if (caseStatus != null) sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendOrderBy("c."+APPLICATION_STATUS+" desc, c."+QUEUE_DATE+", c."+QUEUE_ORDER); return idoFindPKsBySQL(sql.toString(), numberOfEntries, startingEntry); } public Collection ejbFindAllCasesByProviderAndNotInStatus(int providerId, int sortBy, Date fromDate, Date toDate, String[] caseStatus, int numberOfEntries, int startingEntry) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); if (sortBy == SORT_DATE_OF_BIRTH) sql.append(", ic_user u"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerId); if (caseStatus != null) sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); if (sortBy == SORT_DATE_OF_BIRTH) { sql.appendAndEquals("c."+CHILD_ID, "u.ic_user_id"); sql.appendAnd().append("u.date_of_birth").appendGreaterThanOrEqualsSign().append(fromDate); sql.appendAnd().append("u.date_of_birth").appendLessThanOrEqualsSign().append(toDate); } else if (sortBy == SORT_QUEUE_DATE) { sql.appendAnd().append("c."+QUEUE_DATE).appendGreaterThanOrEqualsSign().append(fromDate); sql.appendAnd().append("c."+QUEUE_DATE).appendLessThanOrEqualsSign().append(toDate); } else if (sortBy == SORT_PLACEMENT_DATE) { sql.appendAnd().append("c."+FROM_DATE).appendGreaterThanOrEqualsSign().append(fromDate); sql.appendAnd().append("c."+FROM_DATE).appendLessThanOrEqualsSign().append(toDate); } sql.appendOrderBy("c."+APPLICATION_STATUS+" desc, c."+QUEUE_DATE+", c."+QUEUE_ORDER); return idoFindPKsBySQL(sql.toString(), numberOfEntries, startingEntry); } public Collection ejbFindAllCasesByProviderStatus(int providerId, String caseStatus[]) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerId); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); sql.appendOrderBy("c."+QUEUE_DATE+",c."+QUEUE_ORDER); return idoFindPKsBySQL(sql.toString()); } public Collection ejbFindAllByAreaAndApplicationStatus(Object areaID, String applicationStatus[], String caseCode, Date queueDate, Date placementDate, boolean firstHandOnly) throws FinderException { IDOQuery inQuery = idoQuery(); inQuery.appendSelect().append("ic_user_id").appendFrom().append("sch_class_member"); IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p, sch_school s, ic_user u"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,"s.sch_school_id"); sql.appendAndEquals("c."+CHILD_ID,"u.ic_user_id"); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } sql.appendAnd().append("c."+APPLICATION_STATUS).appendInArrayWithSingleQuotes(applicationStatus); if (areaID != null) { sql.appendAndEquals("s.sch_school_area_id", areaID); } sql.appendAnd().append(QUEUE_DATE).appendLessThanSign().append(queueDate); sql.appendAnd().append(FROM_DATE).appendLessThanSign().append(placementDate); if (firstHandOnly) { sql.appendAndEquals(CHOICE_NUMBER, 1); } sql.appendAnd().append(CHILD_ID).appendNotIn(inQuery); sql.appendOrderBy("u.last_name, u.first_name, u.last_name, c."+APPLICATION_STATUS+", c."+QUEUE_DATE); return idoFindPKsBySQL(sql.toString()); } public Collection ejbFindAllCasesByProviderStatusNotRejected(int providerId, String caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerId); sql.appendAnd().appendEqualsQuoted("p.case_status",caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendAnd().append(REJECTION_DATE).append(" is null"); return idoFindPKsBySQL(sql.toString()); } public Collection ejbFindAllCasesByUserAndStatus(User owner, String caseStatus) throws FinderException { return super.ejbFindAllCasesByUserAndStatus(owner,caseStatus); } public Collection ejbFindAllCasesByStatus(String caseStatus) throws FinderException { return super.ejbFindAllCasesByStatus(caseStatus); } public Collection ejbFindApplicationsByProviderAndStatus(int providerID, String caseStatus) throws FinderException { String[] status = { caseStatus }; return ejbFindApplicationsByProviderAndStatus(providerID, status, -1, -1); } public Collection ejbFindApplicationsByProviderAndStatus(int providerID, String[] caseStatus) throws FinderException { return ejbFindApplicationsByProviderAndStatus(providerID, caseStatus, -1, -1); } public Collection ejbFindApplicationsByProviderAndStatus(int providerID, String[] caseStatus, String caseCode) throws FinderException { return ejbFindApplicationsByProviderAndStatus(providerID, caseStatus, caseCode, -1, -1); } public Collection ejbFindApplicationsByProviderAndStatus(int providerID, String caseStatus, int numberOfEntries, int startingEntry) throws FinderException { String[] status = { caseStatus }; return ejbFindApplicationsByProviderAndStatus(providerID, status, numberOfEntries, startingEntry); } public Collection ejbFindApplicationsByProviderAndStatus(int providerID, String[] caseStatus, int numberOfEntries, int startingEntry) throws FinderException { return ejbFindApplicationsByProviderAndStatus(providerID, caseStatus, null, numberOfEntries, startingEntry); } public Collection ejbFindApplicationsByProviderAndStatus(int providerID, String[] caseStatus, String caseCode, int numberOfEntries, int startingEntry) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p, ic_user u"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID, "u.ic_user_id"); sql.appendAndEquals("c."+PROVIDER_ID, providerID); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); if (caseCode != null) sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); sql.appendOrderBy("u.last_name, u.first_name, u.middle_name"); if (numberOfEntries == -1) return idoFindPKsBySQL(sql.toString()); else return idoFindPKsBySQL(sql.toString(), numberOfEntries, startingEntry); } public Collection ejbFindApplicationsByProviderAndApplicationStatus(int providerID, String[] applicationStatuses) throws FinderException { return ejbFindApplicationsByProviderAndApplicationStatus(providerID, applicationStatuses, null); } public Collection ejbFindApplicationsByProviderAndApplicationStatus(int providerID, String[] applicationStatuses, String caseCode) throws FinderException { return ejbFindApplicationsByProviderAndApplicationStatus(providerID, applicationStatuses, caseCode, -1, -1); } public Collection ejbFindApplicationsByProviderAndApplicationStatus(int providerID, String[] applicationStatuses, String caseCode, int numberOfEntries, int startingEntry) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p, ic_user u"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID, "u.ic_user_id"); sql.appendAndEquals("c."+PROVIDER_ID, providerID); sql.appendAnd().append("c."+APPLICATION_STATUS).appendInArrayWithSingleQuotes(applicationStatuses); if (caseCode != null) sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); sql.appendOrderBy("u.last_name, u.first_name, u.middle_name"); if (numberOfEntries == -1) return idoFindPKsBySQL(sql.toString()); else return idoFindPKsBySQL(sql.toString(), numberOfEntries, startingEntry); } public Integer ejbFindApplicationByChildAndApplicationStatus(int childID, String[] applicationStatuses) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID, childID); sql.appendAnd().append("c."+APPLICATION_STATUS).appendInArrayWithSingleQuotes(applicationStatuses); return (Integer) idoFindOnePKByQuery(sql); } public Collection ejbFindApplicationsWithoutPlacing() throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelect().append(" distinct c.* ").appendFrom().append(getEntityName()).append(" c, comm_childcare_archive a"); sql.appendWhereEquals("c."+getIDColumnName(), "a.application_id").appendAnd().append("c." + APPLICATION_STATUS).appendNOTEqual().appendWithinSingleQuotes("E"); sql.appendAnd().append("a.sch_class_member_id").appendIsNull(); return idoFindPKsByQuery(sql); } public Integer ejbFindApplicationByChildAndChoiceNumber(User child, int choiceNumber) throws FinderException { return ejbFindApplicationByChildAndChoiceNumber(((Integer)child.getPrimaryKey()).intValue(), choiceNumber); } public Integer ejbFindApplicationByChildAndChoiceNumber(int childID, int choiceNumber) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).appendWhereEquals(CHOICE_NUMBER, choiceNumber).appendAndEquals(CHILD_ID,childID); return (Integer) idoFindOnePKByQuery(sql); } public Integer ejbFindApplicationByChildAndChoiceNumberWithStatus(int childID, int choiceNumber, String caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.append("select c.* from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID, childID); sql.appendAnd().appendEqualsQuoted("p.case_status", caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code", CASE_CODE_KEY); sql.appendAndEquals(CHOICE_NUMBER, choiceNumber); return (Integer) idoFindOnePKByQuery(sql); } public Integer ejbFindApplicationByChildAndChoiceNumberInStatus(int childID, int choiceNumber, String[] caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID, childID); //sql.appendAnd().appendEqualsQuoted("p.case_code", CASE_CODE_KEY); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); sql.appendAndEquals(CHOICE_NUMBER, choiceNumber); return (Integer) idoFindOnePKByQuery(sql); } public Integer ejbFindApplicationByChildAndChoiceNumberNotInStatus(int childID, int choiceNumber, String[] caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID, childID); //sql.appendAnd().appendEqualsQuoted("p.case_code", CASE_CODE_KEY); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); sql.appendAndEquals(CHOICE_NUMBER, choiceNumber); return (Integer) idoFindOnePKByQuery(sql); } public Collection ejbFindApplicationByChild(int childID) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).appendWhereEquals(CHILD_ID,childID); sql.appendOrderBy(CHOICE_NUMBER); return super.idoFindPKsByQuery(sql); } public Integer ejbFindApplicationByChildAndProvider(int childID, int providerID) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).appendWhereEquals(CHILD_ID,childID); sql.appendAndEquals(PROVIDER_ID, providerID); return (Integer) idoFindOnePKByQuery(sql); } public Integer ejbFindApplicationByChildAndProviderAndStatus(int childID, int providerID, String[] status) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).appendWhereEquals(CHILD_ID,childID); sql.appendAndEquals(PROVIDER_ID, providerID); sql.appendAnd().append(APPLICATION_STATUS).appendInArrayWithSingleQuotes(status); return (Integer) idoFindOnePKByQuery(sql); } public Integer ejbFindNewestApplication(int providerID, Date date) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).appendWhereEquals(PROVIDER_ID, providerID); sql.appendAnd().append(QUEUE_DATE).appendLessThanSign().append(date); sql.appendOrderBy(QUEUE_DATE+" desc, "+QUEUE_ORDER+" desc"); return (Integer) idoFindOnePKByQuery(sql); } public Integer ejbFindOldestApplication(int providerID, Date date) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).appendWhereEquals(PROVIDER_ID, providerID); sql.appendAnd().append(QUEUE_DATE).appendGreaterThanSign().append(date); sql.appendOrderBy(QUEUE_DATE+", "+QUEUE_ORDER); return (Integer) idoFindOnePKByQuery(sql); } public Collection ejbFindApplicationByChildAndNotInStatus(int childID, String[] caseStatus) throws FinderException { return ejbFindApplicationByChildAndNotInStatus(childID, caseStatus, null); } public Collection ejbFindApplicationByChildAndNotInStatus(int childID, String[] caseStatus, String caseCode) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); sql.appendOrderBy(CHOICE_NUMBER); return super.idoFindPKsByQuery(sql); } public Collection ejbFindApplicationByChildAndInStatus(int childID, String[] caseStatus, String caseCode) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); sql.appendOrderBy(CHOICE_NUMBER); return super.idoFindPKsByQuery(sql); } public Integer ejbFindActiveApplicationByChild(int childID) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendAnd().appendEqualsQuoted("p.case_status", "KLAR"); return (Integer) idoFindOnePKByQuery(sql); } public Integer ejbFindActiveApplicationByChildAndStatus(int childID, String[] caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); sql.appendOrderBy(CHOICE_NUMBER); return (Integer) idoFindOnePKByQuery(sql); } public int ejbHomeGetNumberOfActiveApplications(int childID) throws IDOException { return ejbHomeGetNumberOfActiveApplications(childID, null); } public int ejbHomeGetNumberOfActiveApplications(int childID, String caseCode) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } sql.appendAnd().appendEqualsQuoted("p.case_status", "KLAR"); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplicationsByStatusAndActiveDate(int childID, String[] caseStatus, String caseCode, Date activeDate) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } sql.appendAnd().appendLeftParenthesis().append("c."+REJECTION_DATE).appendLessThanOrEqualsSign().append(activeDate); sql.appendOr().append("c."+REJECTION_DATE).appendIsNull().appendRightParenthesis(); return idoGetNumberOfRecords(sql); } public Collection ejbFindApplicationsByProviderAndDate(int providerID, Date date) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).appendWhereEquals(PROVIDER_ID,providerID); sql.appendAndEquals(QUEUE_DATE, date); sql.appendOrderBy(QUEUE_ORDER); return super.idoFindPKsByQuery(sql); } public Collection ejbFindApplicationsBeforeLastReplyDate(Date date, String[] caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); sql.appendAnd().append("c."+LAST_REPLY_DATE).appendLessThanSign().append(date); return idoFindPKsByQuery(sql); } public Collection ejbFindApplicationsByProviderAndBeforeDate(int providerID, Date date, String[] caseStatus) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); if (providerID != -1) { sql.appendAndEquals("c."+PROVIDER_ID,providerID); } sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); sql.appendAnd().append("c."+QUEUE_DATE).appendLessThanSign().append(date); return idoFindPKsByQuery(sql); } public int ejbHomeGetNumberOfApplications(int providerID, String caseStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().appendEqualsQuoted("p.case_status",caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplications(int providerID, String[] caseStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplicationsForChild(int childID) throws IDOException { IDOQuery sql = idoQuery(); sql.appendSelectCountFrom(this).appendWhereEquals(CHILD_ID, childID); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplicationsForChild(int childID, String caseStatus, String caseCode) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); sql.appendAnd().appendEqualsQuoted("p.case_status",caseStatus); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplicationsForChildNotInStatus(int childID, String[] caseStatus) throws IDOException { return ejbHomeGetNumberOfApplicationsForChildNotInStatus(childID, caseStatus, null); } public int ejbHomeGetNumberOfApplicationsForChildNotInStatus(int childID, String[] caseStatus, String caseCode) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplicationsForChildInStatus(int childID, String[] caseStatus, String caseCode) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+CHILD_ID,childID); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); if (caseCode != null) { sql.appendAnd().appendEqualsQuoted("p.case_code",caseCode); } return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfPlacedApplications(int childID, int providerID, String[] caseStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAnd().append("c."+PROVIDER_ID).appendNOTEqual().append(providerID); sql.appendAndEquals(CHILD_ID, childID); sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplications(int providerID, String[] caseStatus, int sortBy, Date fromDate, Date toDate) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); if (sortBy == SORT_DATE_OF_BIRTH) sql.append(", ic_user u"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); if (caseStatus != null) sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); if (sortBy == SORT_DATE_OF_BIRTH) { sql.appendAndEquals("c."+CHILD_ID, "u.ic_user_id"); sql.appendAnd().append("u.date_of_birth").appendGreaterThanOrEqualsSign().append(fromDate); sql.appendAnd().append("u.date_of_birth").appendLessThanOrEqualsSign().append(toDate); } else if (sortBy == SORT_QUEUE_DATE) { sql.appendAnd().append("c."+QUEUE_DATE).appendGreaterThanOrEqualsSign().append(fromDate); sql.appendAnd().append("c."+QUEUE_DATE).appendLessThanOrEqualsSign().append(toDate); } else if (sortBy == SORT_PLACEMENT_DATE) { sql.appendAnd().append("c."+FROM_DATE).appendGreaterThanOrEqualsSign().append(fromDate); sql.appendAnd().append("c."+FROM_DATE).appendLessThanOrEqualsSign().append(toDate); } //sql.appendAnd().appendEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetPositionInQueue(Date queueDate, int providerID, String[] caseStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAndEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendAnd().append(QUEUE_DATE).appendLessThanSign().append(queueDate); return idoGetNumberOfRecords(sql); } public int ejbHomeGetPositionInQueue(Date queueDate, int providerID, String applicationStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count("+CHILD_ID+") from ").append(ENTITY_NAME); sql.appendWhereEquals(PROVIDER_ID,providerID); sql.appendAndEqualsQuoted(APPLICATION_STATUS,applicationStatus); sql.appendAnd().append(QUEUE_DATE).appendLessThanSign().append(queueDate); return idoGetNumberOfRecords(sql); } public int ejbHomeGetPositionInQueueByDate(int queueOrder, Date queueDate, int providerID, String[] caseStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAndEqualsQuoted("p.case_code",CASE_CODE_KEY); sql.appendAndEquals(QUEUE_DATE, queueDate); sql.appendAnd().append(QUEUE_ORDER).appendLessThanOrEqualsSign().append(queueOrder); return idoGetNumberOfRecords(sql); } public int ejbHomeGetPositionInQueueByDate(int queueOrder, Date queueDate, int providerID, String applicationStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count("+CHILD_ID+") from ").append(ENTITY_NAME); sql.appendWhereEquals(PROVIDER_ID,providerID); sql.appendAndEqualsQuoted(APPLICATION_STATUS,applicationStatus); sql.appendAndEquals(QUEUE_DATE, queueDate); sql.appendAnd().append(QUEUE_ORDER).appendLessThanOrEqualsSign().append(queueOrder); return idoGetNumberOfRecords(sql); } public int ejbHomeGetQueueSizeNotInStatus(int providerID, String caseStatus[]) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAndEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetQueueSizeNotInStatus(int providerID, String caseStatus[], Date from, Date to) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); if (from == null) { from = new Date(0L); } if (to == null) { to = Date.valueOf("2999-01-01"); } sql.appendAnd().appendBetweenDates(FROM_DATE, from, to); return idoGetNumberOfRecords(sql); } public int ejbHomeGetBruttoQueueSizeNotInStatus(int providerID, String caseStatus[], Date from, Date to) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); if (from == null) { from = new Date(0L); } if (to == null) { to = Date.valueOf("2999-01-01"); } Date today = new Date(System.currentTimeMillis()); sql.appendAnd().appendBetweenDates(FROM_DATE, from, to) .appendAnd().append("c." + CHILD_ID + " in ") .appendLeftParenthesis() - .appendSelect().append("m.ic_user_id").appendFrom() + .appendSelect().append("c.child_id").appendFrom() .append("comm_childcare_archive a,") .append("comm_childcare c") .appendWhereEquals("a.application_id", "c.comm_childcare_id") .appendAndEqualsQuoted("c.application_status", "F") .appendAnd().appendLeftParenthesis().append("a.terminated_date is null").appendOr() .append("a.terminated_date").appendGreaterThanOrEqualsSign().appendWithinSingleQuotes(today).appendRightParenthesis() .appendAnd().append("a.valid_from_date").appendLessThanSign().appendWithinSingleQuotes(today) .appendRightParenthesis(); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNettoQueueSizeNotInStatus(int providerID, String caseStatus[], Date from, Date to) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); if (from == null) { from = new Date(0L); } if (to == null) { to = Date.valueOf("2999-01-01"); } Date today = new Date(System.currentTimeMillis()); sql.appendAnd().appendBetweenDates(FROM_DATE, from, to) .appendAnd().append("c." + CHILD_ID + " not in ") .appendLeftParenthesis() - .appendSelect().append("m.ic_user_id").appendFrom() + .appendSelect().append("c.child_id").appendFrom() .append("comm_childcare_archive a,") .append("comm_childcare c") .appendWhereEquals("a.application_id", "c.comm_childcare_id") .appendAndEqualsQuoted("c.application_status", "F") .appendAnd().appendLeftParenthesis().append("a.terminated_date is null").appendOr() .append("a.terminated_date").appendGreaterThanOrEqualsSign().appendWithinSingleQuotes(today).appendRightParenthesis() .appendAnd().append("a.valid_from_date").appendLessThanSign().appendWithinSingleQuotes(today) .appendRightParenthesis(); return idoGetNumberOfRecords(sql); } public int ejbHomeGetQueueSizeInStatus(int providerID, String caseStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAndEqualsQuoted("p.case_status",caseStatus); //sql.appendAndEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetQueueSizeInStatus(int providerID, String caseStatus, Date from, Date to) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAndEqualsQuoted("p.case_status",caseStatus); if (from == null) { from = new Date(0L); } if (to == null) { to = Date.valueOf("2999-01-01"); } sql.appendAnd().appendBetweenDates(FROM_DATE, from, to); return idoGetNumberOfRecords(sql); } public int ejbHomeGetBruttoQueueSizeInStatus(int providerID, String caseStatus, Date from, Date to) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAndEqualsQuoted("p.case_status",caseStatus); if (from == null) { from = new Date(0L); } if (to == null) { to = Date.valueOf("2999-01-01"); } Date today = new Date(System.currentTimeMillis()); sql.appendAnd().appendBetweenDates(FROM_DATE, from, to) .appendAnd().append("c." + CHILD_ID + " in ") .appendLeftParenthesis() - .appendSelect().append("m.ic_user_id").appendFrom() + .appendSelect().append("c.child_id").appendFrom() .append("comm_childcare_archive a,") .append("comm_childcare c") .appendWhereEquals("a.application_id", "c.comm_childcare_id") .appendAndEqualsQuoted("c.application_status", "F") .appendAnd().appendLeftParenthesis().append("a.terminated_date is null").appendOr() .append("a.terminated_date").appendGreaterThanOrEqualsSign().appendWithinSingleQuotes(today).appendRightParenthesis() .appendAnd().append("a.valid_from_date").appendLessThanSign().appendWithinSingleQuotes(today) .appendRightParenthesis(); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNettoQueueSizeInStatus(int providerID, String caseStatus, Date from, Date to) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,providerID); sql.appendAndEqualsQuoted("p.case_status",caseStatus); if (from == null) { from = new Date(0L); } if (to == null) { to = Date.valueOf("2999-01-01"); } Date today = new Date(System.currentTimeMillis()); sql.appendAnd().appendBetweenDates(FROM_DATE, from, to) - .appendAnd().append("c." + CHILD_ID + " in ") + .appendAnd().append("c." + CHILD_ID + " not in ") .appendLeftParenthesis() - .appendSelect().append("m.ic_user_id").appendFrom() + .appendSelect().append("c.child_id").appendFrom() .append("comm_childcare_archive a,") .append("comm_childcare c") .appendWhereEquals("a.application_id", "c.comm_childcare_id") .appendAndEqualsQuoted("c.application_status", "F") .appendAnd().appendLeftParenthesis().append("a.terminated_date is null").appendOr() .append("a.terminated_date").appendGreaterThanOrEqualsSign().appendWithinSingleQuotes(today).appendRightParenthesis() .appendAnd().append("a.valid_from_date").appendLessThanSign().appendWithinSingleQuotes(today) .appendRightParenthesis(); return idoGetNumberOfRecords(sql); } public int ejbHomeGetQueueSizeByAreaNotInStatus(int areaID, String caseStatus[]) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p, sch_school s"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("s.sch_school_id","c."+PROVIDER_ID); sql.appendAndEquals("s.sch_school_area_id",areaID); sql.appendAnd().append("p.case_status").appendNotInArrayWithSingleQuotes(caseStatus); //sql.appendAndEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetQueueSizeByAreaInStatus(int areaID, String caseStatus) throws IDOException { IDOQuery sql = idoQuery(); sql.append("select count(c."+CHILD_ID+") from ").append(ENTITY_NAME).append(" c , proc_case p, sch_school s"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("s.sch_school_id","c."+PROVIDER_ID); sql.appendAndEquals("s.sch_school_area_id",areaID); sql.appendAndEqualsQuoted("p.case_status",caseStatus); //sql.appendAndEqualsQuoted("p.case_code",CASE_CODE_KEY); return idoGetNumberOfRecords(sql); } public int ejbHomeGetNumberOfApplicationsByProviderAndChoiceNumber(int providerID, int choiceNumber) throws IDOException { IDOQuery sql = idoQuery(); sql.appendSelectCountFrom(this).appendWhereEquals(PROVIDER_ID, providerID); sql.appendAndEquals(CHOICE_NUMBER, choiceNumber); return idoGetNumberOfRecords(sql); } public boolean isAcceptedByParent() { return getStatus().equals("PREL") && //CaseBMPBean.CASE_STATUS_PRELIMINARY_KEY (make public...?) getApplicationStatus() == 'D'; //ChildCareBusinessBean.STATUS_PARENTS_ACCEPT (make public...?) } public boolean isCancelledOrRejectedByParent() { return getStatus().equals("TYST") //CaseBMPBean.CASE_STATUS_INACTIVE_KEY (make public...?) && (getApplicationStatus() == 'Z' //ChildCareBusinessBean.STATUS_CANCELLED (make public...?) || getApplicationStatus() == 'V'); //ChildCareBusinessBean.STATUS_REJECTED (make public...?) } public boolean isActive(){ Contract contract = getContract(); java.util.Date today = new java.util.Date(); return contract != null && contract.getValidFrom().compareTo(today) <= 0 && contract.getValidTo().compareTo(today) >= 0 && contract.isSigned(); } public Collection ejbFindApplicationsInSchoolAreaByStatus(int schoolAreaID, String[] statuses, int choiceNumber) throws FinderException { IDOQuery sql = idoQuery(); sql.appendSelectAllFrom(this).append(" c, proc_case p, sch_school s"); sql.appendWhereEquals("c."+getIDColumnName(), "p.proc_case_id"); sql.appendAndEquals("c."+PROVIDER_ID,"s.sch_school_id"); sql.appendAndEquals("s.sch_school_area_id", schoolAreaID); if (choiceNumber != -1) { sql.appendAndEquals(CHOICE_NUMBER, choiceNumber); } sql.appendAnd().append("p.case_status").appendInArrayWithSingleQuotes(statuses); sql.appendOrderBy("c."+APPLICATION_STATUS+" desc, c."+QUEUE_DATE+", c."+QUEUE_ORDER); return idoFindPKsByQuery(sql); } } \ No newline at end of file
false
false
null
null
diff --git a/Lib_Gui/src/net/sf/anathema/lib/gui/dialog/progress/UnstyledProgressDialog.java b/Lib_Gui/src/net/sf/anathema/lib/gui/dialog/progress/UnstyledProgressDialog.java index dc24e152c4..7a28c75514 100644 --- a/Lib_Gui/src/net/sf/anathema/lib/gui/dialog/progress/UnstyledProgressDialog.java +++ b/Lib_Gui/src/net/sf/anathema/lib/gui/dialog/progress/UnstyledProgressDialog.java @@ -1,92 +1,89 @@ package net.sf.anathema.lib.gui.dialog.progress; import com.google.common.base.Preconditions; import net.miginfocom.layout.AC; import net.miginfocom.layout.CC; import net.miginfocom.layout.LC; import net.miginfocom.swing.MigLayout; import net.sf.anathema.lib.gui.swing.GuiUtilities; import net.sf.anathema.lib.progress.IObservableCancelable; import net.sf.anathema.lib.progress.IProgressMonitor; import org.jdesktop.swingx.JXLabel; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JPanel; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Font; import java.awt.Insets; -import java.awt.Point; public class UnstyledProgressDialog extends AbstractProgressDialog implements IProgressMonitor, IObservableCancelable, IProgressComponent { private final Component parentComponent; private final String title; public UnstyledProgressDialog(Component parentComponent, String title, InternalProgressDialogModel model) { super(model, new SimpleProgressMonitorComponent()); Preconditions.checkNotNull(model); this.parentComponent = parentComponent; this.title = title; } @Override protected JDialog createDialog() { JDialog newDialog = GuiUtilities.createRawDialogForParentComponent(parentComponent); newDialog.setTitle(title); newDialog.setUndecorated(true); createContent(newDialog); newDialog.pack(); if (parentComponent instanceof Container) { coverParentContainer(newDialog); makeMilky(newDialog); } else { GuiUtilities.centerToParent(newDialog); makeTransparent(newDialog); } newDialog.setResizable(false); newDialog.setModal(true); return newDialog; } private void createContent(JDialog newDialog) { JPanel panel = new JPanel(new MigLayout(new LC().fill().wrapAfter(1), new AC().align("center"), new AC().align("center").grow().fill())); JComponent containerContent = getContainerContent(); panel.add(containerContent, new CC().pos("0.5al", "0.5al")); JXLabel textDisplay = new JXLabel(title); textDisplay.setLineWrap(true); textDisplay.setFont(textDisplay.getFont().deriveFont(Font.BOLD).deriveFont(30f)); textDisplay.setTextAlignment(JXLabel.TextAlignment.CENTER); panel.add(textDisplay, new CC().dockSouth().gapBottom("20")); panel.setOpaque(false); newDialog.getContentPane().add(panel); } private void makeMilky(JDialog newDialog) { Color background = new Color(255, 255, 255, 130); configureBackground(newDialog, background); } private void coverParentContainer(JDialog newDialog) { Insets insets = ((Container) parentComponent).getInsets(); newDialog.setSize(parentComponent.getWidth() - insets.left - insets.right, parentComponent.getHeight() - insets.top - insets.bottom); - Point location = newDialog.getLocation(); - newDialog.setLocation(parentComponent.getLocationOnScreen().x + location.x + insets.left, - parentComponent.getLocationOnScreen().y + location.y + insets.top); + newDialog.setLocation(parentComponent.getX() + insets.left, parentComponent.getY() + insets.top); } private void makeTransparent(JDialog newDialog) { Color background = new Color(0, 0, 0, 0); configureBackground(newDialog, background); } private void configureBackground(JDialog newDialog, Color background) { newDialog.getContentPane().setBackground(background); newDialog.setBackground(background); newDialog.getRootPane().setOpaque(false); } } \ No newline at end of file
false
false
null
null
diff --git a/hu.documaison.dal/src/hu/documaison/dal/interfaces/DalImplementation.java b/hu.documaison.dal/src/hu/documaison/dal/interfaces/DalImplementation.java index 59d7d6e..e5a67b3 100644 --- a/hu.documaison.dal/src/hu/documaison/dal/interfaces/DalImplementation.java +++ b/hu.documaison.dal/src/hu/documaison/dal/interfaces/DalImplementation.java @@ -1,1080 +1,1085 @@ /** * */ package hu.documaison.dal.interfaces; import hu.documaison.dal.database.DatabaseUtils; import hu.documaison.data.entities.*; import hu.documaison.data.exceptions.UnknownDocumentException; import hu.documaison.data.exceptions.UnknownDocumentTypeException; import hu.documaison.data.search.BoolOperator; import hu.documaison.data.search.Expression; import hu.documaison.data.search.SearchExpression; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import com.j256.ormlite.support.ConnectionSource; /** * @author Dani * */ class DalImplementation implements DalInterface { private <T extends DatabaseObject> T genericCreate(Class<T> c, String info) { T instance; try { instance = c.newInstance(); } catch (InstantiationException e) { return null; } catch (IllegalAccessException e) { return null; } return genericCreate(c, instance, info); } private <T extends DatabaseObject> T genericCreate(Class<T> c, T instance, String info) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<T, Integer> dao = DaoManager.createDao(connectionSource, c); // add T ret = instance; dao.create(ret); return ret; } catch (SQLException e) { HandleSQLException(e, info); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, info); } } } return null; } private <T extends DatabaseObject> void genericDelete(int id, Class<T> c, String info) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<T, Integer> dao = DaoManager.createDao(connectionSource, c); // delete dao.deleteById(id); } catch (SQLException e) { HandleSQLException(e, info); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, info); } } } } private <T extends DatabaseObject> void genericUpdate(T entity, Class<T> c, String info) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<T, Integer> dao = DaoManager.createDao(connectionSource, c); // update dao.update(entity); } catch (SQLException e) { HandleSQLException(e, info); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, info); } } } } @Override public Comment createComment() { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Comment, Integer> dao = DaoManager.createDao(connectionSource, Comment.class); // add Comment comment = new Comment(); dao.create(comment); return comment; } catch (SQLException e) { HandleSQLException(e, "createComment"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "createComment"); } } } return null; } @Override public DefaultMetadata createDefaultMetadata() { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<DefaultMetadata, Integer> dao = DaoManager.createDao( connectionSource, DefaultMetadata.class); // add DefaultMetadata ret = new DefaultMetadata(); dao.create(ret); return ret; } catch (SQLException e) { HandleSQLException(e, "createDefaultMetadata"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "createDefaultMetadata"); } } } return null; } @Override public Document createDocument(int typeId) throws UnknownDocumentTypeException { // create a connection source to our database ConnectionSource connectionSource = null; try { DocumentType documentType = this.getDocumentType(typeId); if (documentType == null) { throw new UnknownDocumentTypeException(typeId); } // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); // add Document newDocument = new Document(documentType, dao); - if (documentType.getDefaultMetadataCollection() != null) { - for (DefaultMetadata md : documentType - .getDefaultMetadataCollection()) { - newDocument.addMetadata(md.createMetadata()); - } - } - if (documentType.getDefaultThumbnailBytes() != null) { - newDocument.setThumbnailBytes(documentType - .getDefaultThumbnailBytes().clone()); - } - newDocument.setDateAdded(new Date()); - dao.create(newDocument); + + // set properties + + // following lines moved to BLL +// if (documentType.getDefaultMetadataCollection() != null) { +// for (DefaultMetadata md : documentType +// .getDefaultMetadataCollection()) { +// newDocument.addMetadata(md.createMetadata()); +// } +// } +// if (documentType.getDefaultThumbnailBytes() != null) { +// newDocument.setThumbnailBytes(documentType +// .getDefaultThumbnailBytes().clone()); +// } + newDocument.setDateAdded(new Date()); + dao.update(newDocument); + return newDocument; } catch (SQLException e) { HandleSQLException(e, "createDocument"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "createDocument"); } } } return null; } @Override public DocumentType createDocumentType() { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<DocumentType, Integer> dao = DaoManager.createDao( connectionSource, DocumentType.class); // add DocumentType documentType = new DocumentType(dao); dao.create(documentType); return documentType; } catch (SQLException e) { HandleSQLException(e, "createDocumentType"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "createDocumentType"); } } } return null; } @Override public Metadata createMetadata() { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Metadata, Integer> dao = DaoManager.createDao(connectionSource, Metadata.class); // add Metadata ret = new Metadata(); dao.create(ret); return ret; } catch (SQLException e) { HandleSQLException(e, "createMetadata"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "createMetadata"); } } } return null; } @Override public Tag createTag(String name) { return genericCreate(Tag.class, "createTag"); } @Override public Document getDocument(int id) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); // query Document ret = dao.queryForId(id); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getDocument"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getDocument"); } } } return null; } // @Override // public void addTag(Tag tag) { // // create a connection source to our database // ConnectionSource connectionSource = null; // // try { // // create connection // connectionSource = DatabaseUtils.getConnectionSource(); // // // instantiate the dao // Dao<Tag, Integer> dao = DaoManager.createDao(connectionSource, // Tag.class); // // // add // dao.create(tag); // // } catch (SQLException e) { // HandleSQLException(e, "addTag"); // } finally { // // close connection // if (connectionSource != null) { // try { // connectionSource.close(); // } catch (SQLException e) { // HandleSQLException(e, "addTag"); // } // } // } // } @Override public Collection<Document> getDocuments() { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); // query List<Document> ret = dao.queryForAll(); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getDocuments"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getDocuments"); } } } return null; } @Override public Collection<Document> getDocumentsByTags(List<Tag> tags) { if (tags == null){ return new ArrayList<Document>(); } ArrayList<Integer> tagIds = new ArrayList<Integer>(); for (Tag t : tags){ tagIds.add(t.getId()); } return getDocumentsByTagIds(tagIds); } @Override public Collection<Document> getDocumentsByTag(Tag tag) { return getDocumentsByTagId(tag.getId()); } private Collection<Document> getDocumentsByTagId(int tagId) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); Dao<DocumentTagConnection, Integer> daoTags = DaoManager.createDao(connectionSource, DocumentTagConnection.class); // query QueryBuilder<Document, Integer> qb = dao.queryBuilder(); QueryBuilder<DocumentTagConnection, Integer> qbTags = daoTags.queryBuilder(); qbTags.where().eq(DocumentTagConnection.TAGID, tagId); qb.join(qbTags); System.out.println("Query: " + qb.prepareStatementString()); List<Document> ret = dao.query(qb.prepare()); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getDocumentsByTagId(int)"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getDocumentsByTagId(int)"); } } } return null; } private Collection<Document> getDocumentsByTagIds(List<Integer> tagIds) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); Dao<DocumentTagConnection, Integer> daoTags = DaoManager.createDao(connectionSource, DocumentTagConnection.class); // query QueryBuilder<Document, Integer> qb = dao.queryBuilder(); QueryBuilder<DocumentTagConnection, Integer> qbTags = daoTags.queryBuilder(); qbTags.where().in(DocumentTagConnection.TAGID, tagIds); qb.join(qbTags); qb.distinct(); System.out.println("Query: " + qb.prepareStatementString()); List<Document> ret = dao.query(qb.prepare()); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getDocumentsByTagId(int)"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getDocumentsByTagId(int)"); } } } return null; } @Override public DocumentType getDocumentType(int id) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<DocumentType, Integer> dao = DaoManager.createDao( connectionSource, DocumentType.class); // query DocumentType ret = dao.queryForId(id); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getDocumentType"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getDocumentType"); } } } return null; } @Override public Collection<DocumentType> getDocumentTypes() { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<DocumentType, Integer> dao = DaoManager.createDao( connectionSource, DocumentType.class); // query List<DocumentType> ret = dao.queryForAll(); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getDocumentTypes"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getDocumentTypes"); } } } return null; } @Override public Tag getTag(int id) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Tag, Integer> dao = DaoManager.createDao(connectionSource, Tag.class); // query Tag ret = dao.queryForId(id); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getTags"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getTags"); } } } return null; } // @Override // public void addDocumentType(DocumentType documentType) { // // create a connection source to our database // ConnectionSource connectionSource = null; // // try { // // create connection // connectionSource = DatabaseUtils.getConnectionSource(); // // // instantiate the dao // Dao<DocumentType, Integer> dao = DaoManager.createDao( // connectionSource, DocumentType.class); // // // add // dao.create(documentType); // // } catch (SQLException e) { // HandleSQLException(e, "addDocumentType"); // } finally { // // close connection // if (connectionSource != null) { // try { // connectionSource.close(); // } catch (SQLException e) { // HandleSQLException(e, "addDocumentType"); // } // } // } // } @Override public Tag getTag(String name) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Tag, Integer> dao = DaoManager.createDao(connectionSource, Tag.class); // query Tag ret = dao.queryForFirst(dao.queryBuilder().where() .eq(Tag.NAME, name).prepare()); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getTag"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getTag"); } } } return null; } @Override public Collection<Tag> getTags() { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Tag, Integer> dao = DaoManager.createDao(connectionSource, Tag.class); // query List<Tag> ret = dao.queryForAll(); // return return ret; } catch (SQLException e) { HandleSQLException(e, "getTags"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "getTags"); } } } return null; } private void HandleSQLException(SQLException e, String method) { System.err.println("Exception @ " + method); e.printStackTrace(); } @Override public void removeComment(int id) { genericDelete(id, Comment.class, "removeComment"); } @Override public void removeDefaultMetadata(int id) { genericDelete(id, DefaultMetadata.class, "removeDefaultMetadata"); } @Override public void removeDocument(int id) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); // delete dao.deleteById(id); } catch (SQLException e) { HandleSQLException(e, "removeDocument"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "removeDocument"); } } } } @Override public void removeDocumentType(int id) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<DocumentType, Integer> dao = DaoManager.createDao( connectionSource, DocumentType.class); // add dao.deleteById(id); } catch (SQLException e) { HandleSQLException(e, "removeDocumentType"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "removeDocumentType"); } } } } @Override public void removeMetadata(int id) { genericDelete(id, Metadata.class, "removeMetadata"); } @Override public void removeTag(int id) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Tag, Integer> dao = DaoManager.createDao(connectionSource, Tag.class); // delete dao.deleteById(id); } catch (SQLException e) { HandleSQLException(e, "removeTag"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "removeTag"); } } } } @Override public void updateComment(Comment comment) { genericUpdate(comment, Comment.class, "updateComment"); } @Override public void updateDefaultMetadata(DefaultMetadata metadata) { genericUpdate(metadata, DefaultMetadata.class, "updateDefaultMetadata"); } @Override public void updateDocument(Document document) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); // update dao.update(document); } catch (SQLException e) { HandleSQLException(e, "updateDocument"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "updateDocument"); } } } } @Override public void updateDocumentType(DocumentType documentType) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<DocumentType, Integer> dao = DaoManager.createDao( connectionSource, DocumentType.class); // update dao.update(documentType); } catch (SQLException e) { HandleSQLException(e, "updateDocumentType"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "updateDocumentType"); } } } } @Override public void updateMetadata(Metadata metadata) { genericUpdate(metadata, Metadata.class, "updateMetadata"); } @Override public void updateTag(Tag tag) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Tag, Integer> dao = DaoManager.createDao(connectionSource, Tag.class); // update dao.update(tag); } catch (SQLException e) { HandleSQLException(e, "updateTag"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "updateTag"); } } } } @Override public Collection<Document> searchDocuments(SearchExpression sexpr) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<Document, Integer> dao = DaoManager.createDao(connectionSource, Document.class); // instantiate the metadata dao Dao<Metadata, Integer> daoMD = DaoManager.createDao( connectionSource, Metadata.class); // query QueryBuilder<Document, Integer> qb = dao.queryBuilder(); QueryBuilder<Metadata, Integer> qbMD = daoMD.queryBuilder(); qb.join(qbMD); // TODO: review Where<Metadata, Integer> where = qbMD.where(); Boolean notFirst = false; for (Expression expr : sexpr.getExpressions()) { // Expression-�k �sszef�z�se if (notFirst) { if (sexpr.getBoolOperator() == BoolOperator.or) { where.or(); } else { where.and(); } } qbMD.where().eq(AbstractMetadata.NAME, expr.getMetadataName()); switch (expr.getOperator()) { case eq: where.and().eq(AbstractMetadata.VALUE, expr.getValue()); break; case ge: where.and().ge(AbstractMetadata.VALUE, expr.getValue()); break; case gt: where.and().gt(AbstractMetadata.VALUE, expr.getValue()); break; case contains: where.and().like(AbstractMetadata.VALUE, "%" + expr.getValue() + "%"); break; case le: where.and().le(AbstractMetadata.VALUE, expr.getValue()); break; case like: where.and().like(AbstractMetadata.VALUE, expr.getValue()); break; case lt: where.and().lt(AbstractMetadata.VALUE, expr.getValue()); break; case neq: where.and().ne(AbstractMetadata.VALUE, expr.getValue()); break; default: break; } notFirst = true; } System.out.println("Search for: " + where.getStatement()); // TODO: // delete List<Document> ret = dao.query(qb.prepare()); // return return ret; } catch (SQLException e) { HandleSQLException(e, "searchDocuments(SearchExpression)"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "searchDocuments(SearchExpression)"); } } } return null; } @Override public void addTagToDocument(Tag tag, Document document) { DocumentTagConnection dtc = new DocumentTagConnection(); dtc.setDocument(document); dtc.setTag(tag); dtc = genericCreate(DocumentTagConnection.class, dtc, "addTagToDocument"); genericUpdate(dtc, DocumentTagConnection.class, "addTagToDocument"); } @Override public void removeTagFromDocument(Tag tag, Document document) { // create a connection source to our database ConnectionSource connectionSource = null; try { // create connection connectionSource = DatabaseUtils.getConnectionSource(); // instantiate the dao Dao<DocumentTagConnection, Integer> dao = DaoManager.createDao( connectionSource, DocumentTagConnection.class); // query DeleteBuilder<DocumentTagConnection, Integer> db = dao .deleteBuilder(); db.where().eq(DocumentTagConnection.DOCUMENTID, document.getId()) .and().eq(DocumentTagConnection.TAGID, tag.getId()); dao.delete(db.prepare()); } catch (SQLException e) { HandleSQLException(e, "removeTagFromDocument"); } finally { // close connection if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException e) { HandleSQLException(e, "removeTagFromDocument"); } } } } }
false
false
null
null
diff --git a/src/cytoscape/actions/CreateNetworkViewAction.java b/src/cytoscape/actions/CreateNetworkViewAction.java index b33baacb5..4922258d6 100644 --- a/src/cytoscape/actions/CreateNetworkViewAction.java +++ b/src/cytoscape/actions/CreateNetworkViewAction.java @@ -1,53 +1,53 @@ package cytoscape.actions; import cytoscape.CyNetwork; import cytoscape.Cytoscape; import cytoscape.CytoscapeInit; import cytoscape.util.CytoscapeAction; import javax.swing.*; import java.awt.event.ActionEvent; import java.text.NumberFormat; import java.text.DecimalFormat; public class CreateNetworkViewAction extends CytoscapeAction { public CreateNetworkViewAction() { super("Create View"); setPreferredMenu("Edit"); setAcceleratorCombo(java.awt.event.KeyEvent.VK_V, ActionEvent.ALT_MASK); } public CreateNetworkViewAction(boolean label) { super(); } public void actionPerformed(ActionEvent e) { CyNetwork cyNetwork = Cytoscape.getCurrentNetwork(); createViewFromCurrentNetwork(cyNetwork); } public static void createViewFromCurrentNetwork(CyNetwork cyNetwork) { - System.out.println("Secondary View Threshold: " - + CytoscapeInit.getSecondaryViewThreshold()); NumberFormat formatter = new DecimalFormat("#,###,###"); if (cyNetwork.getNodeCount() > CytoscapeInit.getSecondaryViewThreshold()) { int n = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), "Network contains " + formatter.format(cyNetwork.getNodeCount()) + " nodes and " + formatter.format (cyNetwork.getEdgeCount()) + " edges. " + "\nRendering a network this size may take several " + "minutes.\n" + "Do you wish to proceed?", "Rendering Large Network", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } else { JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "Create View Request Cancelled by User."); } + } else { + Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } } }
false
true
public static void createViewFromCurrentNetwork(CyNetwork cyNetwork) { System.out.println("Secondary View Threshold: " + CytoscapeInit.getSecondaryViewThreshold()); NumberFormat formatter = new DecimalFormat("#,###,###"); if (cyNetwork.getNodeCount() > CytoscapeInit.getSecondaryViewThreshold()) { int n = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), "Network contains " + formatter.format(cyNetwork.getNodeCount()) + " nodes and " + formatter.format (cyNetwork.getEdgeCount()) + " edges. " + "\nRendering a network this size may take several " + "minutes.\n" + "Do you wish to proceed?", "Rendering Large Network", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } else { JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "Create View Request Cancelled by User."); } } }
public static void createViewFromCurrentNetwork(CyNetwork cyNetwork) { NumberFormat formatter = new DecimalFormat("#,###,###"); if (cyNetwork.getNodeCount() > CytoscapeInit.getSecondaryViewThreshold()) { int n = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), "Network contains " + formatter.format(cyNetwork.getNodeCount()) + " nodes and " + formatter.format (cyNetwork.getEdgeCount()) + " edges. " + "\nRendering a network this size may take several " + "minutes.\n" + "Do you wish to proceed?", "Rendering Large Network", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } else { JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "Create View Request Cancelled by User."); } } else { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } }
diff --git a/src/WMLL.java b/src/WMLL.java index c38a738..239cf28 100644 --- a/src/WMLL.java +++ b/src/WMLL.java @@ -1,1525 +1,1524 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.net.SocketAddress; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.minecraft.client.Minecraft; import net.minecraft.server.MinecraftServer; import org.lwjgl.input.Keyboard; import reifnsk.minimap.ReiMinimap; public class WMLL { public static final String wmllVersion() { - return "Test 791"; // 789 + return "Test 802"; } public static final String getMinecraftVersion() { return "1.5"; } public static final String[] autoDisable = {".*\\.oc\\.tc"}; public static final List<Integer> blockBlackList = Arrays.asList(0, 8, 7, 9, 20, 44, 50, 130); public static final Map<String, String> fieldNames = new HashMap<String, String>(); public static final WMLLUpdateCheck wmllUpdateCheck = new WMLLUpdateCheck(); public static WMLL i = new WMLL(); public static boolean Enabled = true; public static int WMLLI; public static boolean debugActive; public static int F4Key; public static int TextColour; public static Properties options; public static Properties outputOptions; public static int outputLocation; public static boolean useImages; public static int clockSetting; public static boolean optionsOpen = false; public static int[] playerPos; public static boolean militaryclock; public long worldSeed = 0L; public boolean autoSeed = true; public Minecraft mc; public boolean wmllOverrideF3; public int F3Type; public boolean showSeedWithCoords; public boolean debugClassPresent = false; public boolean classicOutput = false; public boolean autoUpdateCheck = true; public boolean compatDisabled = false; public boolean showUnderGUIs = true; private static final int propertiesVersion = 3; public static File settingsFile, outputOptionsFile; public static long lastUpdateCheck = 0; private static final Calendar calendar = Calendar.getInstance(); private WMLLRenderer wmllRenderer; private WMLLF3 wmllF3; public boolean Rei, ReiUseMl, RadarBro, AlienRadar, ZansMinimap, ReiEnabled, AlienEnabled, ZansEnabled, forgeDetected, forgeEnabled, useForge; private Object alienRadar; private Object zansMinimap; public boolean satBar; private boolean ranInit = false; public boolean firstRun = true; private final String[] sleepstrings = {"What's My Arrow Level?", "Almost makes you wish for a nuclear winter!", "1 byte of posts!", "Kuurth for 1000!", "Paralympics!", "Olympics!", "London 2012!", "Would you kindly?", "Goodnight, PLAYERNAME!", "This is my bed. There are many like it, but this one is mine.", "If it fits, I sleeps!", "*fade to blackness*", "*water drip*", "Goodnight, Hero!", "ZzzzzZZz", "That'sssssssss a very nice bed you have there...", "That bed looks comfy!", "*snoring*", "...aaaaaannnnddd asleepness!", "Muuuuuuurrrrh", "*clank*", "*screech*"}; private boolean sleepingStringSet = false; private String lightString = "Light level: 9001"; private long lastF4Press = 0; private boolean wmllF3Output = false; private awp fontRenderer; public String lastWorld = ""; public boolean worldSeedSet = false; public boolean warnedAboutConflicts = false; public String reiError = "Not found", zanError = "Not found", alienError = "Not found", forgeError = "Not found"; public String[] updateInfo = {}; protected WMLLCompatibility wmllCompatibility; public boolean showWorldName = true; public WMLL() { debug("[WMLL] Initializing WMLL "+wmllVersion()); fieldNames.put("sendQueue", "i"); fieldNames.put("netManager", "g"); - fieldNames.put("remoteSocketAddress", "j"); + fieldNames.put("remoteSocketAddress", "k"); fieldNames.put("SPremoteSocketAddress", "a"); fieldNames.put("genNetherBridge", "c"); fieldNames.put("SpawnListEntry", "a"); fieldNames.put("localServerWorldName", "b"); fieldNames.put("worldSeed", "a"); fieldNames.put("chatLines", "c"); Rei = ReiUseMl = RadarBro = false; this.debugClassPresent = (getClass().getClassLoader().getResource("ipeer_wmll_debug") != null); debugActive = this.debugClassPresent; settingsFile = new File("./mods/WMLL"); if (!settingsFile.exists()) settingsFile.mkdirs(); settingsFile = new File(settingsFile, "WMLL.properties"); outputOptionsFile = new File(Minecraft.a("minecraft"), "WMLLOutput.properties"); try { wmllCompatibility = new WMLLCompatibility(); } catch (Exception e) { shitBricks(1, e); } catch (Error e) { shitBricks(1, e); } compatDisabled = (getClass().getClassLoader().getResource("WMLLCompatibility.class") == null); if (compatDisabled) debug("[WMLL] Couldn't create compatibility object (class missing)."); loadOptions(); this.autoSeed = Boolean.parseBoolean(options.getProperty("autoAquireSeed", "true")); if (getClass().getClassLoader().getResource("net/minecraftforge/common/ForgeHooks.class") != null) { useForge = forgeDetected = true; forgeError = ""; } if (getClass().getClassLoader().getResource("mod_ReiMinimap.class") != null) { try { Rei = true; ReiUseMl = ReiMinimap.instance.useModloader; } catch(VerifyError e) { shitBricks(2, e); } } if (getClass().getClassLoader().getResource("MotionTracker.class") != null) { try { AlienRadar = true; alienRadar = new MotionTracker(); } catch (VerifyError e) { shitBricks(3, e); AlienRadar = false; } } if (getClass().getClassLoader().getResource("ZanMinimap.class") != null) { try { ZansMinimap = true; zansMinimap = new ZanMinimap(); zanError = ""; } catch (VerifyError e) { shitBricks(4, e); ZansMinimap = false; } catch (NoClassDefFoundError e) { shitBricks(4, e); ZansMinimap = false; } } if (getClass().getClassLoader().getResource("RadarBro.class") != null) { RadarBro = true; } if (debugClassPresent) { RadarBro = false; useForge = false; } if (outputOptionsFile.exists()) { debug("[WMLL] WMLLOutput.properties exists, merging with WMLL.properties"); try { Properties a = new Properties(); a.load(new FileInputStream(outputOptionsFile)); options.putAll(a); saveOptions(); outputOptionsFile.deleteOnExit(); debug("[WMLL] Succesfully merged files."); } catch (IOException w) { debug("[WMLL] Unable to merge files (IOException)\n"); w.printStackTrace(); } } debug("[WMLL] WMLL is"+(debugClassPresent ? "" : " not")+" running in debug mode"); if (Rei) debug("[WMLL] WMLL is running in Rei's Minimap Compatibility mode"); if (useForge) debug("[WMLL] WMLL is running in Forge Compatibility mode"); if (RadarBro) debug("[WMLL] WMLL is running in RadarBro Compatibility mode"); if (satBar) debug("[WMLL] WMLL is running in Saturation Bar Compatibility mode"); if (AlienRadar) debug("[WMLL] WMLL is running in Alien Radar Compatibility mode"); debug("[WMLL] Updater: "+autoUpdateCheck); debug("[WMLL] Debug Data:"); try { debug("\t* "+wmllCompatibility.toString()); } catch (Exception e) { debug("\t* null"); } debug("\t* "+this.toString()); try { debug("\t* "+settingsFile.getCanonicalPath()); } catch (IOException e) { } for (String a : fieldNames.keySet()) debug("\t* "+a+": "+fieldNames.get(a)); debug("[WMLL] WMLL "+wmllVersion()+" initialized."); } public void updategui(Minecraft h) { updategui(h, h.w); } public void updategui(Minecraft h, awq awq) { if (getWorld() != null && !wmllUpdateCheck.running && autoUpdateCheck) { wmllUpdateCheck.start(); } else if (getWorld() == null && wmllUpdateCheck.running) { System.out.println("[WMLL] FATAL: World == NULL! -- Stopping update thread."); wmllUpdateCheck.stop1(); } if (getWorld() != null && !getWorldName().equals(lastWorld) && autoSeed) { worldSeedSet = false; lastWorld = getWorldName(); // if (!options.containsKey("Seed:"+getWorldName().toLowerCase()) && !isMultiplayer()) // entityPlayer().d("/seed"); - debug("[WMLL] World name differs, re-acquiring seed..."); + if (!isMultiplayer()) + debug("[WMLL] World name differs, re-acquiring seed..."); boolean[] b = {Rei && ReiEnabled, ZansMinimap && ZansEnabled, AlienRadar && AlienEnabled}; if (atLeast2True(b) && !warnedAboutConflicts) { ReiEnabled = ZansEnabled = AlienEnabled = false; sendChatMessage("[\2472WMLL\247f] \247cWMLL has detected that you have multiple minimap mods installed and enabled. To prevent crashes"); sendChatMessage("[\2472WMLL\247f] \247cWMLL has disabled them all temporarily. Please go into WMLL's config and press \"Compatibility Settings\" and enable the one you wish to use."); //sendChatMessage("[\2472WMLL\247f] \247cand enable the one you wish to use."); } if (!isEnabled()) entityPlayer().a("[\2472WMLL\247f] \247cWMLL has been disabled on this "+(isMultiplayer() ? "server" : "world")+"."); } - if (!worldSeedSet && getWorld() != null) { + if (!worldSeedSet && getWorld() != null && !isMultiplayer()) { try { if (options.getProperty("Seed:"+getWorldName().toLowerCase()) != null) { worldSeedSet = true; this.worldSeed = Long.valueOf(options.getProperty("Seed:"+getWorldName().toLowerCase())); debug("[WMLL] Seed set to "+this.worldSeed+" (from file)"); } else { worldSeedSet = true; this.worldSeed = ((zv)MinecraftServer.D().a(0)).F(); debug("[WMLL] Seed set to "+this.worldSeed); /*Object obj = awq.b(); Field f = obj.getClass().getDeclaredField(getField("chatLines")); f.setAccessible(true); obj = f.get(obj); @SuppressWarnings("unchecked") List<String> a = (List<String>)obj; @SuppressWarnings("rawtypes") Iterator c = a.iterator(); int e = 0; while (c.hasNext()) { e++; aut d = (aut)c.next(); String b = d.a(); //d.a(); if (b.startsWith("Seed: ")) { //aow.b().a(); //if (!isMultiplayer()) //a.remove(e - 1); c.remove(); long worldSeed = Long.parseLong(b.split("Seed: ")[1]); worldSeedSet = true; this.worldSeed = worldSeed; debug("[WMLL] Seed set to "+worldSeed); break; } }*/ } } catch (Exception e) { e.printStackTrace(); } //skip; } if (firstRun && getWorld() != null) { firstRun = false; wmllRenderer.firstRun = true; } if (Rei && !ReiUseMl && ReiEnabled) ReiMinimap.instance.onTickInGame(h); if (AlienRadar && AlienEnabled && alienRadar != null && getWorld() != null) ((MotionTracker)alienRadar).onTickInGame(mc); if (ZansMinimap && ZansEnabled && zansMinimap != null && getWorld() != null) ((ZanMinimap)zansMinimap).onTickInGame(mc); if (!ranInit) { this.mc = h; wmllRenderer = new WMLLRenderer(mc, this); wmllF3 = new WMLLF3(mc, this); ranInit = true; this.fontRenderer = h.q; if (debugClassPresent) entityPlayer().a("Test"); //(new Thread(wmllUpdateCheck)).start(); } if (mcDebugOpen() || wmllF3Output) { if (mcDebugOpen() && wmllOverrideF3) toggleF3Override(); else if (mcDebugOpen() && !wmllOverrideF3) drawStringUsingPixels("WMLL "+wmllVersion(), 2, 52, 0xfffffe); else wmllF3.draw(); } else { if (satBar && !compatDisabled) { try { wmllCompatibility.drawSaturationBar(mc, this); } catch (NoSuchMethodError n) { satBar = false; } catch (NoClassDefFoundError n1) { satBar = false; } catch (NoSuchFieldError n2) { satBar = false; } catch (NullPointerException n3) { satBar = false; } // 12W40 ERROR catch (Error e) { satBar = false; } } if (RadarBro && !compatDisabled) try { wmllCompatibility.RadarBroRun(mc, this); } catch (NoSuchMethodError n) { } catch (NoClassDefFoundError n1) { } catch (NoSuchFieldError n2) { } Enabled = isEnabled(); if (WMLLDebugActive()) { int x = getPlayerCoordinates()[0]; int z = getPlayerCoordinates()[2]; String worldName = getWorldName()+" ("+isMultiplayer()+")"; drawDebug(worldName, (getWindowSize().a() - (getFontRenderer().a(worldName) + 1)), 0, 0xffffff); drawDebug(Integer.toString(getDimension()), (getWindowSize().a() - (getFontRenderer().a(Integer.toString(getDimension())) + 1)), 1, 0xffffff); drawDebug(Boolean.toString(isPlayerSleeping()), (getWindowSize().a() - (getFontRenderer().a(Boolean.toString(isPlayerSleeping())) + 1)), 2, 0xffffff); drawDebug(Integer.toString(WMLLI), (getWindowSize().a() - (getFontRenderer().a(Integer.toString(WMLLI)) + 1)), 3, 0xffffff); int blockID = getBlockID(getPlayerCoordinates()[0], getPlayerCoordinates()[1] - 1, getPlayerCoordinates()[2]); drawDebug(Integer.toString(blockID), (getWindowSize().a() - (getFontRenderer().a(Integer.toString(blockID)) + 1)), 4, 0xffffff); try { drawDebug(mc.s.toString(), (getWindowSize().a() - (getFontRenderer().a(mc.s.toString()) + 1)), 5, 0xffffff); } catch (NullPointerException e) { drawDebug("null", (getWindowSize().a() - (getFontRenderer().a("null") + 1)), 5, 0xffffff); } drawDebug(Boolean.toString(canSlimesSpawnHere(x, z)), (getWindowSize().a() - (getFontRenderer().a(Boolean.toString(canSlimesSpawnHere(x, z))) + 1)), 6, 0xffffff); long nextUpdate = ((lastUpdateCheck + 3600000) - System.currentTimeMillis()) / 1000; int hours = (int)(nextUpdate / 3600); int seconds = (int)nextUpdate % 60; int minutes = (int)(nextUpdate % 3600) / 60; String update = pad(hours)+":"+pad(minutes)+":"+pad(seconds); String t = "Next update check: "+update; drawDebug(t, (getWindowSize().a() - (getFontRenderer().a(t) + 1)), 7, 0xffffff); drawDebug(getPlayerController().toString(), (getWindowSize().a() - (getFontRenderer().a(getPlayerController().toString()) + 1)), 8, 0xffffff); String a = getCalendarDate()+"/"+getCalendarDate(2); drawDebug(a, (getWindowSize().a() - (getFontRenderer().a(a) + 1)), 9, 0xffffff); drawDebug(Boolean.toString(isSeedSet()), (getWindowSize().a() - (getFontRenderer().a(Boolean.toString(isSeedSet())) + 1)), 10, 0xffffff); a = "CP: "+getChunkProvider().toString(); drawDebug(a, (getWindowSize().a() - (getFontRenderer().a(a) + 1)), 12, 0xffffff); a = Minecraft.a("minecraft").getAbsolutePath(); drawDebug(a, (getWindowSize().a() - (getFontRenderer().a(a) + 1)), 11, 0xffffff); a = "S: "+canBlockSeeTheSky(x, getPlayerCoordinates()[1], z); drawDebug(a, (getWindowSize().a() - (getFontRenderer().a(a) + 1)), 13, 0xffffff); a = "WS: "+getWindowSize().a()+"x"+getWindowSize().b(); drawDebug(a, (getWindowSize().a() - (getFontRenderer().a(a) + 1)), 14, 0xffffff); } WMLLCheckKeys(); if (!Enabled || !shouldShow() || (WMLLI == 11 && classicOutput)) return; // 0 = x, 1 = y, 2 = z, 3 = f int[] playerPos = getPlayerCoordinates(); int light = getLightLevel(playerPos[0], playerPos[1], playerPos[2]); if (isPlayerSleeping()) { if (getCalendarDate().equals("66")) // My birthday lightString = "Happy birthday, iPeer!"; else if (getCalendarDate().equals("243")) // Roxy's birthday (<3) lightString = "Happy birthday, Roxy!"; else if (getCalendarDate().equals("202")) // WMLL's "birthday" lightString = "Happy birthday, WMLL!"; else if (getCalendarDate().equals("84")) // Easter Sunday lightString = "Happy Easter!"; else if (getCalendarDate().equals("2512")) // Christmas Day lightString = "Why are you playing Minecraft on Christmas Day?"; else if (getCalendarDate().equals("11")) // New Year lightString = "Happy New Year!"; else if (getCalendarDate().equals("3110")) // Halloween lightString = "Happy Halloween! WoooOOOoooOOoooO!"; else if (getCalendarDate().equals("31")) // Millie <3 RIP, honey. lightString = "Millie <3"; else if (getCalendarDate().equals("32")) {// Roxy and I's anniversary String a = getCalendarDate(2); int now = Integer.parseInt(a.substring(a.length() - 4)); int years = now-2007; lightString = years+" years today!"; } else if (!sleepingStringSet) { lightString = sleepstrings[new Random().nextInt(sleepstrings.length)].replaceAll("PLAYERNAME", getPlayerName()); sleepingStringSet = true; } } else { lightString = generateLightString(); sleepingStringSet = false; } if (WMLLI < 6 || (!useImages || !classicOutput)) { if (!isPlayerSleeping() && useImages) drawLightImage(light); else drawString(lightString, 2, 0, 0xffffff); } // Compass if (useImages || classicOutput) { if (Arrays.asList(3, 4, 5, 8, 9, 10).contains(WMLLI)) { int out = 1; if (WMLLI == 9 || WMLLI == 4) { out = isMultiplayer() && !isSeedSet() ? 3 : 4; if (getDimension() == 1) out--; } else if (WMLLI == 8 || WMLLI == 3 || WMLLI == 4) out = 0; else if (WMLLI == 10 || WMLLI == 5) out = 1; if ((isSeedSet()) || isMultiplayer()) out++; + if ((isMultiplayer() && (getDimension() == -1 || getDimension() == 1))) + out++; // if (getDimension() == 1) // out--; ng player = thePlayer(); double x = player.t; double y = player.u; double z = player.v; double f = kx.c((double)((player.z * 4F) / 360F) + 0.5D) & 3; NumberFormat d = new DecimalFormat("#0.00"); String coords = "("+d.format(x)+", "+d.format(y)+", "+d.format(z)+", "+getPlayerDirection((int)f)+")"; drawString(coords, 2, out, 0xffffff); if (WMLLI != 5 && WMLLI != 10) { boolean showSeed = (!isMultiplayer() || isSeedSet()/* || getWorldName().equals("localServer")*/) && showSeedWithCoords; if (showSeed) drawString("Seed: "+getWorldSeed(), 2, out + 1, 0xffffff); //drawString("Facing: "+getPlayerDirection(playerPos[3]), 2, out, 0xffffff); drawString("Biome: "+getBiome()+" (T: "+getTemperature()+", H: "+getHumidity()+")", 2, showSeed ? out + 2 : out + 1, 0xffffff); } } // Indicators if (Arrays.asList(1, 4, 6, 9).contains(WMLLI)) { if (useImages) { wmllRenderer.renderIndicatorImages(light, getBlockID(playerPos[0], playerPos[1] - 1, playerPos[2]), getDimension(), canSlimesSpawnHere(playerPos[0], playerPos[2]), canBlockSeeTheSky(playerPos[0], playerPos[1] - 1, playerPos[2])); return; } boolean showSlimes = true; if (isMultiplayer()) showSlimes = isSeedSet(); String[] labels = {"Mobs", "Animals", "Trees", "Crops", "Mushrooms", "Slimes", "Ghasts", "Pigmen", "Blaze", "Endermen", "Grass"}; if (getDimension() == -1) { // Nether if (!isBlockInBlacklist(getBlockID(playerPos[0], playerPos[1] - 1, playerPos[2]))) { drawString("\247a"+labels[6], 2, 1, 0xffffff); // Ghasts drawString("\247a"+labels[7], 2, 2, 0xffffff); // Pigmen if (light < 12) drawString("\247a"+labels[8], 2, 3, 0xffffff); // Blaze else drawString("\247c"+labels[8], 2, 3, 0xffffff); // Blaze drawString("\247a"+labels[5], 2, 4, 0xffffff); // Slimes } else { drawString("\247c"+labels[6], 2, 1, 0xffffff); // Ghasts drawString("\247c"+labels[7], 2, 2, 0xffffff); // Pigmen drawString("\247c"+labels[8], 2, 3, 0xffffff); // Blaze drawString("\247c"+labels[5], 2, 4, 0xffffff); // Slimes } } else if (getDimension() == 1) { // End if (light < 7 && !isBlockInBlacklist(getBlockID(playerPos[0], playerPos[1] - 1, playerPos[2]))) drawString("\247a"+labels[9], 2, 1, 0xffffff); else drawString("\247c"+labels[9], 2, 1, 0xffffff); } else { // Normal world // Hostiles if ((light < 8 && !isBlockInBlacklist(getBlockID(playerPos[0], playerPos[1] - 1, playerPos[2]))) && (getBlockID(playerPos[0], playerPos[1] - 1, playerPos[2]) != 110 && !getBiome().startsWith("MushroomIsland"))) drawString("\247a"+labels[0], 2, 1, 0xffffff); else drawString("\247c"+labels[0], 2, 1 , 0xffffff); // Animals if (playerIsStandingOnBlock(2)) if (light < 9) drawString((!canBlockSeeTheSky(playerPos[0], playerPos[1], playerPos[2]) ? "\247c" : "\247e")+labels[1], 2, 2, 0xffffff); else drawString("\247a"+labels[1], 2, 2, 0xffffff); else drawString("\247c"+labels[1], 2, 2, 0xffffff); // Slimes if (showSlimes) { if (getBiome().startsWith("Swamp")) { boolean a = isBlockInBlacklist(getBlockID(playerPos[0], playerPos[1] - 1, playerPos[2])); if (light < 8 && !a) drawString("\247a"+labels[5], 2, 3, 0xffffff); else if (light > 7 && !a) drawString("\247e"+labels[5], 2, 3, 0xffffff); else drawString("\247c"+labels[5], 2, 3, 0xffffff); } else if (canSlimesSpawnHere(playerPos[0], playerPos[2]) && !getBiome().startsWith("Swamp")) if ((playerPos[1] - 1) <= 40) drawString("\247a"+labels[5], 2, 3, 0xffffff); else drawString("\247e"+labels[5], 2, 3, 0xffffff); else drawString("\247c"+labels[5], 2, 3, 0xffffff); } } // Crops if (playerIsStandingOnBlock(60) && (getLightLevel(playerPos[0], playerPos[1] + 1, playerPos[2]) > 8 || canBlockSeeTheSky(playerPos[0], playerPos[1], playerPos[2]))) drawString("\247a"+labels[3], getDimension() == 1 ? 55 : 40, 1, 0xffffff); else drawString("\247c"+labels[3], getDimension() == 1 ? 55 : 40, 1, 0xffffff); // Trees if ((playerIsStandingOnBlock(2) || playerIsStandingOnBlock(3)) && (light > 8 || canBlockSeeTheSky(playerPos[0], playerPos[1], playerPos[2]))) drawString("\247a"+labels[2], getDimension() == 1 ? 2 : 40, 2, 0xffffff); else drawString("\247c"+labels[2], getDimension() == 1 ? 2 : 40, 2, 0xffffff); // Mushrooms if ((playerIsStandingOnBlock(110) || light < 13) && !isBlockInBlacklist(getBlockID(playerPos[0], playerPos[1] - 1, playerPos[2]))) drawString("\247a"+labels[4], getDimension() == 0 ? 40 : 40, getDimension() == 1 ? 2 : 3, 0xffffff); else drawString("\247c"+labels[4], getDimension() == 0 ? 40 : 40, getDimension() == 1 ? 2 : 3, 0xffffff); // Grass if ((playerIsStandingOnBlock(3) && light > 8)) drawString("\247a"+labels[10], getDimension() == -1 ? 40 : 2, getDimension() == 1 ? 3 : getDimension() == -1 ? 4 : !showSlimes ? 3 : 4, 0xffffff); else drawString("\247c"+labels[10], getDimension() == -1 ? 40 : 2, getDimension() == 1 ? 3 : getDimension() == -1 ? 4 : !showSlimes ? 3 : 4, 0xffffff); } if (Arrays.asList(2, 5, 7, 10).contains(WMLLI)) drawString(getFPSString(),2, 1, 0xffffff); } } wmllRenderer.tick(); } private void drawLightImage(int light) { wmllRenderer.renderLightImage(light); drawString(Integer.toString(light), 6, 0, 0xffffff); } public String generateLightString() { return generateLightString(options.getProperty("lightString", "Light level: %LightLevel%")); } public String generateLightString(String s) { // [Roxy] Now Case insensitive int x = getPlayerCoordinates()[0]; int y = getPlayerCoordinates()[1]; int z = getPlayerCoordinates()[2]; double x1 = getPlayerCoordinatesAsDouble()[0]; double y1 = getPlayerCoordinatesAsDouble()[1]; double z1 = getPlayerCoordinatesAsDouble()[2]; double yfeet = getPlayerCoordinatesAsDouble()[3]; int a = getLightLevel(x, y, z); Pattern SkyLight = Pattern.compile("%skylight%", Pattern.CASE_INSENSITIVE); Pattern BlockLight = Pattern.compile("%blocklight%", Pattern.CASE_INSENSITIVE); Pattern RawLight = Pattern.compile("%rawlight%", Pattern.CASE_INSENSITIVE); Pattern Light = Pattern.compile("%LightLevel%", Pattern.CASE_INSENSITIVE); Pattern sunLight = Pattern.compile("%sunlight%", Pattern.CASE_INSENSITIVE); Pattern Biome = Pattern.compile("%Biome%", Pattern.CASE_INSENSITIVE); Pattern FPS = Pattern.compile("%fps%", Pattern.CASE_INSENSITIVE); Pattern FPS_noCU = Pattern.compile("%fps2%", Pattern.CASE_INSENSITIVE); Pattern fullCompass = Pattern.compile("%fullcompass%", Pattern.CASE_INSENSITIVE); Pattern chunkUpdates = Pattern.compile("%(cu|chunkupdates)%", Pattern.CASE_INSENSITIVE); Pattern heading = Pattern.compile("%heading%", Pattern.CASE_INSENSITIVE); Pattern fx = Pattern.compile("%fx%", Pattern.CASE_INSENSITIVE); Pattern fy = Pattern.compile("%fy%", Pattern.CASE_INSENSITIVE); Pattern feety = Pattern.compile("%feety%", Pattern.CASE_INSENSITIVE); Pattern fz = Pattern.compile("%fz%", Pattern.CASE_INSENSITIVE); Pattern cx = Pattern.compile("%cx%", Pattern.CASE_INSENSITIVE); Pattern cy = Pattern.compile("%cy%", Pattern.CASE_INSENSITIVE); Pattern cz = Pattern.compile("%cz%", Pattern.CASE_INSENSITIVE); Pattern clock = Pattern.compile("%clock%", Pattern.CASE_INSENSITIVE); Pattern clock2 = Pattern.compile("%12hclock%", Pattern.CASE_INSENSITIVE); Pattern chunkx = Pattern.compile("%chunkx%", Pattern.CASE_INSENSITIVE); Pattern chunkz = Pattern.compile("%chunkz%", Pattern.CASE_INSENSITIVE); Pattern seed = Pattern.compile("%seed%", Pattern.CASE_INSENSITIVE); Pattern localTime = Pattern.compile("%localtime%", Pattern.CASE_INSENSITIVE); Pattern localTime12h = Pattern.compile("%12hlocaltime%", Pattern.CASE_INSENSITIVE); Pattern entities = Pattern.compile("%entities%", Pattern.CASE_INSENSITIVE); Pattern entities2 = Pattern.compile("%fullentities%", Pattern.CASE_INSENSITIVE); String lightLevel = (a < 8 ? "\247c" : "")+Integer.toString(a)+"\247r"; a = getSavedBlockLight(x, y, z); String blockLight = (a < 8 ? "\247c" : "")+Integer.toString(a)+"\247r"; a = getRawLightLevel(x, y, z); String rawLight = (a < 8 ? "\247c" : "")+Integer.toString(a)+"\247r"; a = getSunLight(x, y, z); String skyLight = (a < 8 ? "\247c" : "")+Integer.toString(a)+"\247r"; Matcher m = SkyLight.matcher(s); s = m.replaceAll(skyLight); m = BlockLight.matcher(s); s = m.replaceAll(blockLight); m = RawLight.matcher(s); s = m.replaceAll(rawLight); m = Light.matcher(s); s = m.replaceAll(lightLevel); m = Biome.matcher(s); s = m.replaceAll(getBiome()); m = FPS.matcher(s); s = m.replaceAll(getFPSString()); m = FPS_noCU.matcher(s); s = m.replaceAll(getFPSString().split(",")[0]); m = chunkUpdates.matcher(s); s = m.replaceAll(getFPSString().split(",")[1].substring(1)); m = fx.matcher(s); s = m.replaceAll(Integer.toString((int)Math.floor(x1))); m = fy.matcher(s); s = m.replaceAll(Integer.toString((int)Math.floor(y1))); m = fz.matcher(s); s = m.replaceAll(Integer.toString((int)Math.floor(z1))); m = cx.matcher(s); s = m.replaceAll(Integer.toString((int)Math.ceil(x1))); m = cy.matcher(s); s = m.replaceAll(Integer.toString((int)Math.ceil(y1))); m = cz.matcher(s); s = m.replaceAll(Integer.toString((int)Math.ceil(z1))); m = clock.matcher(s); s = m.replaceAll(getFormattedWorldTime(2)); m = clock2.matcher(s); s = m.replaceAll(getFormattedWorldTime(3)); m = chunkx.matcher(s); s = m.replaceAll(Integer.toString(getChunk(x, z).g)); m = chunkz.matcher(s); s = m.replaceAll(Integer.toString(getChunk(x, z).h)); m = seed.matcher(s); s = m.replaceAll(""+(getWorldSeed() != 0L ? getWorldSeed() : "")); int f1 = getPlayerCoordinates()[3]; NumberFormat n = new DecimalFormat("#0.00"); String coords = "("+n.format(x1)+", "+n.format(y1)+", "+n.format(z1)+", "+getPlayerDirection((int)f1)+")"; m = fullCompass.matcher(s); s = m.replaceAll(coords); m = heading.matcher(s); s = m.replaceAll(getPlayerDirection((int)f1)); Pattern coordsX = Pattern.compile("%x%", Pattern.CASE_INSENSITIVE); m = coordsX.matcher(s); s = m.replaceAll(n.format(x1)); Pattern coordsY = Pattern.compile("%y%", Pattern.CASE_INSENSITIVE); m = coordsY.matcher(s); s = m.replaceAll(n.format(y1)); m = feety.matcher(s); s = m.replaceAll(n.format(yfeet)); Pattern coordsZ = Pattern.compile("%z%", Pattern.CASE_INSENSITIVE); m = coordsZ.matcher(s); s = m.replaceAll(n.format(z1)); Pattern indicators = Pattern.compile("%ind:([\\p{Alnum}\\p{Punct}&&[^\\\\ ]]+)%", Pattern.CASE_INSENSITIVE); m = indicators.matcher(s); while (m.find()) { String ind = m.group().replaceAll("%ind:|%", "").toLowerCase(); s = s.replaceAll("%ind:"+ind+"%", getIdenString(ind)+"\247r"); } m = localTime.matcher(s); s = m.replaceAll(getLocalTime(0)); m = localTime12h.matcher(s); s = m.replaceAll(getLocalTime(1)); m = sunLight.matcher(s); s = m.replaceAll(Integer.toString(getSunLight(x, y, z))); m = entities.matcher(s); s = m.replaceAll(mc.n().split(" ")[1].split("/")[0]); m = entities2.matcher(s); s = m.replaceAll(mc.n().split(" ")[1].replaceAll("\\.", "")); Pattern debug = Pattern.compile("%debug:([\\p{Alnum}\\p{Punct}&&[^\\\\ ]]+)%", Pattern.CASE_INSENSITIVE); m = debug.matcher(s); while (m.find()) { String dval = m.group().replaceAll("%debug:|%", "").toLowerCase(); s = s.replaceAll("%debug:"+dval+"%", debugValue(dval)+"\247r"); } return s; } public wg getHeldItem() { return getPlayerInventory().h(); } public int getHeldItemID() { try { return getHeldItem().c; } catch (NullPointerException e) { return -1; } } public si getPlayerInventory() { return entityPlayer().bK; } public boolean itemHasEnchant(int enchantID) { return itemHasEnchant(enchantID, getHeldItem()); } public wg[] getPlayerArmour() { return entityPlayer().ad(); } public boolean itemHasEnchant(int enchantID, wg wg) { return yv.a(51, wg) > 0; } public String getInternalItemNameForSlot(int slot) { return getPlayerInventory().a[slot].a(); } public boolean isSlotEmpty(int slot) { return getPlayerInventory().a[slot] == null; } private String debugValue(String v) { if (v.equals("arrows")) { if (getHeldItemID() != 261) return "Not holding a bow."; wg[] items = getPlayerInventory().a; int arrows = 0; String arr = "Arrows: "; if (itemHasEnchant(51, getHeldItem()) || isCreative()) return arr+"Unlimited"; for (int x1 = 0; x1 < items.length; x1++) { if (!isSlotEmpty(x1) && getInternalItemNameForSlot(x1).equals("item.arrow")) arrows += items[x1].a; } return arr+arrows; } else if (v.equals("armour")) { wg[] armour = getPlayerArmour(); String o = ""; for (int i = armour.length-1; i > -1; i--) { if (armour[i] != null) o = o+(o.length() > 0 ? ", " : "")+armour[i].s(); } if (o.equals("")) return "no armour."; return o; } else if (v.equals("helditem")) { try { wg itemStack = getHeldItem(); if (itemStack == null) return "Nothing"; // Item internal name: a() // Item name: r() // Stack quantity: a // Item ID: c // Item durability: k() // Item used durability: j() // Item data: i() // Has been used: h() // Is Enchanted or Named: o() String itemName = itemStack.s(); int itemMaxDur = itemStack.l(); int itemCurrDur = (itemMaxDur - itemStack.k()); int itemData = itemStack.l(); int itemID = itemStack.c; boolean hasData = itemStack.g(); if (debugClassPresent && debugActive) return "N: "+itemName+", MaxDur: "+itemMaxDur+", CurrDur: "+itemCurrDur+", Data: "+itemData+", ID: "+itemID+", HasData: "+hasData; if (itemMaxDur > 0) { return itemName+": "+new DecimalFormat("##").format(((double)itemCurrDur/itemMaxDur)*100.00)+"% durability, "+itemCurrDur+" uses."; } return itemName +" ("+itemID+(hasData ? ":"+itemData : "")+")"; } catch (Exception e) { return e.toString(); } } return "Invalid"; } private String getLocalTime(int mode) { calendar.setTime(new Date(System.currentTimeMillis())); String time = calendar.getTime().toString().split(" ")[3]; if (mode == 1) { int a = Integer.valueOf(time.split(":")[0]); if (a > 12) a -= 12; return a+":"+time.split(":")[1]+":"+time.split(":")[2]+" "+(a + 12 > 11 ? "PM" : "AM"); } return calendar.getTime().toString().split(" ")[3]; } private bdm getWorld() { try { return mc.e; } catch (NullPointerException n) { return null; } } public bja sspServer() { return mc.D(); } public String getWorldName() { if (!isMultiplayer()) return sspServer().K(); try { Object obj = thePlayer(); Field f = obj.getClass().getDeclaredField("a"); // sendQueue f.setAccessible(true); obj = f.get(obj); Field f1 = obj.getClass().getDeclaredField(getField("netManager")); // netManager f1.setAccessible(true); obj = f1.get(obj); Field f2; - if (!isMultiplayer()) - f2 = obj.getClass().getDeclaredField(getField("SPremoteSocketAddress")); // remoteSocketAddress - - else - f2 = obj.getClass().getDeclaredField(getField("remoteSocketAddress")); + f2 = obj.getClass().getDeclaredField(getField("remoteSocketAddress")); f2.setAccessible(true); SocketAddress a = (SocketAddress)f2.get(obj); String s = a.toString(); String server = s.split("/")[0].split(":")[0]; if (server == null || server.equals("")) server = s.split("/")[1].split(":")[0]; String port = s.split(":")[1]; return server+":"+port; } catch (Exception e) { return "Unknown - "+e.getMessage(); } } // public String worldName() { // return worldInstance().m()+", "+worldInstance().n(); // } public awp getFontRenderer() { return this.fontRenderer; } public axm getWindowSize() { return new axm(mc.z, mc.c, mc.d); } private boolean mcDebugOpen() { return getGameSettings().ab; } private avs getGameSettings() { return mc.z; } public boolean isMultiplayer() { return !mc.B(); } public int getSavedBlockLight(int x, int y, int z) { if (y < 0 || y > 255) return 0; return getChunk(x, z).a(aag.b, x & 0xf, y, z & 0xf); } public int getRawLightLevel(int x, int y, int z) { if (y < 0 || y > 255) return 0; return getChunk(x, z).c(x & 0xf, y, z & 0xf, 0); } public int getSunLight(int x, int y, int z) { if (y < 0 || y > 255) return 0; return getChunk(x, z).a(aag.a, x & 0xf, y, z & 0xf); } public int getBlockLight(int i, int j, int k) { if (j < 0 || j > 255) return 0; return getChunk(i, k).a(aag.b, i & 0xf, j, k & 0xf); } public int getLightLevel(int j, int k, int l) { if (k < 0 || k > 255) return 0; return getChunk(j, l).c(j & 0xf, k, l & 0xf, getSkyLight(1.0f)); } public int getSkyLight(float f) { return getWorld().a(f); } public String getBiome(int x, int z) { return getChunk(x, z).a(x & 0xf, z & 0xf, getBiomeGenBase()).y; } public String getBiome() { int x = getPlayerCoordinates()[0]; int z = getPlayerCoordinates()[2]; return getBiome(x, z); } private String getTemperature() { return NumberFormat.getPercentInstance().format(getBiomeGenBase().a(getPlayerCoordinates()[0], getPlayerCoordinates()[2]).F); } private String getHumidity() { return NumberFormat.getPercentInstance().format(getBiomeGenBase().a(getPlayerCoordinates()[0], getPlayerCoordinates()[2]).G); } private aau getBiomeGenBase() { return getWorld().t(); } private boolean playerIsStandingOnBlock(int id) { int[] coords = getPlayerCoordinates(); return getBlockID(coords[0], coords[1] - 1, coords[2]) == id; } private int getBlockID(int x, int y, int z) { return getWorld().a(x, y, z); } private boolean isBlockInBlacklist(int id) { return blockBlackList.contains(id); } private boolean canBlockSeeTheSky(int x, int y, int z) { return getWorld().l(x, y, z); } public void sendChatMessage(String t) { entityPlayer().a(t); } public bdp entityPlayer() { return mc.g; } public ng thePlayer() { return mc.h; } public beo playerEntity() { return mc.j; } public String getPlayerName() { return playerEntity().b(); } public bdl getPlayerController() { return mc.b; } public boolean isCreative() { return !getPlayerController().b(); } public ajp worldInfo() { return getWorld().x; } protected Minecraft getMCInstance() { return mc; } private abq getChunk(int x, int z) { return getWorld().d(x, z); } private int getDimension() { return getWorldProvider().h; } private boolean canSlimesSpawnHere(int x, int z) { if (isSeedSet()) { abq chunk = getChunk(x, z); int g = chunk.g; int h = chunk.h; return new Random(getWorldSeed() + (long)(g * g * 0x4c1906) + (long)(g * 0x5ac0db) + (long)(h * h) * 0x4307a7L + (long)(h * 0x5f24f) ^ 0x3ad8025fL).nextInt(10) == 0; } return (getChunk(x, z).a(0x3ad8025fL).nextInt(10) == 0 && getWorldSeed() != 0L)/* || (getBiome(x, z).startsWith("Swamp") && getLightLevel(x, getPlayerCoordinates()[1], x) < 8)*/; } private ach getWorldProvider() { return getWorld().t; } private abn getChunkProvider() { return getWorldProvider().c(); } public long getWorldTime() { return getWorld().H(); } private String getFormattedWorldTime(int i) { long a = getWorldTime(); int h = (int)(((a + 6000L) % 24000L) / 1000L); int m = (int)(((a % 1000L) * 60L) / 1000L); String suffix = "AM"; String out = "00:00"; if (i == 2) { out = pad(h)+":"+pad(m); } else { if (h >= 12) { suffix = "PM"; h -= 12; } if (h == 0) { h = 12; } out = pad(h)+":"+pad(m)+" "+suffix; } return out; } private String pad(int i) { return (i < 10 ? "0"+i : i).toString(); } private boolean isPlayerSleeping() { return thePlayer().bz(); } public int[] getPlayerCoordinates() { int[] a = {kx.c(thePlayer().u), kx.c(thePlayer().v - 1), kx.c(thePlayer().w), kx.c((double)((thePlayer().A * 4F) / 360F) + 0.5D) & 3, (int)thePlayer().u, (int)thePlayer().v, (int)thePlayer().w}; return a; } public double[] getPlayerCoordinatesAsDouble() { double[] a = {thePlayer().u, thePlayer().v, thePlayer().w, thePlayer().E.b, kx.c((double)((thePlayer().A * 4F) / 360F) + 0.5D) & 3}; return a; } public long getWorldSeed() { if (worldSeedSet) return this.worldSeed; else { try { return Long.parseLong(options.getProperty("Seed:"+getWorldName().toLowerCase(), "0")); } catch (NumberFormatException n) { return 0L; } catch (NullPointerException n1) { return 0L; } } //} //return getChunk(0, 0).e.x.c().b(); } public String getFPSString() { return mc.L; } public static boolean WMLLDebugActive() { return debugActive; } public void drawDebug(String t, int x, int y, int c) { if (WMLLI > 5 && WMLLI < 11) y++; drawString(t, x, y, c); } public void drawStringUsingPixels(String t, int x, int y, int c) { if (c == 0xffffff) c = TextColour; getFontRenderer().a(t, x, y, c); } public void drawString(String t, int i, int j, int k) { //int textpos = (WMLLI > 5 && classicOutput ? -8 : 2); int textpos = 2; //t = (k == 0xffffff ? "\247"+Integer.toHexString(TextColour) : "")+t; Pattern re = Pattern.compile("\247[0-9a-f,l-o,r]"); int w = getWindowSize().a(); int h = getWindowSize().b(); t = t.replaceAll("\\\\t", (classicOutput ? " " : " ")); String[] lines = {}; if (classicOutput) { lines = new String[1]; lines[0] = t.replaceAll("\\\\n", " "); } else lines = t.split("\\\\n"); int l = 0; for (String a : lines) { String a1 = re.matcher(a).replaceAll(""); if (k == 0xffffff) k = TextColour; if (outputLocation == 1) // Top right getFontRenderer().a(a, w - (getFontRenderer().a(a1) + (i - 1)), textpos+(j*10+(10*l++)), k); else if (outputLocation == 2) // Bottom left getFontRenderer().a(a, i, h - (textpos+(j*10+(10*l++)) + 8), k); else if (outputLocation == 3) // Bottom Right getFontRenderer().a(a, w - (getFontRenderer().a(a1) + (i - 1)), h - (textpos+(j*10+(10*l++)) + 8), k); else // Top Left getFontRenderer().a(a, i, textpos+((j*10)+(10*l++)), k); } } public void saveOptions() { debug("[WMLL] Attempting to save options..."); try { if (options == null) options = new Properties(); options.setProperty("WMLLI", Integer.toString(WMLLI)); if (!debugClassPresent) options.setProperty("WMLLD", Boolean.toString(debugActive)); options.setProperty("FirstRun", Boolean.toString(firstRun)); options.setProperty("version", Integer.toString(propertiesVersion)); options.setProperty("F4", Integer.toString(F4Key)); options.setProperty("TextColour", Integer.toString(TextColour)); options.setProperty("clockSetting", Integer.toString(clockSetting)); options.setProperty("useImages", Boolean.toString(useImages)); options.setProperty("OutputLocation", Integer.toString(outputLocation)); options.setProperty("OverrideIngameF3", Boolean.toString(wmllOverrideF3)); options.setProperty("showSeedWithCoords", Boolean.toString(showSeedWithCoords)); options.setProperty("F3Type", Integer.toString(F3Type)); options.setProperty("classicOutput", Boolean.toString(classicOutput)); options.setProperty("autoUpdateCheck", Boolean.toString(autoUpdateCheck)); options.setProperty("SaturationBar", Boolean.toString(satBar)); options.setProperty("Compat-Rei", Boolean.toString(ReiEnabled)); options.setProperty("Compat-Zans", Boolean.toString(ZansEnabled)); options.setProperty("Compat-Alien", Boolean.toString(AlienEnabled)); options.setProperty("Compat-Forge", Boolean.toString(forgeEnabled)); options.setProperty("showUnderGUIs", Boolean.toString(showUnderGUIs)); options.setProperty("showWorldName", Boolean.toString(showWorldName)); options.store(new FileOutputStream(settingsFile), "WMLL Config File - Do not edit unless you know what you're doing!"); // if (!outputOptions.isEmpty()) // outputOptions.store(new FileOutputStream(outputOptionsFile), "WMLL's Output Options File - only edit if you know waht you're doing!"); debug("[WMLL] Options saved."); //debug(options.toString()+"\n"+outputOptions.toString()); } catch (Exception e) { debug("[WMLL] Unable to save options: "+e.getMessage()); e.printStackTrace(); } } public void loadOptions() { try { boolean updatedFormat = false; if (options == null) options = new Properties(); if (outputOptions == null) outputOptions = new Properties(); if (settingsFile.exists()) options.load(new FileInputStream(settingsFile)); else { File a = new File(Minecraft.a("minecraft"), "WMLL.properties"); if (a.exists()) { options.load(new FileInputStream(a)); System.err.println(">> "+a.getAbsolutePath()); a.deleteOnExit(); updatedFormat = true; } } if (outputOptionsFile.exists()) outputOptions.load(new FileInputStream(outputOptionsFile)); firstRun = Integer.parseInt(options.getProperty("version", "0")) < propertiesVersion ? true : false; // if (!debugClassPresent) // debugActive = Boolean.parseBoolean(options.getProperty("WMLLD", "false")); WMLLI = Integer.parseInt(options.getProperty("WMLLI", "0")); useImages = Boolean.parseBoolean(options.getProperty("useImages", "false")); TextColour = Integer.parseInt(options.getProperty("TextColour", "-1")); F4Key = Integer.parseInt(options.getProperty("F4", "62")); clockSetting = Integer.parseInt(options.getProperty("clockSetting", "2")); outputLocation = Integer.parseInt(options.getProperty("OutputLocation", "0")); wmllOverrideF3 = Boolean.parseBoolean(options.getProperty("OverrideIngameF3", "false")); // Now defaults to false due to Minecraft's native Shift + F3 F3Type = Integer.parseInt(options.getProperty("F3Type", "0")); showSeedWithCoords = Boolean.parseBoolean(options.getProperty("showSeedWithCoords", "true")); classicOutput = Boolean.parseBoolean(options.getProperty("classicOutput", "false")); autoUpdateCheck = Boolean.parseBoolean(options.getProperty("autoUpdateCheck", "true")); satBar = Boolean.parseBoolean(options.getProperty("SaturationBar", "false")); ReiEnabled = Boolean.valueOf(options.getProperty("Compat-Rei", "true")); AlienEnabled = Boolean.valueOf(options.getProperty("Compat-Alien", "true")); ZansEnabled = Boolean.valueOf(options.getProperty("Compat-Zans", "true")); forgeEnabled = Boolean.valueOf(options.getProperty("Compat-Forge", "true")); showUnderGUIs = Boolean.valueOf(options.getProperty("showUnderGUIs", "true")); showWorldName = Boolean.valueOf(options.getProperty("showWorldName", "true")); debug("[WMLL] Loaded options."); //debug(options.toString()+"\n"+outputOptions.toString()); if (firstRun || updatedFormat) saveOptions(); } catch (Exception e) { debug("[WMLL] Unable to load options: "+e.getMessage()); } } public String getPlayerDirection(int f) { switch (f) { case 1: return "West"; case 2: return "North"; case 3: return "East"; default: return "South"; } } public static void toggleDebug() { debugActive = !debugActive; } public void debug(String s) { System.out.println(s); } private void WMLLCheckKeys() { if (Keyboard.isKeyDown(F4Key) && System.currentTimeMillis() - lastF4Press > 250) { lastF4Press = System.currentTimeMillis(); if (Keyboard.isKeyDown(29) && mc.s == null) mc.a(new WMLLOptionsMenu(this)); else if (mc.s == null) { //&& !(mc.s instanceof acr/*GuiChat*/) && !(mc.s instanceof ars/*Sign Editing*/) && !(mc.s instanceof hw/*Book Editing*/)) { if (useImages || classicOutput) { if (Keyboard.isKeyDown(42)) { WMLLI--; while (!isOutputEnabled(WMLLI)) WMLLI--; } else { WMLLI++; while (!isOutputEnabled(WMLLI)) WMLLI++; } saveOptions(); } } } } private void toggleF3Override() { wmllF3Output = !wmllF3Output; getGameSettings().ab = false; } public int getFPSThreshold() { return Integer.parseInt(options.getProperty("FPSThreshold", "60")); } public boolean isSeedSet() { try { if (!isMultiplayer()/* || getWorldName().equals("localServer")*/) return true; return options.containsKey("Seed:"+getWorldName().toLowerCase()); } catch (NullPointerException n) { n.printStackTrace(); return false; } } public void displayUpdateString(String newver, String mcVersion) { sendChatMessage("WMLL \247c"+newver+"\247f is now available for Minecraft \247c"+mcVersion); } public String getCalendarDate() { return getCalendarDate(1); } public String getCalendarDate(int type) { if (calendar.getTime() != new Date()) calendar.setTime(new Date()); String c = ""; int a = calendar.get(5); int b = calendar.get(2) + 1; if (type == 2) { int d = calendar.get(1); c = Integer.toString(a)+Integer.toString(b)+Integer.toString(d); } else c = Integer.toString(a)+Integer.toString(b); return c; } public boolean isOutputEnabled(int i) { try { if (i > 11) WMLLI = i = 0; if (i < 0) WMLLI = i = 11; return Boolean.parseBoolean(options.getProperty("Output"+i, "true")); } catch (Exception e) { e.printStackTrace(); return true; } } private String getField(String n) { return fieldNames.get(n); } public boolean areAllOutputsDisabled() { int x = 0; for (; Boolean.parseBoolean(options.getProperty("Output"+x, "true")) == false && x <= 11; x++) { } return x > 11; } public static boolean hasUpdateBeenAnnounced(String i) { return options.containsKey("Update"+i.replaceAll(" ", "_")); } public void setUpdateAsAnnounced(String i) { options.put("Update"+i.replaceAll(" ", "_"), "true"); saveOptions(); } public String getIdenString(String i) { int x = getPlayerCoordinates()[0]; int y = getPlayerCoordinates()[1]; int z = getPlayerCoordinates()[2]; int l = getLightLevel(x, y, z); int b = getBlockID(x, y - 1, z); int d = getDimension(); Boolean sk = canBlockSeeTheSky(x, y, z); Boolean c = canSlimesSpawnHere(x, z); Boolean v = blockBlackList.contains(b); String s = "\247cInvalid indicator! Valid types are: \247omobs, animals, slimes, crops, trees \247r\247cor\247o mushrooms\247r\247c."; String bi = getBiome(); if (i.equals("mobs")) { if (d == 0) { if (l > 7 && !v || bi.startsWith("MushroomIsland")) s = "\247cMobs"; else if (l < 8 && !v) s = "\247aMobs"; else s = "\247cMobs"; } else if (d == -1) if (v) s = "\247cGhasts"; else s = "\247aGhasts"; else s = (!v && l < 8 ? "\247aEndermen" : "\247cEndermen"); } else if (i.equals("animals")) { if (d == -1) if (!v) s = "\247aPigmen"; else s = "\247cPigmen"; else if (d == 0) if (b == 2) if (l < 9 && !sk) s = "\247cAnimals"; else if (l < 9 && sk) s = "\247eAnimals"; else s = "\247aAnimals"; else s = "\247cAnimals"; else s = "\247cAnimals"; } else if (i.equals("slimes")) { if (d == 0) if ((c && y + 1 > 40) || (l > 7 && bi.startsWith("Swamp"))) s = "\247eSlimes"; else if (c && y + 1 < 41 && v) s = "\247cSlimes"; else if ((c && y + 1 < 41) || (l < 8 && bi.startsWith("Swamp"))) s = "\247aSlimes"; else s = "\247cSlimes"; else if (d == -1) if (!v) s = "\247aSlimes"; else s = "\247cSlimes"; else s = "\247cSlimes"; } else if (i.equals("crops")) { if (b == 60) s = (l > 9 ? "\247aCrops" : "\247cCrops"); else s = "\247cCrops"; } else if (i.equals("trees")) { if (Arrays.asList(2, 3).contains(b)) s = (l > 9 ? "\247aTrees" : "\247cTrees"); else s = "\247cTrees"; } else if (i.equals("grass")) { // Boolean a = getBlockID(x - 1, y - 1, z) == 2; // Boolean e = getBlockID(x + 1, y - 1, z) == 2; // Boolean f = getBlockID(x, y - 1, z + 1) == 2; // Boolean g = getBlockID(x, y - 1, z - 1) == 2; // Boolean h = getBlockID(x - 1, y - 1, z - 1) == 2; // Boolean j = getBlockID(x + 1, y - 1, z + 1) == 2; if (l > 9 && b == 3/* && (a || e || f || g || h || j)*/) s = "\247aGrass"; else s = "\247cGrass"; } else if (i.equals("mushrooms")) { if ((l > 12 || v) && b != 110) s = "\247cMushrooms"; else s = "\247aMushrooms"; } // else if (i.equals("wither") && debugClassPresent) { // Disabled for end-users, not working. // //TODO // if (d > -1) // s = "\247cWither Skeletons"; // else { // try { // aaz cp = (aaz)getChunkProvider(); // yc structureGen = (yc)cp.c; // boolean a = structureGen.a(x >> 4, z >> 4); // //boolean a = canStructureSpawnHere(netherStructure.b, x, z); // // s = (a ? "\247a" : "\247c")+"Wither Skeletons"; // s = "\247c"+a+", "+x+", "+(y - 1)+", "+z+" | "+getWorldSeed(); // } // catch (NullPointerException e) { // s = "\247cWither Skeletons (NPE)"; // //e.printStackTrace(); // } // catch (Exception e) { // s = "\247cWither Skeletons (GE)"; // } // } // } return s+(debugActive ? ", "+l+", "+v+", "+sk : ""); } public void toggleSatBar() { this.satBar = !this.satBar; } public void shitBricks(int id, Throwable e) { switch (id) { case 1: System.err.println("[WMLL] Error creating compatibility object."); printStackTrace(e); compatDisabled = true; break; case 2: System.err.println("[WMLL] Error creating Rei's Minimap Compatibility."); printStackTrace(e); Rei = ReiUseMl = false; reiError = e.toString(); break; case 3: System.err.println("[WMLL] Error creating Alien Radar Compatibility."); AlienRadar = false; printStackTrace(e); alienError = e.toString(); break; case 4: System.err.println("[WMLL] Error creating Zan's Minimap Compatibility."); ZansMinimap = false; printStackTrace(e); zanError = e.toString(); break; } } public void printStackTrace(Throwable e) { debug("[WMLL] Exception: "+e.toString()); for (int x = 0; x < e.getStackTrace().length; x++) debug("\t* "+e.getStackTrace()[x]); } public boolean isEnabled() { //boolean a = isAutoDisabledServer(); return /*!a && */Boolean.parseBoolean(options.getProperty("World-"+getWorldName(), "true")) && !Boolean.parseBoolean(options.getProperty("AllOutputsOff", "false")); } @SuppressWarnings("unused") private boolean isAutoDisabledServer() { for (String b : autoDisable) if (getWorldName().matches(b)) return true; return false; } public boolean atLeast2True(boolean[] b) { int x = 0; for (int i = 0; i < b.length; i++) if (b[i]) x++; return x > 1; } public void deleteSettingsFile() { settingsFile.delete(); } public boolean shouldShow() { if (showUnderGUIs) return true; else return mc.s == null; } public boolean canStructureSpawnHere(int x, int z) { return canStructureSpawnHere(new Random(), x, z); } public boolean canStructureSpawnHere(Random a, int x, int z) { //Random a = r; int cx = x >> 4; int cz = z >> 4; a.setSeed((long)(cx ^ cz << 4) ^ getWorldSeed()); a.nextInt(); return a.nextInt(3) != 0 ? false : (x != (cx << 4) + 4 + a.nextInt(8) ? false : z == (cz << 4) + 4 + a.nextInt(8)); } } diff --git a/src/WMLLOptionsOutput.java b/src/WMLLOptionsOutput.java index c6d816f..bb5dab6 100644 --- a/src/WMLLOptionsOutput.java +++ b/src/WMLLOptionsOutput.java @@ -1,210 +1,210 @@ import java.awt.Color; import java.awt.Desktop; import java.net.URI; import java.util.ArrayList; import org.lwjgl.input.Keyboard; public class WMLLOptionsOutput extends axl { private static final String[] outputs = {"Just Light", "Light & Indicators", "Light, FPS & Chunk Updates", "Light & Compass", "Light, Indicators & Compass", "Light, FPS & Coordinates", "Just Indicators", "Just FPS & Chunk Updates", "Just Compass", "Just Indicators and Compass", "Just FPS & Coordinates", "Nothing"}; private static final String[] locations = {"Top Left", "Top Right", "Bottom Left", "Bottom Right"}; private WMLL wmll; private axl parent; public awm lightLevelBox; private awm R, G, B, seedBox; private awa showButton; private ArrayList<awm> editboxes = new ArrayList<awm>(); private Desktop desktop; private int[] colours; public WMLLOptionsOutput(WMLL wmll, axl aum) { this.wmll = wmll; this.parent = aum; } public void b() { Keyboard.enableRepeatEvents(false); } @SuppressWarnings("unchecked") public void A_() { Keyboard.enableRepeatEvents(true); i.clear(); lightLevelBox = new awm(l, g / 2 - ((wmll.getWindowSize().a() - 20) / 2), 35, wmll.getWindowSize().a() - 20, 15); lightLevelBox.f(500); lightLevelBox.a(WMLL.options.getProperty("lightString", "Light level: %LightLevel%")); lightLevelBox.b(true); i.add(showButton = new awa(1, g / 2 - 75, h / 4 + 5, 275, 20, "Show: "+outputs[WMLL.WMLLI])); R = new awm(l, g / 2 - 60, h / 4 + 70, 30, 10); R.f(3); R.a(WMLL.options.getProperty("RGB-R", "255")); G = new awm(l, g / 2 - 15, h / 4 + 70, 30, 10); G.f(3); G.a(WMLL.options.getProperty("RGB-G", "255")); B = new awm(l, g / 2 + 30, h / 4 + 70, 30, 10); B.f(3); B.a(WMLL.options.getProperty("RGB-B", "255")); if (R.b().equals("")) R.a("0"); if (G.b().equals("")) G.a("0"); if (B.b().equals("")) B.a("0"); colours = new int[3]; colours[0] = Integer.valueOf((R.b().equals("") ? "0" : R.b())); colours[1] = Integer.valueOf((G.b().equals("") ? "0" : G.b())); colours[2] = Integer.valueOf((B.b().equals("") ? "0" : B.b())); seedBox = new awm(l, g / 2 - ((wmll.getWindowSize().a() - 20) / 2), h / 4 + 105, wmll.getWindowSize().a() - 20, 15); seedBox.f(500); seedBox.a(Long.toString(wmll.getWorldSeed())); editboxes.add(seedBox); editboxes.add(lightLevelBox); editboxes.add(R); editboxes.add(G); editboxes.add(B); showButton.g = wmll.classicOutput || WMLL.useImages; i.add(new awa(2, g / 2 - 200, h / 4 + 5, 120, 20, "Location: "+locations[WMLL.outputLocation])); i.add(new awa(3, g / 2 - 200, h / 4 + 30, 120, 20, "Output type: "+(wmll.classicOutput ? "Classic" : "Custom"))); i.add(new awa(4, g / 2 - 75, h / 4 + 30, 120, 20, "Images: "+(WMLL.useImages ? "ON" : "OFF"))); i.add(new awa(0, g / 2 - 190, h - 30, 380, 20, "Done")); awa paramButton; i.add(paramButton = new awa(-1, wmll.getWindowSize().a() - 108, 19, 100, 14, "Parameter help")); paramButton.h = Desktop.isDesktopSupported() && (this.desktop = Desktop.getDesktop()).isSupported(Desktop.Action.BROWSE); if (wmll.debugClassPresent) i.add(new awa(9001, g - 20, 0, 20, 20, "R")); } protected void a(awa b) { switch (b.f) { case 9001: f.a(new WMLLOptionsOutput(this.wmll, this.parent)); return; case 0: WMLL.options.put("RGB-R", R.b()); WMLL.options.put("RGB-G", G.b()); WMLL.options.put("RGB-B", B.b()); WMLL.TextColour = new Color(colours[0], colours[1], colours[2]).getRGB(); WMLL.options.put("lightString", lightLevelBox.b()); - if (!seedBox.b().equals(wmll.getWorldSeed())) { + if (!seedBox.b().equals(wmll.getWorldSeed()) && seedBox.b() != "0") { wmll.worldSeedSet = true; wmll.worldSeed = Long.valueOf(seedBox.b()); WMLL.options.put("Seed:"+wmll.getWorldName(), seedBox.b()); } f.a(parent); return; case 1: int c = WMLL.WMLLI; c++; if (c > (outputs.length - 1)) c = 0; b.e = "Show: "+outputs[c]; WMLL.WMLLI = c; return; case 2: int d = WMLL.outputLocation; d++; if (d > (locations.length - 1)) d = 0; b.e = "Location: "+locations[d]; WMLL.outputLocation = d; return; case 3: boolean a = wmll.classicOutput; b.e = "Output type: "+(!a ? "Classic" : "Custom"); wmll.classicOutput = !a; showButton.g = !a || WMLL.useImages; return; case 4: a = WMLL.useImages; b.e = "Images: "+(!a ? "ON" : "OFF"); WMLL.useImages = !a; showButton.g = wmll.classicOutput || WMLL.useImages; return; case -1: try { this.desktop.browse(new URI("http://www.minecraftforum.net/topic/170739-#parameters")); } catch (Exception e) { b.h = false; } return; } } protected void a(char c, int i) { if (Keyboard.KEY_ESCAPE == i) f.a(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) ? null : parent); else if (lightLevelBox.l()) lightLevelBox.a(c, i); else if (seedBox.l()) seedBox.a(c, i); else if (R.l() || G.l() || B.l()) { if (R.l()) R.a(c, i); if (G.l()) G.a(c, i); if (B.l()) B.a(c, i); //colours = new int[3]; colours[0] = Integer.valueOf((R.b().equals("") ? "0" : R.b())); colours[1] = Integer.valueOf((G.b().equals("") ? "0" : G.b())); colours[2] = Integer.valueOf((B.b().equals("") ? "0" : B.b())); if (colours[0] > 255) colours[0] = 255; if (colours[0] < 0) colours[0] = 0; if (colours[1] > 255) colours[1] = 255; if (colours[1] < 0) colours[1] = 0; if (colours[2] > 255) colours[2] = 255; if (colours[2] < 0) colours[2] = 0; } else super.a(c, i); } public void a(int i, int j, float f) { e(); a(l, "Output format", g / 2 - ((wmll.getWindowSize().a() - wmll.getFontRenderer().a("Output format") - 20) / 2), 22, 0xffffff); a(l, "Text Colour", g / 2, h / 4 + 55, 0xffffff); a(l, "R: ", g / 2 - 63, h / 4 + 71, 0xffffff); a(l, "G: ", g / 2 - 18, h / 4 + 71, 0xffffff); a(l, "B: ", g / 2 + 27, h / 4 + 71, 0xffffff); int r = colours[0]; int g1 = colours[1]; int b = colours[2]; a(l, "Colour preview", g / 2, h / 4 + 85, new Color(r, g1, b).getRGB()); a(l, "Seed", g / 2 - ((wmll.getWindowSize().a() - wmll.getFontRenderer().a("Seed") - 20) / 2), h / 4 + 92, 0xffffff); for (awm a : editboxes) a.f(); super.a(i, j, f); } public void a() { lightLevelBox.a(); R.a(); G.a(); B.a(); seedBox.a(); } protected void a(int i, int j, int k) { super.a(i, j, k); lightLevelBox.a(i, j, k); R.a(i, j, k); B.a(i, j, k); G.a(i, j, k); seedBox.a(i, j, k); } }
false
false
null
null
diff --git a/modules/plugin/epsg-hsql/src/test/java/org/geotools/referencing/factory/epsg/ThreadedHsqlEpsgFactoryTest.java b/modules/plugin/epsg-hsql/src/test/java/org/geotools/referencing/factory/epsg/ThreadedHsqlEpsgFactoryTest.java index a8485d9e4a..5a44de06e1 100644 --- a/modules/plugin/epsg-hsql/src/test/java/org/geotools/referencing/factory/epsg/ThreadedHsqlEpsgFactoryTest.java +++ b/modules/plugin/epsg-hsql/src/test/java/org/geotools/referencing/factory/epsg/ThreadedHsqlEpsgFactoryTest.java @@ -1,328 +1,326 @@ /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2007-2008, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.referencing.factory.epsg; import java.lang.reflect.Method; import static org.junit.Assert.*; import java.util.Set; import org.geotools.geometry.DirectPosition2D; import org.geotools.referencing.AbstractIdentifiedObject; import org.geotools.referencing.CRS; import org.geotools.referencing.ReferencingFactoryFinder; import org.geotools.referencing.datum.BursaWolfParameters; import org.geotools.referencing.datum.DefaultGeodeticDatum; import org.geotools.referencing.factory.IdentifiedObjectFinder; import org.junit.Before; import org.junit.Test; import org.opengis.geometry.DirectPosition; import org.opengis.referencing.FactoryException; import org.opengis.referencing.IdentifiedObject; import org.opengis.referencing.ReferenceIdentifier; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.crs.GeographicCRS; import org.opengis.referencing.operation.MathTransform; /** * This class makes sure we can find the ThreadedHsqlEpsgFactory * using ReferencingFactoryFinder. * * @author Jody * * * * @source $URL$ */ public class ThreadedHsqlEpsgFactoryTest { private static ThreadedHsqlEpsgFactory factory; private static IdentifiedObjectFinder finder; static final double EPS = 1e-06; @Before public void setUp() throws Exception { if( factory == null ){ factory = (ThreadedHsqlEpsgFactory) ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", null ); } // force in the standard timeout factory.setTimeout(30 * 60 * 1000); - if( finder == null ){ - finder = factory.getIdentifiedObjectFinder(CoordinateReferenceSystem.class); - } + finder = factory.getIdentifiedObjectFinder(CoordinateReferenceSystem.class); corruptConnection(); } @Test public void testConnectionCorruption() throws Exception { corruptConnection(); CRS.decode("EPSG:4326"); } @Test public void testConnectionCorruptionListAll() throws Exception { Set<String> original = CRS.getSupportedCodes("EPSG"); assertTrue(original.size() > 4000); corruptConnection(); Set<String> afterCorruption = CRS.getSupportedCodes("EPSG"); assertEquals(original, afterCorruption); } private void corruptConnection() throws Exception { java.lang.reflect.Field field = org.geotools.referencing.factory.BufferedAuthorityFactory.class.getDeclaredField("backingStore"); field.setAccessible(true); Object def = field.get(factory); Method getConnection = DirectEpsgFactory.class.getDeclaredMethod("getConnection"); java.sql.Connection conn = (java.sql.Connection) getConnection.invoke( def ); conn.close(); } @Test public void testCreation() throws Exception { assertNotNull(factory); CoordinateReferenceSystem epsg4326 = factory.createCoordinateReferenceSystem("EPSG:4326"); CoordinateReferenceSystem code4326 = factory.createCoordinateReferenceSystem("4326"); assertEquals("4326 equals EPSG:4326", code4326, epsg4326); assertSame("4326 == EPSG:4326", code4326, epsg4326); } @Test public void testFunctionality() throws Exception { CoordinateReferenceSystem crs1 = factory.createCoordinateReferenceSystem("4326"); CoordinateReferenceSystem crs2 = factory.createCoordinateReferenceSystem("3005"); // reproject MathTransform transform = CRS.findMathTransform(crs1, crs2,true); DirectPosition pos = new DirectPosition2D(48.417, 123.35); transform.transform(pos, null); } @Test public void testAuthorityCodes() throws Exception { Set authorityCodes = factory.getAuthorityCodes(CoordinateReferenceSystem.class); assertNotNull(authorityCodes); assertTrue(authorityCodes.size() > 3000); } @Test public void testFindWSG84() throws FactoryException { String wkt; wkt = "GEOGCS[\"WGS 84\",\n" + " DATUM[\"World Geodetic System 1984\",\n" + " SPHEROID[\"WGS 84\", 6378137.0, 298.257223563]],\n" + " PRIMEM[\"Greenwich\", 0.0],\n" + " UNIT[\"degree\", 0.017453292519943295],\n" + " AXIS[\"Geodetic latitude\", NORTH],\n" + " AXIS[\"Geodetic longitude\", EAST]]"; CoordinateReferenceSystem crs = CRS.parseWKT(wkt); finder.setFullScanAllowed(false); assertNull("Should not find without a full scan, because the WKT contains no identifier " + "and the CRS name is ambiguous (more than one EPSG object have this name).", finder.find(crs)); finder.setFullScanAllowed(true); IdentifiedObject find = finder.find(crs); assertNotNull("With full scan allowed, the CRS should be found.", find); assertTrue("Should found an object equals (ignoring metadata) to the requested one.",CRS.equalsIgnoreMetadata(crs, find)); ReferenceIdentifier found = AbstractIdentifiedObject.getIdentifier(find, factory.getAuthority()); //assertEquals("4326",found.getCode()); assertNotNull( found ); finder.setFullScanAllowed(false); String id = finder.findIdentifier(crs); assertEquals("The CRS should still be in the cache.","EPSG:4326", id); } @Test public void testFindBeijing1954() throws FactoryException { /* * The PROJCS below intentionally uses a name different from the one found in the * EPSG database, in order to force a full scan (otherwise the EPSG database would * find it by name, but we want to test the scan). */ String wkt = "PROJCS[\"Beijing 1954\",\n" + " GEOGCS[\"Beijing 1954\",\n" + " DATUM[\"Beijing 1954\",\n" + " SPHEROID[\"Krassowsky 1940\", 6378245.0, 298.3]],\n" + " PRIMEM[\"Greenwich\", 0.0],\n" + " UNIT[\"degree\", 0.017453292519943295],\n" + " AXIS[\"Geodetic latitude\", NORTH],\n" + " AXIS[\"Geodetic longitude\", EAST]],\n" + " PROJECTION[\"Transverse Mercator\"],\n" + " PARAMETER[\"central_meridian\", 135.0],\n" + " PARAMETER[\"latitude_of_origin\", 0.0],\n" + " PARAMETER[\"scale_factor\", 1.0],\n" + " PARAMETER[\"false_easting\", 500000.0],\n" + " PARAMETER[\"false_northing\", 0.0],\n" + " UNIT[\"m\", 1.0],\n" + " AXIS[\"Northing\", NORTH],\n" + " AXIS[\"Easting\", EAST]]"; CoordinateReferenceSystem crs = CRS.parseWKT(wkt); finder.setFullScanAllowed(false); assertNull("Should not find the CRS without a full scan.", finder.find(crs)); finder.setFullScanAllowed(true); IdentifiedObject find = finder.find(crs); assertNotNull("With full scan allowed, the CRS should be found.", find); assertTrue("Should found an object equals (ignoring metadata) to the requested one.", CRS.equalsIgnoreMetadata(crs, find)); assertEquals("2442", AbstractIdentifiedObject.getIdentifier(find, factory.getAuthority()).getCode()); finder.setFullScanAllowed(false); String id = finder.findIdentifier(crs); assertEquals("The CRS should still be in the cache.","EPSG:2442", id); } @Test public void testGoogleProjection() throws Exception { CoordinateReferenceSystem epsg4326 = CRS.decode("EPSG:4326"); CoordinateReferenceSystem epsg3785 = CRS.decode("EPSG:3857"); String wkt900913 = "PROJCS[\"WGS84 / Google Mercator\", " + "GEOGCS[\"WGS 84\", " + " DATUM[\"World Geodetic System 1984\", " + " SPHEROID[\"WGS 84\", 6378137.0, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], " + " AUTHORITY[\"EPSG\",\"6326\"]], " + " PRIMEM[\"Greenwich\", 0.0, " + " AUTHORITY[\"EPSG\",\"8901\"]], " + " UNIT[\"degree\", 0.017453292519943295], AUTHORITY[\"EPSG\",\"4326\"]], " + "PROJECTION[\"Mercator (1SP)\", " + "AUTHORITY[\"EPSG\",\"9804\"]], " + "PARAMETER[\"semi_major\", 6378137.0], " + "PARAMETER[\"semi_minor\", 6378137.0], " + "PARAMETER[\"latitude_of_origin\", 0.0], " + "PARAMETER[\"central_meridian\", 0.0], " + "PARAMETER[\"scale_factor\", 1.0], " + "PARAMETER[\"false_easting\", 0.0], " + "PARAMETER[\"false_northing\", 0.0], " + "UNIT[\"m\", 1.0], " + "AUTHORITY[\"EPSG\",\"900913\"]]"; CoordinateReferenceSystem epsg900913 = CRS.parseWKT(wkt900913); MathTransform t1 = CRS.findMathTransform(epsg4326, epsg3785); MathTransform t2 = CRS.findMathTransform(epsg4326, epsg900913); // check the two equate each other, we know the above 900913 definition works double[][] points = new double[][] {{0,0}, {30.0, 30.0}, {-45.0, 45.0}, {-20, -20}, {80,-80}, {85, 180}, {-85, -180}}; double[][] points2 = new double[points.length][2]; double[] tp1 = new double[2]; double[] tp2= new double[2]; for (double[] point : points) { t1.transform(point, 0, tp1, 0, 1); t2.transform(point, 0, tp2, 0, 1); assertEquals(tp1[0], tp2[0], EPS); assertEquals(tp1[1], tp2[1], EPS); // check inverse as well t1.inverse().transform(tp1, 0, tp1, 0, 1); t2.inverse().transform(tp2, 0, tp2, 0, 1); assertEquals(point[0], tp2[0], EPS); assertEquals(point[1], tp2[1], EPS); } } /** * GEOT-3497 (given the same accuracy use the transformation method with the largest valid area) */ @Test public void testNad83() throws Exception { GeographicCRS crs = (GeographicCRS) CRS.decode("EPSG:4269"); DefaultGeodeticDatum datum = (DefaultGeodeticDatum) crs.getDatum(); BursaWolfParameters[] params = datum.getBursaWolfParameters(); boolean wgs84Found = false; for(int i = 0; i < params.length; i++) { if(DefaultGeodeticDatum.isWGS84(params[i].targetDatum)) { wgs84Found = true; assertEquals(0.0, params[i].dx, EPS); assertEquals(0.0, params[i].dy, EPS); assertEquals(0.0, params[i].dz, EPS); assertEquals(0.0, params[i].ex, EPS); assertEquals(0.0, params[i].ey, EPS); assertEquals(0.0, params[i].ez, EPS); assertEquals(0.0, params[i].ppm, EPS); } } assertTrue(wgs84Found); } /** * GEOT-3644, make sure we can decode what we generated * @throws Exception */ @Test public void testEncodeAndParse() throws Exception { // a crs with out of standard axis orientation "South along 45 deg East" CoordinateReferenceSystem crs = CRS.decode("EPSG:3413"); // format it in a lenient way String wkt = crs.toString(); // parse it back, here it did break CoordinateReferenceSystem parsed = CRS.parseWKT(wkt); // also make sure we're getting back the same thing assertTrue(CRS.equalsIgnoreMetadata(crs, parsed)); } /** * GEOT-3482 * @throws Exception */ @Test public void testPPMUnit() throws Exception { // Create WGS 72 CRS where we know that the EPSG defines a unique // Position Vector Transformation to WGS 84 with ppm = 0.219 GeographicCRS wgs72 = (GeographicCRS) CRS.decode("EPSG:4322"); // Get datum DefaultGeodeticDatum datum = (DefaultGeodeticDatum)wgs72.getDatum(); // Get BursaWolf parameters BursaWolfParameters[] params = datum.getBursaWolfParameters(); // Check for coherence with the value contained in the EPSG data base assertEquals(0.219, params[0].ppm, EPS); } @Test public void testDelay() throws Exception { // force a short timeout factory.setTimeout(200); // make it do some work factory.createCoordinateReferenceSystem("EPSG:4326"); factory.getAuthorityCodes(CoordinateReferenceSystem.class); // sleep and force gc to allow the backing store to be released Thread.currentThread().sleep(2000); for(int i = 0; i < 6; i++) { System.gc(); System.runFinalization(); } Thread.currentThread().sleep(2000); // check it has been disposed of assertFalse(factory.isConnected()); // see if it's able to reconnect factory.createCoordinateReferenceSystem("EPSG:4327"); factory.getAuthorityCodes(CoordinateReferenceSystem.class); assertTrue(factory.isConnected()); } }
true
false
null
null
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java index 2e68695b..a5c2c895 100644 --- a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java +++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java @@ -1,250 +1,240 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.provider.cts; import com.android.cts.stub.R; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.provider.MediaStore.Images.Media; import android.provider.MediaStore.Images.Thumbnails; import android.test.InstrumentationTestCase; import java.util.ArrayList; @TestTargetClass(MediaStore.Images.Thumbnails.class) public class MediaStore_Images_ThumbnailsTest extends InstrumentationTestCase { private ArrayList<Uri> mRowsAdded; private Context mContext; private ContentResolver mContentResolver; private FileCopyHelper mHelper; @Override protected void tearDown() throws Exception { for (Uri row : mRowsAdded) { try { mContentResolver.delete(row, null, null); } catch (UnsupportedOperationException e) { // There is no way to delete rows from table "thumbnails" of internals database. // ignores the exception and make the loop goes on } } mHelper.clear(); super.tearDown(); } @Override protected void setUp() throws Exception { super.setUp(); mContext = getInstrumentation().getTargetContext(); mContentResolver = mContext.getContentResolver(); mHelper = new FileCopyHelper(mContext); mRowsAdded = new ArrayList<Uri>(); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "queryMiniThumbnails", args = {ContentResolver.class, Uri.class, int.class, String[].class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "query", args = {ContentResolver.class, Uri.class, String[].class} ) }) public void testQueryInternalThumbnails() { Cursor c = Thumbnails.queryMiniThumbnails(mContentResolver, Thumbnails.INTERNAL_CONTENT_URI, Thumbnails.MICRO_KIND, null); int previousMicroKindCount = c.getCount(); c.close(); // add a thumbnail String path = mHelper.copy(R.raw.scenery, "testThumbnails.jpg"); ContentValues values = new ContentValues(); values.put(Thumbnails.KIND, Thumbnails.MINI_KIND); values.put(Thumbnails.DATA, path); Uri uri = mContentResolver.insert(Thumbnails.INTERNAL_CONTENT_URI, values); if (uri != null) { mRowsAdded.add(uri); } // query with the uri of the thumbnail and the kind c = Thumbnails.queryMiniThumbnails(mContentResolver, uri, Thumbnails.MINI_KIND, null); c.moveToFirst(); assertEquals(1, c.getCount()); assertEquals(Thumbnails.MINI_KIND, c.getInt(c.getColumnIndex(Thumbnails.KIND))); assertEquals(path, c.getString(c.getColumnIndex(Thumbnails.DATA))); // query all thumbnails with other kind c = Thumbnails.queryMiniThumbnails(mContentResolver, Thumbnails.INTERNAL_CONTENT_URI, Thumbnails.MICRO_KIND, null); assertEquals(previousMicroKindCount, c.getCount()); c.close(); // query without kind c = Thumbnails.query(mContentResolver, uri, null); assertEquals(1, c.getCount()); c.moveToFirst(); assertEquals(Thumbnails.MINI_KIND, c.getInt(c.getColumnIndex(Thumbnails.KIND))); assertEquals(path, c.getString(c.getColumnIndex(Thumbnails.DATA))); c.close(); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "queryMiniThumbnail", args = {ContentResolver.class, long.class, int.class, String[].class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "query", args = {ContentResolver.class, Uri.class, String[].class} ) }) public void testQueryExternalMiniThumbnails() { // insert the image by bitmap Bitmap src = BitmapFactory.decodeResource(mContext.getResources(), R.raw.scenery); String stringUrl = null; try{ stringUrl = Media.insertImage(mContentResolver, src, null, null); } catch (UnsupportedOperationException e) { // the tests will be aborted because the image will be put in sdcard fail("There is no sdcard attached! " + e.getMessage()); } assertNotNull(stringUrl); mRowsAdded.add(Uri.parse(stringUrl)); // get the original image id Cursor c = mContentResolver.query(Uri.parse(stringUrl), new String[]{ Media._ID }, null, null, null); c.moveToFirst(); long imageId = c.getLong(c.getColumnIndex(Media._ID)); c.close(); String[] sizeProjection = new String[] { Thumbnails.WIDTH, Thumbnails.HEIGHT }; c = Thumbnails.queryMiniThumbnail(mContentResolver, imageId, Thumbnails.MINI_KIND, sizeProjection); assertEquals(1, c.getCount()); c.moveToFirst(); assertEquals(320, c.getLong(c.getColumnIndex(Thumbnails.WIDTH))); assertEquals(240, c.getLong(c.getColumnIndex(Thumbnails.HEIGHT))); c.close(); c = Thumbnails.queryMiniThumbnail(mContentResolver, imageId, Thumbnails.MICRO_KIND, sizeProjection); assertEquals(1, c.getCount()); c.moveToFirst(); assertEquals(50, c.getLong(c.getColumnIndex(Thumbnails.WIDTH))); assertEquals(50, c.getLong(c.getColumnIndex(Thumbnails.HEIGHT))); c.close(); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getContentUri", args = {String.class} ) public void testGetContentUri() { assertNotNull(mContentResolver.query(Thumbnails.getContentUri("internal"), null, null, null, null)); assertNotNull(mContentResolver.query(Thumbnails.getContentUri("external"), null, null, null, null)); // can not accept any other volume names String volume = "fakeVolume"; assertNull(mContentResolver.query(Thumbnails.getContentUri(volume), null, null, null, null)); } public void testStoreImagesMediaExternal() { ContentValues values = new ContentValues(); values.put(Thumbnails.KIND, Thumbnails.FULL_SCREEN_KIND); values.put(Thumbnails.IMAGE_ID, 0); values.put(Thumbnails.HEIGHT, 480); values.put(Thumbnails.WIDTH, 320); values.put(Thumbnails.DATA, "/sdcard/testimage.jpg"); // insert Uri uri = mContentResolver.insert(Thumbnails.EXTERNAL_CONTENT_URI, values); assertNotNull(uri); // query Cursor c = mContentResolver.query(uri, null, null, null, null); assertEquals(1, c.getCount()); c.moveToFirst(); long id = c.getLong(c.getColumnIndex(Thumbnails._ID)); assertTrue(id > 0); assertEquals(Thumbnails.FULL_SCREEN_KIND, c.getInt(c.getColumnIndex(Thumbnails.KIND))); assertEquals(0, c.getLong(c.getColumnIndex(Thumbnails.IMAGE_ID))); assertEquals(480, c.getInt(c.getColumnIndex(Thumbnails.HEIGHT))); assertEquals(320, c.getInt(c.getColumnIndex(Thumbnails.WIDTH))); assertEquals("/sdcard/testimage.jpg", c.getString(c.getColumnIndex(Thumbnails.DATA))); c.close(); // update values.clear(); values.put(Thumbnails.KIND, Thumbnails.MICRO_KIND); values.put(Thumbnails.IMAGE_ID, 1); values.put(Thumbnails.HEIGHT, 50); values.put(Thumbnails.WIDTH, 50); values.put(Thumbnails.DATA, "/sdcard/testimage1.jpg"); - try { - assertEquals(1, mContentResolver.update(uri, values, null, null)); - fail("Should throw UnsupportedOperationException when updating the thumbnail"); - } catch (UnsupportedOperationException e) { - // expected - } + assertEquals(1, mContentResolver.update(uri, values, null, null)); // delete - try { - assertEquals(1, mContentResolver.delete(uri, null, null)); - fail("Should throw UnsupportedOperationException when deleting the thumbnail"); - } catch (UnsupportedOperationException e) { - // expected - } + assertEquals(1, mContentResolver.delete(uri, null, null)); } public void testStoreImagesMediaInternal() { // can not insert any data, so other operations can not be tested try { mContentResolver.insert(Thumbnails.INTERNAL_CONTENT_URI, new ContentValues()); fail("Should throw UnsupportedOperationException when inserting into internal " + "database"); } catch (UnsupportedOperationException e) { // expected } } }
false
false
null
null
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java index 45b39714b..1bf72c150 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java @@ -1,43 +1,48 @@ /*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.report.engine.layout.area.impl; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.layout.area.IArea; public class RowArea extends ContainerArea { public void addChild( IArea area ) { super.addChild( area ); } RowArea( IRowContent row ) { super( row ); style.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_LEFT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_RIGHT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_BOTTOM_WIDTH, IStyle.NUMBER_0 ); + // Row does not support margin, remove them. + style.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0); + style.setProperty( IStyle.STYLE_MARGIN_LEFT, IStyle.NUMBER_0); + style.setProperty( IStyle.STYLE_MARGIN_RIGHT, IStyle.NUMBER_0); + style.setProperty( IStyle.STYLE_MARGIN_BOTTOM, IStyle.NUMBER_0); } public int getRowID( ) { if ( content != null ) { return ( (IRowContent) content ).getRowID( ); } return 0; } }
true
true
RowArea( IRowContent row ) { super( row ); style.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_LEFT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_RIGHT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_BOTTOM_WIDTH, IStyle.NUMBER_0 ); }
RowArea( IRowContent row ) { super( row ); style.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_LEFT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_RIGHT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_BOTTOM_WIDTH, IStyle.NUMBER_0 ); // Row does not support margin, remove them. style.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0); style.setProperty( IStyle.STYLE_MARGIN_LEFT, IStyle.NUMBER_0); style.setProperty( IStyle.STYLE_MARGIN_RIGHT, IStyle.NUMBER_0); style.setProperty( IStyle.STYLE_MARGIN_BOTTOM, IStyle.NUMBER_0); }
diff --git a/rameses-client-ui/src/com/rameses/rcp/control/table/CellRenderers.java b/rameses-client-ui/src/com/rameses/rcp/control/table/CellRenderers.java index 476b92c2..a8a5d374 100644 --- a/rameses-client-ui/src/com/rameses/rcp/control/table/CellRenderers.java +++ b/rameses-client-ui/src/com/rameses/rcp/control/table/CellRenderers.java @@ -1,599 +1,600 @@ /* * CellRenderers.java * * Created on June 13, 2013, 1:16 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.rameses.rcp.control.table; import com.rameses.common.ExpressionResolver; import com.rameses.rcp.common.AbstractListDataProvider; import com.rameses.rcp.common.CheckBoxColumnHandler; import com.rameses.rcp.common.Column; import com.rameses.rcp.common.ComboBoxColumnHandler; import com.rameses.rcp.common.DateColumnHandler; import com.rameses.rcp.common.DecimalColumnHandler; import com.rameses.rcp.common.IntegerColumnHandler; import com.rameses.rcp.common.LookupColumnHandler; import com.rameses.rcp.common.OpenerColumnHandler; import com.rameses.rcp.common.StyleRule; import com.rameses.rcp.constant.TextCase; import com.rameses.rcp.support.ColorUtil; import com.rameses.rcp.support.ComponentSupport; import com.rameses.rcp.util.ControlSupport; import com.rameses.rcp.util.UIControlUtil; import java.awt.Color; import java.awt.Component; import java.awt.Insets; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.TableCellRenderer; /** * * @author wflores */ public class CellRenderers { private static Map<String,Class> renderers; static { renderers = new HashMap(); renderers.put("text", TextRenderer.class); renderers.put("string", TextRenderer.class); renderers.put("boolean", CheckBoxRenderer.class); renderers.put("checkbox", CheckBoxRenderer.class); renderers.put("combo", ComboBoxRenderer.class); renderers.put("combobox", ComboBoxRenderer.class); renderers.put("date", DateRenderer.class); renderers.put("decimal", DecimalRenderer.class); renderers.put("double", DecimalRenderer.class); renderers.put("integer", IntegerRenderer.class); renderers.put("lookup", LookupRenderer.class); renderers.put("opener", OpenerRenderer.class); } public static AbstractRenderer getRendererFor(Column oColumn) { Column.TypeHandler handler = oColumn.getTypeHandler(); if (handler == null) handler = ColumnHandlerUtil.newInstance().createTypeHandler(oColumn); return null; } public static String getPreferredAlignment(Column oColumn) { if (oColumn == null) return null; String alignment = oColumn.getAlignment(); if (alignment != null) return alignment; Column.TypeHandler handler = oColumn.getTypeHandler(); if (handler instanceof CheckBoxColumnHandler) oColumn.setAlignment("center"); else if (handler instanceof DecimalColumnHandler) oColumn.setAlignment("right"); else if (handler instanceof IntegerColumnHandler) oColumn.setAlignment("center"); else oColumn.setAlignment("left"); return oColumn.getAlignment(); } // <editor-fold defaultstate="collapsed" desc=" Context (class) "> public static class Context { private JTable table; private Object value; private int rowIndex; private int columnIndex; private TableControl tableControl; private TableControlModel tableControlModel; Context(JTable table, Object value, int rowIndex, int columnIndex) { this.table = table; this.value = value; this.rowIndex = rowIndex; this.columnIndex = columnIndex; this.tableControl = (TableControl) table; this.tableControlModel = (TableControlModel) this.tableControl.getModel(); } public JTable getTable() { return table; } public Object getValue() { return value; } public int getRowIndex() { return rowIndex; } public int getColumnIndex() { return columnIndex; } public TableControl getTableControl() { return tableControl; } public TableControlModel getTableControlModel() { return tableControlModel; } public AbstractListDataProvider getDataProvider() { return tableControl.getDataProvider(); } public Object getItemData() { return getItemData(this.rowIndex); } public Object getItemData(int rowIndex) { return getDataProvider().getListItemData(rowIndex); } public Column getColumn() { return getColumn(this.columnIndex); } public Column getColumn(int index) { return getTableControlModel().getColumn(index); } public Object createExpressionBean() { return createExpressionBean(getItemData()); } public Object createExpressionBean(Object bean) { return getTableControl().createExpressionBean(bean); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" AbstractRenderer (class) "> public static abstract class AbstractRenderer implements TableCellRenderer { private Insets CELL_MARGIN = TableUtil.CELL_MARGIN; private Color FOCUS_BG = TableUtil.FOCUS_BG; private ComponentSupport componentSupport; private CellRenderers.Context ctx; protected ComponentSupport getComponentSupport() { if (componentSupport == null) componentSupport = new ComponentSupport(); return componentSupport; } protected CellRenderers.Context getContext() { return ctx; } protected TableControl getTableControl() { return ctx.getTableControl(); } protected TableControlModel getTableControlModel() { return ctx.getTableControlModel(); } public abstract JComponent getComponent(JTable table, int rowIndex, int columnIndex); public abstract void refresh(JTable table, Object value, boolean selected, boolean focus, int rowIndex, int columnIndex); public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int columnIndex) { ctx = new CellRenderers.Context(table, value, rowIndex, columnIndex); TableControl tc = ctx.getTableControl(); TableControlModel tcm = ctx.getTableControlModel(); JComponent comp = getComponent(table, rowIndex, columnIndex); getComponentSupport().setEmptyBorder(comp, CELL_MARGIN); comp.setFont(table.getFont()); if (isSelected) { comp.setBackground(table.getSelectionBackground()); comp.setForeground(table.getSelectionForeground()); comp.setOpaque(true); if (hasFocus) { comp.setBackground(FOCUS_BG); comp.setForeground(table.getForeground()); } } else { comp.setForeground(table.getForeground()); comp.setOpaque(false); if ((rowIndex+1)%2 == 0) { if (tc.getEvenBackground() != null) { comp.setBackground(tc.getEvenBackground()); comp.setOpaque(true); } if (tc.getEvenForeground() != null) comp.setForeground(tc.getEvenForeground()); } else { if (tc.getOddBackground() != null) { comp.setBackground(tc.getOddBackground()); comp.setOpaque(true); } if (tc.getOddForeground() != null) comp.setForeground(tc.getOddForeground()); } } try { if (!hasFocus) applyStyles(comp); } catch(Throwable ex) {;} AbstractListDataProvider ldp = ctx.getDataProvider(); String errmsg = ldp.getMessageSupport().getErrorMessage(rowIndex); if (errmsg != null) { if (!hasFocus) { comp.setBackground( tc.getErrorBackground() ); comp.setForeground( tc.getErrorForeground() ); comp.setOpaque(true); } } if ( !table.isEnabled() ) { Color c = comp.getBackground(); comp.setBackground(ColorUtil.brighter(c, 5)); c = comp.getForeground(); comp.setForeground(ColorUtil.brighter(c, 5)); } //border support Border inner = getComponentSupport().createEmptyBorder(CELL_MARGIN); Border border = BorderFactory.createEmptyBorder(1,1,1,1); if (hasFocus) { if (isSelected) border = UIManager.getBorder("Table.focusSelectedCellHighlightBorder"); if (border == null) border = UIManager.getBorder("Table.focusCellHighlightBorder"); } comp.setBorder(BorderFactory.createCompoundBorder(border, inner)); refresh(table, value, isSelected, hasFocus, rowIndex, columnIndex); return comp; } private void applyStyles(JComponent comp) { TableControl tc = getContext().getTableControl(); if (tc.getVarName() == null || tc.getVarName().length() == 0) return; if (tc.getId() == null || tc.getId().length() == 0) return; StyleRule[] styles = tc.getBinding().getStyleRules(); if (styles == null || styles.length == 0) return; String colName = getContext().getColumn().getName(); String sname = tc.getId()+":"+tc.getVarName()+"."+colName; ExpressionResolver res = ExpressionResolver.getInstance(); //apply style rules for (StyleRule r : styles) { String pattern = r.getPattern(); String expr = r.getExpression(); if (expr != null && sname.matches(pattern)){ try { boolean matched = res.evalBoolean(expr, getContext().createExpressionBean()); if (matched) ControlSupport.setStyles(r.getProperties(), comp); } catch (Throwable ign){;} } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" AbstractNumberRenderer (class) "> public abstract static class AbstractNumberRenderer extends AbstractRenderer { private JLabel label; public AbstractNumberRenderer() { label = new JLabel(); label.setHorizontalAlignment(SwingConstants.RIGHT); } public JComponent getComponent(JTable table, int rowIndex, int columnIndex) { return label; } protected abstract String getFormattedValue(Column c, Object value); protected String resolveAlignment(String alignment) { return alignment; } public void refresh(JTable table, Object value, boolean selected, boolean focus, int rowIndex, int columnIndex) { Column c = getContext().getColumn(); String result = getFormattedValue(c, value); label.setText((result == null ? "" : result)); String alignment = c.getAlignment(); if (alignment != null) getComponentSupport().alignText(label, alignment); } protected String formatValue(Number value, String format, String defaultFormat) { if (value == null) return null; if ("".equals(format)) return value.toString(); DecimalFormat formatter = null; if ( format != null) formatter = new DecimalFormat(format); else formatter = new DecimalFormat(defaultFormat); return formatter.format(value); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" TextRenderer (class) "> public static class TextRenderer extends AbstractRenderer { private JLabel label; public TextRenderer() { label = createComponent(); label.setVerticalAlignment(SwingConstants.CENTER); } private JLabel createComponent() { label = new JLabel(){ }; return label; } public JComponent getComponent(JTable table, int rowIndex, int columnIndex) { return label; } protected Object resolveValue(CellRenderers.Context ctx) { return ctx.getValue(); } public void refresh(JTable table, Object value, boolean selected, boolean focus, int rowIndex, int columnIndex) { Object columnValue = resolveValue(getContext()); Column oColumn = getContext().getColumn(); TextCase oTextCase = oColumn.getTextCase(); if (oTextCase != null && columnValue != null) label.setText(oTextCase.convert(columnValue.toString())); label.setHorizontalAlignment( SwingConstants.LEFT ); if ( columnValue != null && oColumn.isHtmlDisplay() ) columnValue = "<html>" + columnValue + "</html>"; label.setText((columnValue == null ? "" : columnValue.toString())); //set alignment if it is specified in the Column model if ( oColumn.getAlignment() != null ) getComponentSupport().alignText(label, oColumn.getAlignment()); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" CheckBoxRenderer (class) "> public static class CheckBoxRenderer extends AbstractRenderer { private JCheckBox component; private JLabel empty; public CheckBoxRenderer() { component = new JCheckBox(); component.setHorizontalAlignment(SwingConstants.CENTER); component.setBorderPainted(true); //empty renderer when row object is null empty = new JLabel(""); } public JComponent getComponent(JTable table, int rowIndex, int colIndex) { return (getContext().getItemData() == null? empty: component); } public void refresh(JTable table, Object value, boolean selected, boolean focus, int rowIndex, int columnIndex) { Object itemData = getContext().getItemData(); if (itemData == null) return; Column oColumn = getContext().getColumn(); component.setSelected(resolveValue(oColumn, value)); } private boolean resolveValue(Column oColumn, Object value) { Object checkValue = null; if (oColumn.getTypeHandler() instanceof CheckBoxColumnHandler) checkValue = ((CheckBoxColumnHandler) oColumn.getTypeHandler()).getCheckValue(); else checkValue = oColumn.getCheckValue(); boolean selected = false; if (value == null) selected = false; else if (value != null && checkValue != null && value.equals(checkValue)) selected = true; else if (value.equals(checkValue+"")) selected = true; else if ("true".equals(value+"")) selected = true; else if ("yes".equals(value+"")) selected = true; else if ("t".equals(value+"")) selected = true; else if ("y".equals(value+"")) selected = true; else if ("1".equals(value+"")) selected = true; + //System.out.println("renderer: name="+oColumn.getName() + ", value="+value + ", selected="+selected); return selected; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" ComboBoxRenderer (class) "> public static class ComboBoxRenderer extends TextRenderer { protected Object resolveValue(CellRenderers.Context ctx) { String expression = null; Column oColumn = ctx.getColumn(); if (oColumn.getTypeHandler() instanceof ComboBoxColumnHandler) expression = ((ComboBoxColumnHandler) oColumn.getTypeHandler()).getExpression(); else expression = oColumn.getExpression(); Object cellValue = ctx.getValue(); if (expression != null && !(cellValue instanceof String)) { try { Object exprBean = ctx.createExpressionBean(); cellValue = UIControlUtil.evaluateExpr(exprBean, expression); } catch(Exception e) {;} } return cellValue; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" DateRenderer (class) "> public static class DateRenderer extends TextRenderer { private SimpleDateFormat outputFormatter; protected Object resolveValue(CellRenderers.Context ctx) { String format = null; Column oColumn = ctx.getColumn(); if (oColumn.getTypeHandler() instanceof DateColumnHandler) format = ((DateColumnHandler) oColumn.getTypeHandler()).getOutputFormat(); else format = oColumn.getFormat(); Object cellValue = ctx.getValue(); if (format != null && cellValue instanceof Date) { try { if (outputFormatter == null) outputFormatter = new SimpleDateFormat(format); cellValue = outputFormatter.format((Date) cellValue); } catch(Exception ex) {;} } return cellValue; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" DecimalRenderer (class) "> public static class DecimalRenderer extends AbstractNumberRenderer { protected String getFormattedValue(Column c, Object value) { Number num = null; if (value == null) { /* do nothing */ } else if (value instanceof BigDecimal) { num = (BigDecimal) value; } else { try { num = new BigDecimal(value.toString()); } catch(Exception e) {} } if (num == null) return null; String format = null; if (c.getTypeHandler() instanceof DecimalColumnHandler) format = ((DecimalColumnHandler) c.getTypeHandler()).getFormat(); else format = c.getFormat(); if (format == null || format.length() == 0) return num.toString(); return formatValue(num, format, "#,##0.00"); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" IntegerRenderer (class) "> public static class IntegerRenderer extends AbstractNumberRenderer { protected String resolveAlignment(String alignment) { if (alignment == null || alignment.length() == 0) return "CENTER"; else return alignment; } protected String getFormattedValue(Column c, Object value) { Number num = null; if (value == null) { /* do nothing */ } else if (value instanceof Integer) { num = (Integer) value; } else { try { num = new Integer(value.toString()); } catch(Exception e) {} } if (num == null) return null; String format = null; if (c.getTypeHandler() instanceof IntegerColumnHandler) format = ((IntegerColumnHandler) c.getTypeHandler()).getFormat(); else format = c.getFormat(); if (format == null || format.length() == 0) return num.toString(); else return formatValue(num, c.getFormat(), "0"); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" LookupRenderer (class) "> public static class LookupRenderer extends TextRenderer { protected Object resolveValue(CellRenderers.Context ctx) { String expression = null; Column oColumn = ctx.getColumn(); if (oColumn.getTypeHandler() instanceof LookupColumnHandler) expression = ((LookupColumnHandler) oColumn.getTypeHandler()).getExpression(); else expression = oColumn.getExpression(); Object cellValue = ctx.getValue(); if (expression != null) { try { Object exprBean = getContext().createExpressionBean(); cellValue = UIControlUtil.evaluateExpr(exprBean, expression); } catch(Exception e) {;} } return cellValue; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" OpenerRenderer (class) "> public static class OpenerRenderer extends TextRenderer { protected Object resolveValue(CellRenderers.Context ctx) { String expression = null; Column oColumn = ctx.getColumn(); if (oColumn.getTypeHandler() instanceof OpenerColumnHandler) expression = ((OpenerColumnHandler) oColumn.getTypeHandler()).getExpression(); else expression = oColumn.getExpression(); Object cellValue = ctx.getValue(); if (expression != null) { try { Object exprBean = getContext().createExpressionBean(); cellValue = UIControlUtil.evaluateExpr(exprBean, expression); } catch(Exception e) {;} } return cellValue; } } // </editor-fold> } diff --git a/rameses-client-ui/src/com/rameses/rcp/control/table/DataTableComponent.java b/rameses-client-ui/src/com/rameses/rcp/control/table/DataTableComponent.java index 2687c2da..7dd46dce 100644 --- a/rameses-client-ui/src/com/rameses/rcp/control/table/DataTableComponent.java +++ b/rameses-client-ui/src/com/rameses/rcp/control/table/DataTableComponent.java @@ -1,1708 +1,1708 @@ /* * DataTableComponent.java * * Created on January 31, 2011 * @author jaycverg */ package com.rameses.rcp.control.table; import com.rameses.common.ExpressionResolver; import com.rameses.rcp.common.AbstractListDataProvider; import com.rameses.rcp.common.AbstractListModel; import com.rameses.rcp.common.Action; import com.rameses.rcp.common.Column; import com.rameses.rcp.common.EditorListModel; import com.rameses.rcp.common.ListItem; import com.rameses.rcp.common.ListPageModel; import com.rameses.rcp.common.MsgBox; import com.rameses.rcp.common.PropertyChangeHandler; import com.rameses.rcp.common.TableModelHandler; import com.rameses.rcp.control.XCheckBox; import com.rameses.rcp.framework.Binding; import com.rameses.rcp.framework.ChangeLog; import com.rameses.rcp.framework.ClientContext; import com.rameses.rcp.ui.UIControl; import com.rameses.rcp.ui.UIInput; import com.rameses.rcp.ui.Validatable; import com.rameses.rcp.util.ActionMessage; import com.rameses.rcp.util.UICommandUtil; import com.rameses.rcp.util.UIControlUtil; import com.rameses.rcp.util.UIInputUtil; import com.rameses.util.ValueUtil; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.beans.Beans; import javax.swing.JTable; import java.util.*; import javax.swing.InputVerifier; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRootPane; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import javax.swing.event.TableModelEvent; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.text.JTextComponent; public class DataTableComponent extends JTable implements TableControl { private static final String COLUMN_POINT = "COLUMN_POINT"; private Map<Integer, JComponent> editors = new HashMap(); private DataTableBinding itemBinding = new DataTableBinding(); private DataTableModel tableModel; private TableListener tableListener; private ListPageModel pageModel; private EditorListModel editorModel; private AbstractListDataProvider dataProvider; private PropertyChangeHandlerImpl propertyHandler; private TableModelHandlerImpl tableModelHandler; private String multiSelectName; private String varName = "item"; private String varStatus; //internal flags private int editingRow = -1; private boolean readonly; private boolean required; private boolean editingMode; private boolean editorBeanLoaded; private boolean rowCommited = true; private boolean processingRequest; private JComponent currentEditor; private KeyEvent currentKeyEvent; private ListItem previousItem; //row background color options private Color evenBackground; private Color oddBackground; private Color errorBackground = Color.PINK; //row foreground color options private Color evenForeground; private Color oddForeground; private Color errorForeground = Color.BLACK; private Binding binding; private JLabel lblProcessing; private boolean fetching; private int rowHeaderHeight = -1; public DataTableComponent() { initComponents(); } // <editor-fold defaultstate="collapsed" desc=" initComponents "> private void initComponents() { super.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); propertyHandler = new PropertyChangeHandlerImpl(); tableModelHandler = new TableModelHandlerImpl(); tableModel = new DataTableModel(); setTableHeader(new DataTableHeader(this)); getTableHeader().setReorderingAllowed(false); addKeyListener(new TableKeyAdapter()); int cond = WHEN_ANCESTOR_OF_FOCUSED_COMPONENT; KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0); getInputMap(cond).put(enter, "selectNextColumnCell"); KeyStroke shiftEnter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 1); getInputMap(cond).put(shiftEnter, "selectPreviousColumnCell"); new TableEnterAction().install(this); new TableEscapeAction().install(this); //row editing ctrl+Z support KeyStroke ctrlZ = KeyStroke.getKeyStroke("ctrl Z"); registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!rowCommited) { ChangeLog log = itemBinding.getChangeLog(); if (log.hasChanges()) undo(); //clear row editing flag of everything is undone if (!log.hasChanges()) { rowCommited = true; oncancelRowEdit(); } } } }, ctrlZ, JComponent.WHEN_FOCUSED); addComponentListener(new ComponentListener() { public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} public void componentShown(ComponentEvent e) {} public void componentResized(ComponentEvent e) { if (currentEditor == null) return; Point colPoint = (Point) currentEditor.getClientProperty(COLUMN_POINT); Rectangle bounds = getCellRect(colPoint.y, colPoint.x, false); currentEditor.setBounds(bounds); currentEditor.requestFocus(); currentEditor.grabFocus(); } }); addMouseListener(new PopupMenuAdapter()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" Getters/Setters "> protected void uninstall(AbstractListDataProvider dataProvider) {} protected void install(AbstractListDataProvider dataProvider) {} public AbstractListDataProvider getDataProvider() { return dataProvider; } public void setDataProvider(AbstractListDataProvider dataProvider) { if (Beans.isDesignTime()) { Column[] columns = (dataProvider == null? null: dataProvider.getColumns()); DataTableModelDesignTime dtm = new DataTableModelDesignTime(columns); setModel(dtm); dtm.applyColumnAttributes(this); return; } if (this.dataProvider != null) { this.dataProvider.removeHandler(propertyHandler); this.dataProvider.removeHandler(tableModelHandler); uninstall(this.dataProvider); } this.dataProvider = dataProvider; this.editorModel = null; this.pageModel = null; if (this.dataProvider != null) this.dataProvider.addHandler(propertyHandler); if (dataProvider instanceof ListPageModel) this.pageModel = (ListPageModel) dataProvider; if (dataProvider instanceof EditorListModel) this.editorModel = (EditorListModel) dataProvider; tableModel.setDataProvider(dataProvider); if (dataProvider != null) { dataProvider.addHandler(tableModelHandler); install(dataProvider); } itemBinding.setRoot(getBinding()); tableModel.setBinding(itemBinding); setModel(tableModel); buildColumns(); onTableModelChanged(tableModel); } public DataTableModel getDataTableModel() { return tableModel; } public boolean isProcessingRequest() { return (processingRequest || fetching); } public String getId() { DataTableModel dtm = getDataTableModel(); return (dtm == null? null: dtm.getId()); } public void setId(String id) { DataTableModel dtm = getDataTableModel(); if (dtm != null) dtm.setId(id); } public String getVarName() { return varName; } public void setVarName(String varName) { this.varName = varName; getDataTableModel().setVarName(varName); } public String getVarStatus() { return varStatus; } public void setVarStatus(String varStatus) { this.varStatus = varStatus; getDataTableModel().setVarStatus(varStatus); } public String getMultiSelectName() { return multiSelectName; } public void setMultiSelectName(String multiSelectName) { this.multiSelectName = multiSelectName; getDataTableModel().setMultiSelectName(multiSelectName); } public void setBinding(Binding binding) { this.binding = binding; } public Binding getBinding() { return binding; } public void setListener(TableListener listener) { this.tableListener = listener; } public boolean isRequired() { return required; } public boolean isEditingMode() { return editingMode; } public boolean isAutoResize() { return getAutoResizeMode() != super.AUTO_RESIZE_OFF; } public void setAutoResize(boolean autoResize) { if ( autoResize ) { setAutoResizeMode(super.AUTO_RESIZE_LAST_COLUMN); } else { setAutoResizeMode(super.AUTO_RESIZE_OFF); } } public boolean isReadonly() { return readonly; } public void setReadonly(boolean readonly) { this.readonly = readonly; } public Color getEvenBackground() { return evenBackground; } public void setEvenBackground(Color evenBackground) { this.evenBackground = evenBackground; } public Color getOddBackground() { return oddBackground; } public void setOddBackground(Color oddBackground) { this.oddBackground = oddBackground; } public Color getErrorBackground() { return errorBackground; } public void setErrorBackground(Color errorBackground) { this.errorBackground = errorBackground; } public Color getEvenForeground() { return evenForeground; } public void setEvenForeground(Color evenForeground) { this.evenForeground = evenForeground; } public Color getOddForeground() { return oddForeground; } public void setOddForeground(Color oddForeground) { this.oddForeground = oddForeground; } public Color getErrorForeground() { return errorForeground; } public void setErrorForeground(Color errorForeground) { this.errorForeground = errorForeground; } public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); setRowHeaderHeight(rowHeight); } public int getRowHeaderHeight() { return rowHeaderHeight; } public void setRowHeaderHeight(int rowHeaderHeight) { this.rowHeaderHeight = rowHeaderHeight; getTableHeader().setPreferredSize(new Dimension(Short.MAX_VALUE, rowHeaderHeight)); getTableHeader().repaint(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" buildColumns "> private void buildColumns() { removeAll(); //remove all editors editors.clear(); //clear column editors map required = false; //reset flag to false ColumnHandlerUtil handlerUtil = ColumnHandlerUtil.newInstance(); int length = tableModel.getColumnCount(); for ( int i=0; i<length; i++ ) { Column col = tableModel.getColumn(i); TableCellRenderer cellRenderer = TableUtil.getCellRenderer(col); handlerUtil.prepare(col); TableColumn tableCol = getColumnModel().getColumn(i); tableCol.setCellRenderer(cellRenderer); applyColumnProperties(tableCol, col); if (!ValueUtil.isEmpty(col.getEditableWhen())) col.setEditable(true); if (!col.isEditable()) continue; if (editors.containsKey(i)) continue; JComponent editor = TableUtil.createCellEditor(col); if (editor == null) continue; if (!(editor instanceof UIControl)) { System.out.println("Column editor must be an instance of UIControl "); continue; } editor.setVisible(false); editor.setName(col.getName()); editor.setBounds(-10, -10, 10, 10); editor.putClientProperty(JTable.class, true); editor.putClientProperty(Binding.class, getBinding()); editor.putClientProperty(UIInputUtil.Support.class, new EditorInputSupport()); editor.putClientProperty(Validatable.class, new TableColumnValidator(itemBinding, col)); editor.addFocusListener(new EditorFocusSupport()); addKeyboardAction(editor, KeyEvent.VK_ENTER, true); addKeyboardAction(editor, KeyEvent.VK_TAB, true); addKeyboardAction(editor, KeyEvent.VK_ESCAPE, false); UIControl uicomp = (UIControl) editor; uicomp.setBinding(itemBinding); itemBinding.register(uicomp); if (editor instanceof Validatable) { Validatable vi = (Validatable) editor; vi.setRequired(col.isRequired()); vi.setCaption(col.getCaption()); if (vi.isRequired()) required = true; } editors.put(i, editor); add(editor); } itemBinding.setOwner( binding.getOwner() ); itemBinding.setViewContext( binding.getViewContext() ); itemBinding.init(); //initialize item binding } public void rebuildColumns() { tableModel = new DataTableModel(); tableModel.setDataProvider(dataProvider); tableModel.setVarName(getVarName()); tableModel.setVarStatus(getVarStatus()); tableModel.setMultiSelectName(getMultiSelectName()); setModel(tableModel); buildColumns(); onTableModelChanged(tableModel); } protected void onTableModelChanged(DataTableModel tableModel){ } private void addKeyboardAction(JComponent comp, int key, boolean commit) { EditorKeyBoardAction kba = new EditorKeyBoardAction(comp, key, commit); comp.registerKeyboardAction(kba, kba.keyStroke, JComponent.WHEN_FOCUSED); } private void applyColumnProperties(TableColumn tc, Column c) { if ( c.getMaxWidth() > 0 ) tc.setMaxWidth( c.getMaxWidth() ); if ( c.getMinWidth() > 0 ) tc.setMinWidth( c.getMinWidth() ); if ( c.getWidth() > 0 ) { tc.setWidth( c.getWidth() ); tc.setPreferredWidth( c.getWidth() ); } tc.setResizable( c.isResizable() ); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" JTable properties "> protected void paintComponent(Graphics g) { super.paintComponent(g); if ( dataProvider != null && fetching ) { if ( lblProcessing == null ) { lblProcessing = new JLabel("<html><h1>Loading...</h1></html>"); lblProcessing.setForeground(Color.GRAY); lblProcessing.setVerticalAlignment(SwingUtilities.TOP); lblProcessing.setBorder(new EmptyBorder(5,10,10,10)); } Rectangle rec = getVisibleRect(); Graphics g2 = g.create(); g2.translate(rec.x, rec.y); lblProcessing.setSize(rec.width, rec.height); lblProcessing.paint(g2); g2.dispose(); } } public void setTableHeader(JTableHeader tableHeader) { super.setTableHeader(tableHeader); tableHeader = getTableHeader(); if (tableHeader == null) return; tableHeader.setDefaultRenderer(TableUtil.getHeaderRenderer()); tableHeader.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent me) { if (currentEditor == null) return; Point p = new Point(me.getX(), me.getY()); int colIndex = columnAtPoint(p); if (colIndex < 0) return; Point colPoint = (Point) currentEditor.getClientProperty(COLUMN_POINT); if (colPoint.x-1 == colIndex || colPoint.x == colIndex || colPoint.x+1 == colIndex) { Rectangle bounds = getCellRect(colPoint.y, colPoint.x, false); currentEditor.setBounds(bounds); currentEditor.requestFocus(); currentEditor.grabFocus(); } else { hideEditor(false); } } }); } protected void onopenItem() {} private void openItem() { // do not do anything if there is an active process running if (processingRequest) return; try { processingRequest = true; onopenItem(); } catch(Exception ex) { MsgBox.err(ex); } finally { processingRequest = false; } } protected void onprocessMouseEvent(MouseEvent me) {} protected void processMouseEvent(MouseEvent me) { // do not do anything if there is an active process running if (processingRequest) return; if (me.getID()==MouseEvent.MOUSE_CLICKED && me.getClickCount()==2) { Point p = new Point(me.getX(), me.getY()); int colIndex = columnAtPoint(p); Column dc = tableModel.getColumn(colIndex); if (dc != null && !dc.isEditable()) { me.consume(); openItem(); return; } } onprocessMouseEvent(me); if (me.isConsumed()) { //do nothing } else { super.processMouseEvent(me); } } public boolean editCellAt(int rowIndex, int colIndex, EventObject e) { if (isReadonly()) return false; Column oColumn = tableModel.getColumn(colIndex); if (oColumn == null) return false; //automatically this column turns editable if handler is SelectionColumnHandler if (oColumn.getTypeHandler() instanceof SelectionColumnHandler) { if (dataProvider.getListItemData(rowIndex) == null) return false; JComponent editor = editors.get(colIndex); if (editor != null) showEditor(editor, rowIndex, colIndex, e); return false; } if (editorModel == null) return false; if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent) e; if (me.getClickCount()==2 && SwingUtilities.isLeftMouseButton(me)) { //do nothing } else { return false; } } editItem(rowIndex, colIndex, e); return false; } public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) { // do not do anything if there is an active process running if (processingRequest) return; int oldColIndex = getSelectedColumn(); int oldRowIndex = getSelectedRow(); if (editingMode) { //Point point = (Point) currentEditor.getClientProperty(COLUMN_POINT); if (rowIndex != oldRowIndex || columnIndex != oldColIndex) { hideEditor(currentEditor, oldRowIndex, oldColIndex, true, true); } } if (rowIndex != oldRowIndex && editorModel != null && editingRow >= 0) { ListItem li = editorModel.getListItem(editingRow); if (li != null && (editorModel.isTemporaryItem(li) || li.getState()==ListItem.STATE_EDIT)) { try { if (!validateRow(editingRow)) { String errmsg = editorModel.getMessageSupport().getErrorMessage(editingRow); if (errmsg != null) throw new Exception(errmsg); //exit from this process return; } if (li.getState() == ListItem.STATE_DRAFT) editorModel.flushTemporaryItem(li); editorModel.fireCommitItem(li); itemBinding.getChangeLog().clear(); editingRow = -1; } catch(Exception ex) { tableModel.fireTableRowsUpdated(editingRow, editingRow); MsgBox.err(ex); return; } } } super.changeSelection(rowIndex, columnIndex, toggle, extend); putClientProperty("selectionPoint", new Point(columnIndex, rowIndex)); if (rowIndex != oldRowIndex) editingRow = -1; if (columnIndex != oldColIndex && dataProvider != null) { Column oColumn = tableModel.getColumn(columnIndex); dataProvider.setSelectedColumn((oColumn == null? null: oColumn.getName())); } if (rowIndex != oldRowIndex) rowSelectionChanged(rowIndex); } protected void processKeyEvent(KeyEvent e) { // do not do anything if there is an active process running if (processingRequest) return; if (currentEditor != null) return; currentKeyEvent = e; super.processKeyEvent(e); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" row movements/actions support "> public void tableChanged(TableModelEvent e) { if (getSelectedRow() >= getRowCount()) setRowSelectionInterval(0, 0); super.tableChanged(e); } protected void onrowChanged() {} private void rowSelectionChanged(int index) { dataProvider.setSelectedItem(index); editorBeanLoaded = false; rowCommited = true; previousItem = null; onrowChanged(); } protected void oncancelRowEdit() {} public final void cancelRowEdit() { if (!rowCommited) { ChangeLog log = itemBinding.getChangeLog(); List<ChangeLog.ChangeEntry> ceList = log.undoAll(); for (ChangeLog.ChangeEntry ce : ceList) { //dataProvider.setSelectedColumn(ce.getFieldName()); //dataProvider.updateSelectedItem(); } rowCommited = true; int row = getSelectedRow(); tableModel.fireTableRowsUpdated(row, row); oncancelRowEdit(); } } public void undo() { int row = getSelectedRow(); ChangeLog.ChangeEntry ce = itemBinding.getChangeLog().undo(); tableModel.fireTableRowsUpdated(row, row); //dataProvider.setSelectedColumn(ce.getFieldName()); //dataProvider.updateSelectedItem(); } public final void removeItem() { if (isReadonly()) return; if (editorModel == null) return; int rowIndex = getSelectedRow(); if (rowIndex < 0) return; //if the ListModel has error messages //allow editing only to the row that caused the error if (editorModel.getMessageSupport().hasErrorMessages() && editorModel.getMessageSupport().getErrorMessage(rowIndex) == null) return; try { editorModel.setSelectedItem(rowIndex); editorModel.fireRemoveItem(editorModel.getListItem(rowIndex)); } catch(Exception ex) { MsgBox.err(ex); } } public Object createExpressionBean(Object itemBean) { ExprBeanSupport beanSupport = new ExprBeanSupport(binding.getBean()); beanSupport.setItem(getVarName(), itemBean); return beanSupport.createProxy(); } protected void onchangedItem(ListItem item) {} public void editItem(int rowIndex, int colIndex, EventObject e) { if (editorModel == null) return; /* if ListItem has error messages, allow editing only to the row that caused the error */ if (dataProvider.getMessageSupport().hasErrorMessages() && dataProvider.getMessageSupport().getErrorMessage(getSelectedRow()) == null) return; ListItem oListItem = tableModel.getListItem(rowIndex); if (!editorModel.isAllowedForEditing(oListItem)) return; Column col = tableModel.getColumn(colIndex); if (col == null || !col.isEditable()) return; try { if (oListItem.getItem() == null || oListItem.getState() == ListItem.STATE_EMPTY) { editorModel.loadTemporaryItem(oListItem); oListItem.setRoot(binding.getBean()); tableModel.fireTableRowsUpdated(rowIndex, rowIndex); } } catch(Exception ex) { MsgBox.err(ex); return; } // evaluate the editableWhen expression if ( !ValueUtil.isEmpty(col.getEditableWhen()) ) { boolean passed = false; ExpressionResolver er = ExpressionResolver.getInstance(); try { Object exprBean = createExpressionBean(oListItem.getItem()); passed = UIControlUtil.evaluateExprBoolean(exprBean, col.getEditableWhen()); } catch(Exception ex) { System.out.println("Failed to evaluate expression " + col.getEditableWhen() + " caused by " + ex.getMessage()); } if (!passed) { if (dataProvider.getListItem(rowIndex+1) == null) { oListItem.loadItem(null, ListItem.STATE_EMPTY); tableModel.fireTableRowsUpdated(rowIndex, rowIndex); } return; } } JComponent editor = editors.get(colIndex); if ( editor == null ) return; if (editorModel.isLastItem(oListItem)) editorModel.addEmptyItem(); oListItem.setRoot(binding.getBean()); tableModel.fireTableRowsUpdated(rowIndex, rowIndex); try { onchangedItem(oListItem); } catch(Exception ex) { MsgBox.err(ex); } showEditor(editor, rowIndex, colIndex, e); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" helper/supporting methods "> protected void onfocusGained(FocusEvent e) {} protected void onfocusLost(FocusEvent e) {} protected final void processFocusEvent(FocusEvent e) { if (e.getID() == FocusEvent.FOCUS_GAINED) onfocusGained(e); else if (e.getID() == FocusEvent.FOCUS_LOST) onfocusLost(e); super.processFocusEvent(e); } private void log(String msg) { String name = getClass().getSimpleName(); System.out.println("["+name+"] " + msg); } private boolean isPrintableKey(EventObject e) { KeyEvent ke = null; if (e instanceof KeyEvent) ke = (KeyEvent) e; if (ke == null) ke = currentKeyEvent; if (ke == null) return false; if (ke.isActionKey() || ke.isControlDown() || ke.isAltDown()) return false; switch (ke.getKeyCode()) { case KeyEvent.VK_ESCAPE: case KeyEvent.VK_DELETE: case KeyEvent.VK_ENTER: return false; } return true; } private boolean isEditKey(EventObject e) { if (!(e instanceof KeyEvent)) return false; KeyEvent ke = (KeyEvent) e; switch (ke.getKeyCode()) { case KeyEvent.VK_F2: case KeyEvent.VK_INSERT: case KeyEvent.VK_BACK_SPACE: return true; } return false; } private void selectAll(JComponent editor, EventObject evt) { if (editor instanceof JTextComponent) { ((JTextComponent) editor).selectAll(); } else { if (editor instanceof UIInput) ((UIInput) editor).setRequestFocus(true); if (editor instanceof JCheckBox) ((UIInput) editor).setValue(evt); } } private void focusNextCellFrom(int rowIndex, int colIndex) { int nextCol = findNextEditableColFrom(colIndex); int firstEditable = findNextEditableColFrom(-1); if (nextCol >= 0) this.changeSelection(rowIndex, nextCol, false, false); else if (rowIndex+1 < tableModel.getRowCount()) this.changeSelection(rowIndex+1, firstEditable, false, false); else { ListItem item = dataProvider.getSelectedItem(); /* boolean lastRow = !(rowIndex + dataProvider.getTopRow() < dataProvider.getMaxRows()); if ( item.getState() == ListItem.STATE_EMPTY ) lastRow = false; if ( !lastRow ) { this.changeSelection(rowIndex, firstEditable, false, false); moveNextRecord(); } else { this.changeSelection(0, firstEditable, false, false); dataProvider.moveFirstPage(); }*/ } } private int findNextEditableColFrom(int colIndex) { for (int i=colIndex+1; i<tableModel.getColumnCount(); i++ ) { if (editors.get(i) != null) return i; } return -1; } private void hideEditor(boolean commit) { hideEditor(commit, true); } private void hideEditor(boolean commit, boolean grabFocus) { if ( !editingMode || currentEditor == null ) return; Point point = (Point) currentEditor.getClientProperty(COLUMN_POINT); hideEditor(currentEditor, point.y, point.x, commit, grabFocus); } private void hideEditor(JComponent editor, int rowIndex, int colIndex, boolean commit, boolean grabFocus) { if (editor instanceof SelectionCellEditor) commit = false; /* * force to invoke the setValue of the editor support when editor is instanceof JCheckBox * to make sure that the data has been sent to the temporary storage before committing. */ if (editor instanceof JCheckBox && editor instanceof UIInput) { UIInput uiinput = (UIInput) editor; uiinput.putClientProperty("cellEditorValue", uiinput.getValue()); } editor.setVisible(false); editor.setInputVerifier(null); editingMode = false; currentEditor = null; if (commit) { Object value = editor.getClientProperty("cellEditorValue"); tableModel.setBinding(itemBinding); tableModel.setValueAt(value, rowIndex, colIndex); try { if (editorModel != null) { ListItem oListItem = editorModel.getListItem(editingRow); editorModel.fireColumnUpdate(oListItem); } } catch(Exception ex) { MsgBox.alert(ex); } } tableModel.fireTableRowsUpdated(rowIndex, rowIndex); if (grabFocus) grabFocus(); } public void clearEditors() { if (currentEditor != null) { currentEditor.setVisible(false); currentEditor.setInputVerifier(null); } editingMode = false; currentEditor = null; } private boolean validateRow(int rowIndex) { //exit right away if no editor model specified if (editorModel == null) return true; ActionMessage ac = new ActionMessage(); itemBinding.validate(ac); if ( ac.hasMessages() ) dataProvider.getMessageSupport().addErrorMessage(rowIndex, ac.toString()); else dataProvider.getMessageSupport().removeErrorMessage(rowIndex); if ( ac.hasMessages() ) return false; try { editorModel.fireValidateItem( dataProvider.getListItem(rowIndex) ); dataProvider.getMessageSupport().removeErrorMessage(rowIndex); } catch (Exception e ) { if (ClientContext.getCurrentContext().isDebugMode()) e.printStackTrace(); String msg = getMessage(e)+""; dataProvider.getMessageSupport().addErrorMessage(rowIndex, msg); return false; } return true; } private String getMessage(Throwable t) { if (t == null) return null; String msg = t.getMessage(); Throwable cause = t.getCause(); while (cause != null) { String s = cause.getMessage(); if (s != null) msg = s; cause = cause.getCause(); } return msg; } private void showEditor(final JComponent editor, int rowIndex, int colIndex, EventObject e) { Rectangle bounds = getCellRect(rowIndex, colIndex, false); editor.putClientProperty(COLUMN_POINT, new Point(colIndex, rowIndex)); editor.putClientProperty("cellEditorValue", null); editor.setBounds(bounds); UIControl ui = (UIControl) editor; - boolean refreshed = false; + Object bean = dataProvider.getListItemData(rowIndex); + itemBinding.setBean(bean); + boolean refreshed = false; if ( !editorBeanLoaded ) { itemBinding.update(); //clear change log itemBinding.setRoot(binding); itemBinding.setTableModel(tableModel); itemBinding.setRowIndex(rowIndex); - itemBinding.setColumnIndex(colIndex); - - Object bean = dataProvider.getListItemData(rowIndex); - itemBinding.setBean(bean); + itemBinding.setColumnIndex(colIndex); itemBinding.refresh(); refreshed = true; editorBeanLoaded = true; } if (e == null) e = currentKeyEvent; editor.putClientProperty("updateBeanValue", false); editor.putClientProperty("allowSelectAll", false); if (e instanceof MouseEvent || isEditKey(e)) { if (!refreshed) ui.refresh(); + UIInput uiinput = (UIInput) editor; selectAll(editor, e); if (editor instanceof XCheckBox) { hideEditor(editor, rowIndex, colIndex, true, true); return; } } else if (isPrintableKey(e)) { char ch = currentKeyEvent.getKeyChar(); boolean dispatched = false; if (editor instanceof JTextComponent) { try { JTextComponent jtxt = (JTextComponent) editor; jtxt.setText(ch+""); dispatched = true; } catch (Throwable ex) {;} } if (!dispatched && (editor instanceof UIInput)) { UIInput uiinput = (UIInput) editor; uiinput.setValue((KeyEvent) e); if (editor instanceof XCheckBox) { hideEditor(editor, rowIndex, colIndex, true, true); return; } } } else { return; } if (editor instanceof ImmediateCellEditor) { //exit right away since this was tagged as immediate editorBeanLoaded = false; return; } oneditCellAt(rowIndex, colIndex); previousItem = dataProvider.getSelectedItem(); InputVerifier verifier = (InputVerifier) editor.getClientProperty(InputVerifier.class); if ( verifier == null ) { verifier = editor.getInputVerifier(); editor.putClientProperty(InputVerifier.class, verifier); } editor.setInputVerifier( verifier ); editor.setVisible(true); editor.grabFocus(); editingRow = rowIndex; editingMode = true; rowCommited = false; currentEditor = editor; } private boolean isValidKeyCode(int keyCode) { return (keyCode >= 32 && keyCode <= 126); } protected void oneditCellAt(int rowIndex, int colIndex) {} public AbstractListModel getListModel() { return null; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" EditorInputSupport (class) "> private class EditorInputSupport implements UIInputUtil.Support { public void setValue(String name, Object value) { setValue(name, value, null); } public void setValue(String name, Object value, JComponent jcomp) { //temporarily stores the editor value //the value is committed once the cell selection is about to changed if (currentEditor != null) { currentEditor.putClientProperty("cellEditorValue", value); } else if (jcomp != null) { jcomp.putClientProperty("cellEditorValue", value); } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" EditorFocusSupport (class) "> private class EditorFocusSupport implements FocusListener { private boolean fromTempFocus; public void focusGained(FocusEvent e) { if (fromTempFocus) { if (editingMode) { JComponent comp = (JComponent) e.getSource(); UIInput uiinput = (UIInput) comp.getClientProperty(UIInput.class); String ubv = null; if (uiinput != null) ubv = uiinput.getClientProperty("updateBeanValue")+""; else ubv = comp.getClientProperty("updateBeanValue")+""; if ("false".equals(ubv)) return; hideEditor(true); Point selPoint = null; if (uiinput != null) selPoint = (Point) uiinput.getClientProperty(COLUMN_POINT); if (selPoint == null) selPoint = (Point) comp.getClientProperty(COLUMN_POINT); try { focusNextCellFrom(selPoint.y, selPoint.x); } catch(Exception ex) {;} } fromTempFocus = false; } } public void focusLost(FocusEvent e) { fromTempFocus = e.isTemporary(); //if (!e.isTemporary()) hideEditor(true, false); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" EditorKeyBoardAction (class) "> private class EditorKeyBoardAction implements ActionListener { KeyStroke keyStroke; private boolean commit; private ActionListener[] listeners; EditorKeyBoardAction(JComponent comp, int key, boolean commit) { this.commit = commit; this.keyStroke = KeyStroke.getKeyStroke(key, 0); //hold only action on enter key //this is usually used by lookup if ( key == KeyEvent.VK_ENTER && comp instanceof JTextField ) { JTextField jtf = (JTextField) comp; listeners = jtf.getActionListeners(); } } public void actionPerformed(ActionEvent e) { if ( listeners != null && listeners.length > 0 ) { for ( ActionListener l: listeners) { l.actionPerformed(e); } } else { JComponent comp = (JComponent) e.getSource(); Point point = (Point) comp.getClientProperty(COLUMN_POINT); if (commit) focusNextCellFrom( point.y, point.x ); else { comp.firePropertyChange("enableInputVerifier", true, false); hideEditor(comp, point.y, point.x, false, true); } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" TableKeyAdapter (class) "> private class TableKeyAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { // do not do anything if there is an active process running if (processingRequest) return; switch (e.getKeyCode()) { case KeyEvent.VK_DOWN: if (dataProvider.isLastItem(getSelectedRow())) { e.consume(); dataProvider.moveNextRecord(); } break; case KeyEvent.VK_UP: if (dataProvider.isFirstItem(getSelectedRow())) { e.consume(); dataProvider.moveBackRecord(); } break; case KeyEvent.VK_HOME: if (pageModel != null && e.isControlDown()) { e.consume(); pageModel.moveFirstPage(); } break; case KeyEvent.VK_PAGE_DOWN: if (pageModel != null) { e.consume(); pageModel.moveNextPage(); } break; case KeyEvent.VK_PAGE_UP: if (pageModel != null) { e.consume(); pageModel.moveBackPage(); } break; case KeyEvent.VK_DELETE: removeItem(); EventQueue.invokeLater(new Runnable() { public void run() { requestFocusInWindow(); grabFocus(); } }); break; case KeyEvent.VK_ENTER: if (e.isControlDown()) openItem(); break; case KeyEvent.VK_ESCAPE: cancelRowEdit(); break; } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" TableEnterAction (class) "> private class TableEnterAction implements ActionListener { private JComponent component; private ActionListener oldAction; void install(JComponent component) { this.component = component; KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false); oldAction = component.getActionForKeyStroke(ks); component.registerKeyboardAction(this, ks, JComponent.WHEN_FOCUSED); } public void actionPerformed(ActionEvent e) { if ( !isReadonly() && editors.size() > 0 ) { JTable tbl = DataTableComponent.this; int row = tbl.getSelectedRow(); int col = tbl.getSelectedColumn(); focusNextCellFrom(row, col); } else { JRootPane rp = component.getRootPane(); if (rp != null && rp.getDefaultButton() != null ) { JButton btn = rp.getDefaultButton(); btn.doClick(); } else if (oldAction != null) { oldAction.actionPerformed(e); } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" TableEscapeAction (class) "> private class TableEscapeAction implements ActionListener { private ActionListener oldAction; void install(JComponent comp) { KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false); oldAction = comp.getActionForKeyStroke(ks); comp.registerKeyboardAction(this, ks, JComponent.WHEN_FOCUSED); } public void actionPerformed(ActionEvent e) { if (editorModel != null) { fireAction(); return; } ActionListener actionL = (ActionListener) getRootPane().getClientProperty("Window.closeAction"); if (actionL != null) actionL.actionPerformed(e); else if (oldAction != null) oldAction.actionPerformed(e); } private void fireAction() { int rowIndex = getSelectedRow(); ListItem li = editorModel.getListItem(rowIndex); if (li == null) return; if (editorModel.isTemporaryItem(li)) { editorModel.getMessageSupport().removeErrorMessage(li.getIndex()); editorModel.removeTemporaryItem(li); Point sel = (Point) getClientProperty("selectionPoint"); if (sel == null) sel = new Point(0, 0); changeSelection(rowIndex, sel.x, false, false); } else if (li.getState() == ListItem.STATE_EDIT && editorModel.getMessageSupport().hasErrorMessages()) { editorModel.getMessageSupport().removeErrorMessage(li.getIndex()); li.setState(ListItem.STATE_SYNC); tableModel.fireTableRowsUpdated(rowIndex, rowIndex); } else { tableModel.fireTableRowsUpdated(rowIndex, rowIndex); } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" PropertyChangeHandlerImpl (class) "> private class PropertyChangeHandlerImpl implements PropertyChangeHandler { DataTableComponent root = DataTableComponent.this; public void firePropertyChange(String name, int value) { } public void firePropertyChange(String name, boolean value) { if ("loading".equals(name)) { root.fetching = value; root.repaint(); } } public void firePropertyChange(String name, String value) { } public void firePropertyChange(String name, Object value) { if ("focusSelectedItem".equals(name)) focusSelectedItem(); } void focusSelectedItem() { Point loc = (Point) getClientProperty("selectionPoint"); if (loc == null) loc = new Point(); ListItem li = root.dataProvider.getSelectedItem(); int rowIndex = (li == null? 0: li.getIndex()); if (!root.dataProvider.validRange(rowIndex)) rowIndex = 0; root.tableModel.fireTableRowsUpdated(rowIndex, rowIndex); root.setRowSelectionInterval(rowIndex, rowIndex); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" TableModelHandlerImpl (class) "> private class TableModelHandlerImpl implements TableModelHandler { DataTableComponent root = DataTableComponent.this; public void fireTableCellUpdated(int row, int column) {} public void fireTableRowsDeleted(int firstRow, int lastRow) {} public void fireTableRowsInserted(int firstRow, int lastRow) {} public void fireTableRowsUpdated(int firstRow, int lastRow) {} public void fireTableStructureChanged() { root.clearEditors(); } public void fireTableDataChanged() { root.clearEditors(); } public void fireTableRowSelected(int row, boolean focusOnItemDataOnly) { Point sel = (Point) root.getClientProperty("selectionPoint"); if (sel == null) sel = new Point(); ListItem li = root.dataProvider.getListItem(row); if (li == null) root.getSelectionModel().setSelectionInterval(0, 0); else { int preferredRow = 0; int itemCount = root.dataProvider.getListItemCount(); for (int i=row; i>=0; i--) { if (focusOnItemDataOnly) { //select the ListItem whose item bean is not null if (root.dataProvider.getListItemData(i) != null) { preferredRow = i; break; } } else if (i < itemCount) { //retain the focus index as long the range index is still valid preferredRow = i; break; } } root.getSelectionModel().setSelectionInterval(preferredRow, preferredRow); onrowChanged(); } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" PopupMenu Support "> private class PopupMenuAdapter extends MouseAdapter { DataTableComponent root = DataTableComponent.this; private JPopupMenu popup; public void mouseClicked(MouseEvent e) { if (!SwingUtilities.isRightMouseButton(e)) return; if (root.getDataProvider() == null) return; int rowIndex = root.rowAtPoint(e.getPoint()); DataTableModel dtm = root.getDataTableModel(); ListItem li = dtm.getListItem(rowIndex); if (li == null) return; int colIndex = root.columnAtPoint(e.getPoint()); if (colIndex < 0) colIndex = root.getSelectedColumn(); root.changeSelection(rowIndex, colIndex, false, false); if (popup == null) popup = new JPopupMenu(); else popup.setVisible(false); PopupMenuRunnable pmr = new PopupMenuRunnable(); pmr.popup = popup; pmr.dtm = dtm; pmr.li = li; pmr.e = e; pmr.rowIndex = rowIndex; pmr.colIndex = colIndex; EventQueue.invokeLater(pmr); } } private class PopupMenuRunnable implements Runnable { DataTableComponent root = DataTableComponent.this; private JPopupMenu popup; private DataTableModel dtm; private ListItem li; private MouseEvent e; private int rowIndex; private int colIndex; private String colName; public void run() { try { runImpl(); } catch(Exception ex) { MsgBox.err(ex); } } private void runImpl() { if (li.getItem() == null) return; Column oColumn = dtm.getColumn(colIndex); colName = (oColumn == null? null: oColumn.getName()); List<Map> menuItems = root.getDataProvider().getContextMenu(li.getItem(), colName); if (menuItems == null || menuItems.isEmpty()) return; Object items = popup.getClientProperty("ContextMenu.items"); if (items == null || (items != null && !items.equals(menuItems))) { popup.removeAll(); for (Map data: menuItems) { String value = getString(data, "value"); if ("-".equals(value+"")) { popup.addSeparator(); continue; } ActionMenuItem jmi = new ActionMenuItem(data, li); Dimension dim = jmi.getPreferredSize(); jmi.setPreferredSize(new Dimension(Math.max(dim.width, 100), dim.height)); popup.add(jmi); } popup.putClientProperty("ContextMenu.items", menuItems); } Component[] comps = popup.getComponents(); for (int i=0; i<comps.length; i++) { if (!(comps[i] instanceof ActionMenuItem)) continue; ActionMenuItem ami = (ActionMenuItem) comps[i]; ami.listItem = li; ami.refresh(); } popup.pack(); popup.show(e.getComponent(), e.getX(), e.getY()); } private String getString(Map data, String name) { Object o = data.get(name); return (o == null? null: o.toString()); } } private class ActionMenuItem extends JMenuItem { DataTableComponent root = DataTableComponent.this; private Map data; private ListItem listItem; ActionMenuItem(Map data, ListItem listItem) { this.data = (data == null? new HashMap(): data); this.listItem = listItem; setText(this.data.get("value")+""); addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { invokeAction(e); } }); if (this.data.get("action") instanceof Action) { Action a = (Action) this.data.get("action"); Map newData = a.toMap(); newData.putAll(this.data); this.data = newData; } } Map getData() { return data; } void invokeAction(ActionEvent e) { try { Object item = listItem == null? null: listItem.getItem(); Object result = root.getDataProvider().callContextMenu(item, getData()); if (result == null) return; if (result instanceof Action) { Action a = (Action) result; UICommandUtil.processAction(root, root.getBinding(), a); } else { root.getBinding().fireNavigation(result); } } catch(Exception ex) { MsgBox.err(ex); } } void refresh() { try { boolean enabled = !"false".equals(this.data.get("enabled")+""); setEnabled(enabled); Object item = listItem == null? null: listItem.getItem(); if (item == null) return; ExpressionResolver resolver = ExpressionResolver.getInstance(); synchronized (resolver) { Object exprBean = root.createExpressionBean(item); if (this.data.containsKey("disabledWhen")) { String expr = this.data.get("disabledWhen").toString(); setEnabled(!evalBoolean(resolver, exprBean, expr)); } if (this.data.containsKey("visibleWhen")) { String expr = this.data.get("visibleWhen").toString(); setVisible(evalBoolean(resolver, exprBean, expr)); } } } catch(Throwable ex) {;} } boolean evalBoolean(ExpressionResolver resolver, Object exprBean, String expr) { try { return resolver.evalBoolean(expr, exprBean); } catch(Throwable ex) { return false; } } } // </editor-fold> }
false
false
null
null
diff --git a/build/src/com/android/exchange/Configuration.java b/build/src/com/android/exchange/Configuration.java index 840bcf78..ad93cb2b 100644 --- a/build/src/com/android/exchange/Configuration.java +++ b/build/src/com/android/exchange/Configuration.java @@ -1,25 +1,25 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange; public class Configuration { public static final String EXCHANGE_ACCOUNT_MANAGER_TYPE = "com.android.exchange"; public static final String EXCHANGE_SERVICE_INTENT_ACTION = "com.android.email.EXCHANGE_INTENT"; - public static final String EXCHANGE_GAL_AUTHORITY = "com.android.exchange.provider"; + public static final String EXCHANGE_GAL_AUTHORITY = "com.android.exchange.directory.provider"; public static final String EXCHANGE_PROTOCOL = "eas"; }
true
false
null
null
diff --git a/src/main/java/uk/co/o2/customer/CustomerResource.java b/src/main/java/uk/co/o2/customer/CustomerResource.java index 2f7fa72..67e0fcd 100644 --- a/src/main/java/uk/co/o2/customer/CustomerResource.java +++ b/src/main/java/uk/co/o2/customer/CustomerResource.java @@ -1,107 +1,107 @@ package uk.co.o2.customer; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiError; import com.wordnik.swagger.annotations.ApiErrors; import com.wordnik.swagger.annotations.ApiOperation; import uk.co.o2.vo.Customer; @Path("/customers") @Api(value = "/customers", description = "Manage customer details") @Produces({MediaType.APPLICATION_JSON}) public class CustomerResource { @GET - @Path("/customers") + @Path("/") @ApiOperation(value = "Returns list of all available customer details", notes = "Returns all the customer details", responseClass = "uk.co.o2.vo.Customer" , multiValueResponse = true) @ApiErrors(value = { @ApiError(code = 404, reason = "Customers not found") }) @Produces({MediaType.APPLICATION_JSON}) public List<Customer> customer() { return getCustomerDetails(); } @GET @Path("/{customerID}") @ApiOperation(value = "Get customer details by customer id", notes = "Returns customer details for the given customer id", responseClass = "uk.co.o2.vo.Customer") @ApiErrors(value = { @ApiError(code = 400, reason = "Customer ID invalid"), @ApiError(code = 404, reason = "Customer not found") }) @Produces({MediaType.APPLICATION_JSON}) public Customer customer(@PathParam("customerID") int customerID) { return getCustomerDetail(customerID); } /** * Returns customer VO * @param custId - The customer id for which customer details is required * @return Customer - The customer VO */ private Customer getCustomerDetail(int custId) { Customer customer = new Customer(); customer.setCustomerId(custId); customer.setCustomerType("PREPAY"); customer.setFirstName("John"); customer.setLastName("Peter"); customer.setMSISDN(448822903848l); customer.setTitle("Mr"); return customer; } /** * Returns lsit of customer VO * @return List<Customer> - The list of customer VO */ private List<Customer> getCustomerDetails() { ArrayList<Customer> lst = new ArrayList<Customer>(); Customer customer = new Customer(); customer.setCustomerId(1); customer.setCustomerType("PREPAY"); customer.setFirstName("John"); customer.setLastName("Peter"); customer.setMSISDN(448822903848l); customer.setTitle("Mr"); Customer customer1 = new Customer(); customer1.setCustomerId(2); customer1.setCustomerType("PREPAY"); customer1.setFirstName("Daniel"); customer1.setLastName("Peter"); customer1.setMSISDN(448822913887l); customer1.setTitle("Mr"); Customer customer2 = new Customer(); customer2.setCustomerId(3); customer2.setCustomerType("PREPAY"); customer2.setFirstName("Mark"); customer2.setLastName("Pattinson"); customer2.setMSISDN(4488229131123l); customer2.setTitle("Mr"); lst.add(customer); lst.add(customer1); lst.add(customer2); return lst; } } diff --git a/src/main/java/uk/co/o2/util/ApiOriginFilter.java b/src/main/java/uk/co/o2/util/ApiOriginFilter.java new file mode 100644 index 0000000..7090fc1 --- /dev/null +++ b/src/main/java/uk/co/o2/util/ApiOriginFilter.java @@ -0,0 +1,27 @@ +package uk.co.o2.util; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; + +public class ApiOriginFilter implements javax.servlet.Filter { + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() { + } + + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file
false
false
null
null
diff --git a/src/com/globalsight/tools/CreateJobCommand.java b/src/com/globalsight/tools/CreateJobCommand.java index 648d527..fa0fb44 100755 --- a/src/com/globalsight/tools/CreateJobCommand.java +++ b/src/com/globalsight/tools/CreateJobCommand.java @@ -1,192 +1,190 @@ package com.globalsight.tools; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; /** * Create a job. By default, use all the target locales * indicated by the file profile (selected by name or id). * Generate a job name based on the name of the first file uploaded, * unless one is specified on the command line. */ @SuppressWarnings("static-access") -// XXX Wow, there is problem with webservices, the absolute file path isn't stripping -// the '../..' out? // TODO: I should assume the fileprofile target locale by default, but allow overrides // via --target public class CreateJobCommand extends WebServiceCommand { @Override protected void execute(CommandLine command, UserData userData, WebService webService) throws Exception { // Make sure we have at least one file to upload if (command.getArgs().length == 0) { die("Must specify at least one file to import."); } if (command.hasOption(FILEPROFILE) && command.hasOption(FILEPROFILEID)) { usage("Can't specify both " + FILEPROFILE + " and " + FILEPROFILEID + " options."); } if (!(command.hasOption(FILEPROFILE) || command.hasOption(FILEPROFILEID))) { usage("Must specify either " + FILEPROFILE + " or " + FILEPROFILEID + " option."); } FileProfile fp = null; if (command.hasOption(FILEPROFILE)) { String fpName = command.getOptionValue(FILEPROFILE); fp = findByName(webService.getFileProfiles(), fpName); if (fp == null) { die("No such file profile: '" + fpName + "'"); } } else { String fpId = command.getOptionValue(FILEPROFILEID); fp = findById(webService.getFileProfiles(), fpId); if (fp == null) { die("No such file profile id: '" + fpId + "'"); } } // TODO target locale overrides // Convert all remaining arguments to files List<File> files = new ArrayList<File>(); for (String path : command.getArgs()) { File f = new File(path); if (!f.exists() || f.isDirectory()) { die("Not a file: " + f); } - files.add(f); + files.add(f.getCanonicalFile()); } // Get a job name either from command line or first file // uploaded, then uniquify String baseJobName = files.get(0).getName(); if (command.hasOption(JOBNAME)) { command.getOptionValue(JOBNAME); } String jobName = webService.getUniqueJobName(baseJobName); verbose("Got unique job name: " + jobName); List<String> filePaths = new ArrayList<String>(); for (File f : files) { filePaths.add(uploadFile(f, jobName, fp, webService)); } webService.createJob(jobName, filePaths, fp); } FileProfile findByName(List<FileProfile> fileProfiles, String name) { for (FileProfile fp : fileProfiles) { if (fp.getName().equalsIgnoreCase(name)) { return fp; } } return null; } FileProfile findById(List<FileProfile> fileProfiles, String id) { for (FileProfile fp : fileProfiles) { if (fp.getId().equals(id)) { return fp; } } return null; } private static long MAX_SEND_SIZE = 5 * 1000 * 1024; // 5M // Returns the filepath that was sent to the server String uploadFile(File file, String jobName, FileProfile fileProfile, WebService webService) throws Exception { String filePath = file.getAbsolutePath(); // XXX This is so janky - why do we have to do this? filePath = filePath.substring(filePath.indexOf(File.separator) + 1); verbose("Uploading " + filePath + " to job " + jobName); InputStream is = null; try { long bytesRemaining = file.length(); is = new BufferedInputStream(new FileInputStream(file)); while (bytesRemaining > 0) { // Safe cast because it's bounded by MAX_SEND_SIZE int size = (int)Math.min(bytesRemaining, MAX_SEND_SIZE); byte[] bytes = new byte[size]; int count = is.read(bytes); if (count <= 0) { break; } bytesRemaining -= count; verbose("Uploading chunk 1: " + size + " bytes"); webService.uploadFile(filePath, jobName, fileProfile.getId(), bytes); } verbose("Finished uploading " + filePath); } catch (IOException e) { throw new RuntimeException(e); } finally { if (is != null) { is.close(); } } return filePath; } static final String TARGET = "target", FILEPROFILE = "fileprofile", FILEPROFILEID = "fileprofileid", JOBNAME = "name"; static final Option TARGET_OPT = OptionBuilder .withArgName("targetLocale") .hasArg() .withDescription("target locale code") .create(TARGET); static final Option FILEPROFILE_OPT = OptionBuilder .withArgName("fileProfile") .hasArg() .withDescription("file profile to use") .create(FILEPROFILE); static final Option FILEPROFILEID_OPT = OptionBuilder .withArgName("fileProfileId") .hasArg() .withDescription("numeric ID file profile to use") .create(FILEPROFILEID); static final Option JOBNAME_OPT = OptionBuilder .withArgName("jobName") .hasArg() .withDescription("job name") .create(JOBNAME); @Override public Options getOptions() { Options opts = getDefaultOptions(); opts.addOption(TARGET_OPT); opts.addOption(FILEPROFILE_OPT); opts.addOption(FILEPROFILEID_OPT); opts.addOption(JOBNAME_OPT); return opts; } @Override public String getDescription() { // TODO Auto-generated method stub return null; } @Override public String getName() { return "create-job"; } }
false
false
null
null
diff --git a/dspace/src/org/dspace/content/InstallItem.java b/dspace/src/org/dspace/content/InstallItem.java index b1b62c5dd..07842a1b8 100644 --- a/dspace/src/org/dspace/content/InstallItem.java +++ b/dspace/src/org/dspace/content/InstallItem.java @@ -1,178 +1,178 @@ /* * InstallItem.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2001, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.content; import java.io.IOException; import java.sql.SQLException; import java.util.List; import org.dspace.browse.Browse; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.core.Context; import org.dspace.core.Constants; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; import org.dspace.search.DSIndexer; import org.dspace.storage.rdbms.TableRowIterator; import org.dspace.storage.rdbms.DatabaseManager; /** * Support to install item in the archive * * @author dstuve * @version $Revision$ */ public class InstallItem { public static Item installItem(Context c, InProgressSubmission is) throws SQLException, IOException, AuthorizeException { return installItem(c, is, c.getCurrentUser()); } public static Item installItem(Context c, InProgressSubmission is, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if(currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // create handle String handle = HandleManager.createHandle(c, item); String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value - item.addDC("identifier", "uri", null, handle); + item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i].getSize())); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // create date.available // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexItem(c, item); // item.update() above adds item to browse indices //Browse.itemChanged(c, item); // remove in-progress submission is.deleteWrapper(); // remove the submit authorization policies // and replace them with the collection's READ // policies // FIXME: this is an inelegant hack, but out of time! List policies = AuthorizeManager.getPoliciesActionFilter(c, is.getCollection(), Constants.READ ); item.replaceAllPolicies(policies); return item; } /** generate provenance-worthy description of the bitstreams * contained in an item */ public static String getBitstreamProvenanceMessage(Item myitem) { // Get non-internal format bitstreams Bitstream[] bitstreams = myitem.getNonInternalBitstreams(); // Create provenance description String mymessage = "No. of bitstreams: " + bitstreams.length + "\n"; // Add sizes and checksums of bitstreams for (int j = 0; j < bitstreams.length; j++) { mymessage = mymessage + bitstreams[j].getName() + ": " + bitstreams[j].getSize() + " bytes, checksum: " + bitstreams[j].getChecksum() + " (" + bitstreams[j].getChecksumAlgorithm() + ")\n"; } return mymessage; } }
true
true
public static Item installItem(Context c, InProgressSubmission is, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if(currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // create handle String handle = HandleManager.createHandle(c, item); String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handle); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i].getSize())); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // create date.available // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexItem(c, item); // item.update() above adds item to browse indices //Browse.itemChanged(c, item); // remove in-progress submission is.deleteWrapper(); // remove the submit authorization policies // and replace them with the collection's READ // policies // FIXME: this is an inelegant hack, but out of time! List policies = AuthorizeManager.getPoliciesActionFilter(c, is.getCollection(), Constants.READ ); item.replaceAllPolicies(policies); return item; }
public static Item installItem(Context c, InProgressSubmission is, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if(currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // create handle String handle = HandleManager.createHandle(c, item); String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i].getSize())); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // create date.available // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexItem(c, item); // item.update() above adds item to browse indices //Browse.itemChanged(c, item); // remove in-progress submission is.deleteWrapper(); // remove the submit authorization policies // and replace them with the collection's READ // policies // FIXME: this is an inelegant hack, but out of time! List policies = AuthorizeManager.getPoliciesActionFilter(c, is.getCollection(), Constants.READ ); item.replaceAllPolicies(policies); return item; }
diff --git a/closure/closure-compiler/src/com/google/javascript/rhino/jstype/FunctionType.java b/closure/closure-compiler/src/com/google/javascript/rhino/jstype/FunctionType.java index 51c5549de..c5b73b7c8 100644 --- a/closure/closure-compiler/src/com/google/javascript/rhino/jstype/FunctionType.java +++ b/closure/closure-compiler/src/com/google/javascript/rhino/jstype/FunctionType.java @@ -1,1162 +1,1165 @@ /* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Bob Jervis * Google Inc. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Collections; import java.util.List; import java.util.Set; /** * This derived type provides extended information about a function, including * its return type and argument types.<p> * * Note: the parameters list is the LP node that is the parent of the * actual NAME node containing the parsed argument list (annotated with * JSDOC_TYPE_PROP's for the compile-time type of each argument. */ public class FunctionType extends PrototypeObjectType { private static final long serialVersionUID = 1L; private enum Kind { ORDINARY, CONSTRUCTOR, INTERFACE } /** * {@code [[Call]]} property. */ private ArrowType call; /** * The {@code prototype} property. This field is lazily initialized by * {@code #getPrototype()}. The most important reason for lazily * initializing this field is that there are cycles in the native types * graph, so some prototypes must temporarily be {@code null} during * the construction of the graph. * * If non-null, the type must be a PrototypeObjectType. */ private Property prototypeSlot; /** * Whether a function is a constructor, an interface, or just an ordinary * function. */ private final Kind kind; /** * The type of {@code this} in the scope of this function. */ private ObjectType typeOfThis; /** * The function node which this type represents. It may be {@code null}. */ private Node source; /** * The interfaces directly implemented by this function (for constructors) * It is only relevant for constructors. May not be {@code null}. */ private List<ObjectType> implementedInterfaces = ImmutableList.of(); /** * The interfaces directly extendeded by this function (for interfaces) * It is only relevant for constructors. May not be {@code null}. */ private List<ObjectType> extendedInterfaces = ImmutableList.of(); /** * The types which are subtypes of this function. It is only relevant for * constructors and may be {@code null}. */ private List<FunctionType> subTypes; /** * The template type name. May be {@code null}. */ private String templateTypeName; /** Creates an instance for a function that might be a constructor. */ FunctionType(JSTypeRegistry registry, String name, Node source, ArrowType arrowType, ObjectType typeOfThis, String templateTypeName, boolean isConstructor, boolean nativeType) { super(registry, name, registry.getNativeObjectType(JSTypeNative.FUNCTION_INSTANCE_TYPE), nativeType); setPrettyPrint(true); Preconditions.checkArgument(source == null || Token.FUNCTION == source.getType()); Preconditions.checkNotNull(arrowType); this.source = source; this.kind = isConstructor ? Kind.CONSTRUCTOR : Kind.ORDINARY; if (isConstructor) { this.typeOfThis = typeOfThis != null ? typeOfThis : new InstanceObjectType(registry, this, nativeType); } else { this.typeOfThis = typeOfThis != null ? typeOfThis : registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE); } this.call = arrowType; this.templateTypeName = templateTypeName; } /** Creates an instance for a function that is an interface. */ private FunctionType(JSTypeRegistry registry, String name, Node source) { super(registry, name, registry.getNativeObjectType(JSTypeNative.FUNCTION_INSTANCE_TYPE)); setPrettyPrint(true); Preconditions.checkArgument(source == null || Token.FUNCTION == source.getType()); Preconditions.checkArgument(name != null); this.source = source; this.call = new ArrowType(registry, new Node(Token.PARAM_LIST), null); this.kind = Kind.INTERFACE; this.typeOfThis = new InstanceObjectType(registry, this); } /** Creates an instance for a function that is an interface. */ static FunctionType forInterface( JSTypeRegistry registry, String name, Node source) { return new FunctionType(registry, name, source); } @Override public boolean isInstanceType() { // The universal constructor is its own instance, bizarrely. return isEquivalentTo(registry.getNativeType(U2U_CONSTRUCTOR_TYPE)); } @Override public boolean isConstructor() { return kind == Kind.CONSTRUCTOR; } @Override public boolean isInterface() { return kind == Kind.INTERFACE; } @Override public boolean isOrdinaryFunction() { return kind == Kind.ORDINARY; } @Override public FunctionType toMaybeFunctionType() { return this; } @Override public boolean canBeCalled() { return true; } public boolean hasImplementedInterfaces() { if (!implementedInterfaces.isEmpty()){ return true; } FunctionType superCtor = isConstructor() ? getSuperClassConstructor() : null; if (superCtor != null) { return superCtor.hasImplementedInterfaces(); } return false; } public Iterable<Node> getParameters() { Node n = getParametersNode(); if (n != null) { return n.children(); } else { return Collections.emptySet(); } } /** Gets an LP node that contains all params. May be null. */ public Node getParametersNode() { return call.parameters; } /** Gets the minimum number of arguments that this function requires. */ public int getMinArguments() { // NOTE(nicksantos): There are some native functions that have optional // parameters before required parameters. This algorithm finds the position // of the last required parameter. int i = 0; int min = 0; for (Node n : getParameters()) { i++; if (!n.isOptionalArg() && !n.isVarArgs()) { min = i; } } return min; } /** * Gets the maximum number of arguments that this function requires, * or Integer.MAX_VALUE if this is a variable argument function. */ public int getMaxArguments() { Node params = getParametersNode(); if (params != null) { Node lastParam = params.getLastChild(); if (lastParam == null || !lastParam.isVarArgs()) { return params.getChildCount(); } } return Integer.MAX_VALUE; } public JSType getReturnType() { return call.returnType; } public boolean isReturnTypeInferred() { return call.returnTypeInferred; } /** Gets the internal arrow type. For use by subclasses only. */ ArrowType getInternalArrowType() { return call; } @Override public Property getSlot(String name) { if ("prototype".equals(name)) { // Lazy initialization of the prototype field. getPrototype(); return prototypeSlot; } else { return super.getSlot(name); } } /** * Includes the prototype iff someone has created it. We do not want * to expose the prototype for ordinary functions. */ @Override public Set<String> getOwnPropertyNames() { if (prototypeSlot == null) { return super.getOwnPropertyNames(); } else { Set<String> names = Sets.newHashSet("prototype"); names.addAll(super.getOwnPropertyNames()); return names; } } /** * Gets the {@code prototype} property of this function type. This is * equivalent to {@code (ObjectType) getPropertyType("prototype")}. */ public ObjectType getPrototype() { // lazy initialization of the prototype field if (prototypeSlot == null) { setPrototype( new PrototypeObjectType( registry, this.getReferenceName() + ".prototype", registry.getNativeObjectType(OBJECT_TYPE), isNativeObjectType()), null); } return (ObjectType) prototypeSlot.getType(); } /** * Sets the prototype, creating the prototype object from the given * base type. * @param baseType The base type. */ public void setPrototypeBasedOn(ObjectType baseType) { setPrototypeBasedOn(baseType, null); } void setPrototypeBasedOn(ObjectType baseType, Node propertyNode) { // This is a bit weird. We need to successfully handle these // two cases: // Foo.prototype = new Bar(); // and // Foo.prototype = {baz: 3}; // In the first case, we do not want new properties to get // added to Bar. In the second case, we do want new properties // to get added to the type of the anonymous object. // // We handle this by breaking it into two cases: // // In the first case, we create a new PrototypeObjectType and set // its implicit prototype to the type being assigned. This ensures // that Bar will not get any properties of Foo.prototype, but properties // later assigned to Bar will get inherited properly. // // In the second case, we just use the anonymous object as the prototype. if (baseType.hasReferenceName() || isNativeObjectType() || baseType.isFunctionPrototypeType() || !(baseType instanceof PrototypeObjectType)) { baseType = new PrototypeObjectType( registry, this.getReferenceName() + ".prototype", baseType); } setPrototype((PrototypeObjectType) baseType, propertyNode); } /** * Sets the prototype. * @param prototype the prototype. If this value is {@code null} it will * silently be discarded. */ boolean setPrototype(PrototypeObjectType prototype, Node propertyNode) { if (prototype == null) { return false; } // getInstanceType fails if the function is not a constructor if (isConstructor() && prototype == getInstanceType()) { return false; } PrototypeObjectType oldPrototype = prototypeSlot == null ? null : (PrototypeObjectType) prototypeSlot.getType(); boolean replacedPrototype = oldPrototype != null; this.prototypeSlot = new Property("prototype", prototype, true, propertyNode == null ? source : propertyNode); prototype.setOwnerFunction(this); if (oldPrototype != null) { // Disassociating the old prototype makes this easier to debug-- // we don't have to worry about two prototypes running around. oldPrototype.setOwnerFunction(null); } if (isConstructor() || isInterface()) { FunctionType superClass = getSuperClassConstructor(); if (superClass != null) { superClass.addSubType(this); } if (isInterface()) { for (ObjectType interfaceType : getExtendedInterfaces()) { if (interfaceType.getConstructor() != null) { interfaceType.getConstructor().addSubType(this); } } } } if (replacedPrototype) { clearCachedValues(); } return true; } /** * Returns all interfaces implemented by a class or its superclass and any * superclasses for any of those interfaces. If this is called before all * types are resolved, it may return an incomplete set. */ public Iterable<ObjectType> getAllImplementedInterfaces() { // Store them in a linked hash set, so that the compile job is // deterministic. Set<ObjectType> interfaces = Sets.newLinkedHashSet(); for (ObjectType type : getImplementedInterfaces()) { addRelatedInterfaces(type, interfaces); } return interfaces; } private void addRelatedInterfaces(ObjectType instance, Set<ObjectType> set) { FunctionType constructor = instance.getConstructor(); if (constructor != null) { if (!constructor.isInterface()) { return; } set.add(instance); for (ObjectType interfaceType : instance.getCtorExtendedInterfaces()) { addRelatedInterfaces(interfaceType, set); } } } /** Returns interfaces implemented directly by a class or its superclass. */ public Iterable<ObjectType> getImplementedInterfaces() { FunctionType superCtor = isConstructor() ? getSuperClassConstructor() : null; if (superCtor == null) { return implementedInterfaces; } else { return Iterables.concat( implementedInterfaces, superCtor.getImplementedInterfaces()); } } /** Returns interfaces directly implemented by the class. */ public Iterable<ObjectType> getOwnImplementedInterfaces() { return implementedInterfaces; } public void setImplementedInterfaces(List<ObjectType> implementedInterfaces) { // Records this type for each implemented interface. for (ObjectType type : implementedInterfaces) { registry.registerTypeImplementingInterface(this, type); } this.implementedInterfaces = ImmutableList.copyOf(implementedInterfaces); } /** * Returns all extended interfaces declared by an interfaces or its super- * interfaces. If this is called before all types are resolved, it may return * an incomplete set. */ public Iterable<ObjectType> getAllExtendedInterfaces() { // Store them in a linked hash set, so that the compile job is // deterministic. Set<ObjectType> extendedInterfaces = Sets.newLinkedHashSet(); for (ObjectType interfaceType : getExtendedInterfaces()) { addRelatedExtendedInterfaces(interfaceType, extendedInterfaces); } return extendedInterfaces; } private void addRelatedExtendedInterfaces(ObjectType instance, Set<ObjectType> set) { FunctionType constructor = instance.getConstructor(); if (constructor != null) { set.add(instance); for (ObjectType interfaceType : constructor.getExtendedInterfaces()) { addRelatedExtendedInterfaces(interfaceType, set); } } } /** Returns interfaces directly extended by an interface */ public Iterable<ObjectType> getExtendedInterfaces() { return extendedInterfaces; } /** Returns the number of interfaces directly extended by an interface */ public int getExtendedInterfacesCount() { return extendedInterfaces.size(); } public void setExtendedInterfaces(List<ObjectType> extendedInterfaces) throws UnsupportedOperationException { if (isInterface()) { this.extendedInterfaces = ImmutableList.copyOf(extendedInterfaces); } else { throw new UnsupportedOperationException(); } } @Override public JSType getPropertyType(String name) { if (!hasOwnProperty(name)) { // Define the "call", "apply", and "bind" functions lazily. boolean isCall = "call".equals(name); boolean isBind = "bind".equals(name); if (isCall || isBind) { defineDeclaredProperty(name, getCallOrBindSignature(isCall), source); } else if ("apply".equals(name)) { // Define the "apply" function lazily. FunctionParamBuilder builder = new FunctionParamBuilder(registry); // Ecma-262 says that apply's second argument must be an Array // or an arguments object. We don't model the arguments object, // so let's just be forgiving for now. // TODO(nicksantos): Model the Arguments object. builder.addOptionalParams( registry.createNullableType(getTypeOfThis()), registry.createNullableType( registry.getNativeType(JSTypeNative.OBJECT_TYPE))); defineDeclaredProperty(name, new FunctionBuilder(registry) .withParams(builder) .withReturnType(getReturnType()) .build(), source); } } return super.getPropertyType(name); } /** * Get the return value of calling "bind" on this function * with the specified number of arguments. * * If -1 is passed, then we will return a result that accepts * any parameters. */ public FunctionType getBindReturnType(int argsToBind) { FunctionBuilder builder = new FunctionBuilder(registry) .withReturnType(getReturnType()); if (argsToBind >= 0) { Node origParams = getParametersNode(); if (origParams != null) { Node params = origParams.cloneTree(); for (int i = 1; i < argsToBind && params.getFirstChild() != null; i++) { + if (params.getFirstChild().isVarArgs()) { + break; + } params.removeFirstChild(); } builder.withParamsNode(params); } } return builder.build(); } /** * Notice that "call" and "bind" have the same argument signature, * except that all the arguments of "bind" (except the first) * are optional. */ private FunctionType getCallOrBindSignature(boolean isCall) { boolean isBind = !isCall; FunctionBuilder builder = new FunctionBuilder(registry) .withReturnType(isCall ? getReturnType() : getBindReturnType(-1)); Node origParams = getParametersNode(); if (origParams != null) { Node params = origParams.cloneTree(); Node thisTypeNode = Node.newString(Token.NAME, "thisType"); thisTypeNode.setJSType( registry.createOptionalNullableType(getTypeOfThis())); params.addChildToFront(thisTypeNode); thisTypeNode.setOptionalArg(isCall); if (isBind) { // The arguments of bind() are unique in that they are all // optional but not undefinable. for (Node current = thisTypeNode.getNext(); current != null; current = current.getNext()) { current.setOptionalArg(true); } } builder.withParamsNode(params); } return builder.build(); } @Override boolean defineProperty(String name, JSType type, boolean inferred, Node propertyNode) { if ("prototype".equals(name)) { ObjectType objType = type.toObjectType(); if (objType != null) { if (prototypeSlot != null && objType.isEquivalentTo(prototypeSlot.getType())) { return true; } this.setPrototypeBasedOn(objType, propertyNode); return true; } else { return false; } } return super.defineProperty(name, type, inferred, propertyNode); } /** * Computes the supremum or infimum of two functions. * Because sup() and inf() share a lot of logic for functions, we use * a single helper. * @param leastSuper If true, compute the supremum of {@code this} with * {@code that}. Otherwise compute the infimum. * @return The least supertype or greatest subtype. */ FunctionType supAndInfHelper(FunctionType that, boolean leastSuper) { // NOTE(nicksantos): When we remove the unknown type, the function types // form a lattice with the universal constructor at the top of the lattice, // and the LEAST_FUNCTION_TYPE type at the bottom of the lattice. // // When we introduce the unknown type, it's much more difficult to make // heads or tails of the partial ordering of types, because there's no // clear hierarchy between the different components (parameter types and // return types) in the ArrowType. // // Rather than make the situation more complicated by introducing new // types (like unions of functions), we just fallback on the simpler // approach of getting things right at the top and the bottom of the // lattice. // // If there are unknown parameters or return types making things // ambiguous, then sup(A, B) is always the top function type, and // inf(A, B) is always the bottom function type. Preconditions.checkNotNull(that); if (isEquivalentTo(that)) { return this; } // If these are ordinary functions, then merge them. // Don't do this if any of the params/return // values are unknown, because then there will be cycles in // their local lattice and they will merge in weird ways. if (isOrdinaryFunction() && that.isOrdinaryFunction() && !this.call.hasUnknownParamsOrReturn() && !that.call.hasUnknownParamsOrReturn()) { // Check for the degenerate case, but double check // that there's not a cycle. boolean isSubtypeOfThat = this.isSubtype(that); boolean isSubtypeOfThis = that.isSubtype(this); if (isSubtypeOfThat && !isSubtypeOfThis) { return leastSuper ? that : this; } else if (isSubtypeOfThis && !isSubtypeOfThat) { return leastSuper ? this : that; } // Merge the two functions component-wise. FunctionType merged = tryMergeFunctionPiecewise(that, leastSuper); if (merged != null) { return merged; } } // The function instance type is a special case // that lives above the rest of the lattice. JSType functionInstance = registry.getNativeType( JSTypeNative.FUNCTION_INSTANCE_TYPE); if (functionInstance.isEquivalentTo(that)) { return leastSuper ? that : this; } else if (functionInstance.isEquivalentTo(this)) { return leastSuper ? this : that; } // In theory, we should be using the GREATEST_FUNCTION_TYPE as the // greatest function. In practice, we don't because it's way too // broad. The greatest function takes var_args None parameters, which // means that all parameters register a type warning. // // Instead, we use the U2U ctor type, which has unknown type args. FunctionType greatestFn = registry.getNativeFunctionType(JSTypeNative.U2U_CONSTRUCTOR_TYPE); FunctionType leastFn = registry.getNativeFunctionType(JSTypeNative.LEAST_FUNCTION_TYPE); return leastSuper ? greatestFn : leastFn; } /** * Try to get the sup/inf of two functions by looking at the * piecewise components. */ private FunctionType tryMergeFunctionPiecewise( FunctionType other, boolean leastSuper) { Node newParamsNode = null; if (call.hasEqualParameters(other.call)) { newParamsNode = call.parameters; } else { // If the parameters are not equal, don't try to merge them. // Someday, we should try to merge the individual params. return null; } JSType newReturnType = leastSuper ? call.returnType.getLeastSupertype(other.call.returnType) : call.returnType.getGreatestSubtype(other.call.returnType); ObjectType newTypeOfThis = null; if (isEquivalent(typeOfThis, other.typeOfThis)) { newTypeOfThis = typeOfThis; } else { JSType maybeNewTypeOfThis = leastSuper ? typeOfThis.getLeastSupertype(other.typeOfThis) : typeOfThis.getGreatestSubtype(other.typeOfThis); if (maybeNewTypeOfThis instanceof ObjectType) { newTypeOfThis = (ObjectType) maybeNewTypeOfThis; } else { newTypeOfThis = leastSuper ? registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE) : registry.getNativeObjectType(JSTypeNative.NO_OBJECT_TYPE); } } boolean newReturnTypeInferred = call.returnTypeInferred || other.call.returnTypeInferred; return new FunctionType( registry, null, null, new ArrowType( registry, newParamsNode, newReturnType, newReturnTypeInferred), newTypeOfThis, null, false, false); } /** * Given a constructor or an interface type, get its superclass constructor * or {@code null} if none exists. */ public FunctionType getSuperClassConstructor() { Preconditions.checkArgument(isConstructor() || isInterface()); ObjectType maybeSuperInstanceType = getPrototype().getImplicitPrototype(); if (maybeSuperInstanceType == null) { return null; } return maybeSuperInstanceType.getConstructor(); } /** * Given an interface and a property, finds the top-most super interface * that has the property defined (including this interface). */ public static ObjectType getTopDefiningInterface(ObjectType type, String propertyName) { ObjectType foundType = null; if (type.hasProperty(propertyName)) { foundType = type; } for (ObjectType interfaceType : type.getCtorExtendedInterfaces()) { if (interfaceType.hasProperty(propertyName)) { foundType = getTopDefiningInterface(interfaceType, propertyName); } } return foundType; } /** * Given a constructor or an interface type and a property, finds the * top-most superclass that has the property defined (including this * constructor). */ public ObjectType getTopMostDefiningType(String propertyName) { Preconditions.checkState(isConstructor() || isInterface()); Preconditions.checkArgument(getPrototype().hasProperty(propertyName)); FunctionType ctor = this; if (isInterface()) { return getTopDefiningInterface(this.getInstanceType(), propertyName); } ObjectType topInstanceType = ctor.getInstanceType(); while (true) { topInstanceType = ctor.getInstanceType(); ctor = ctor.getSuperClassConstructor(); if (ctor == null || !ctor.getPrototype().hasProperty(propertyName)) { break; } } return topInstanceType; } /** * Two function types are equal if their signatures match. Since they don't * have signatures, two interfaces are equal if their names match. */ @Override public boolean isEquivalentTo(JSType otherType) { FunctionType that = JSType.toMaybeFunctionType(otherType); if (that == null) { return false; } if (this.isConstructor()) { if (that.isConstructor()) { return this == that; } return false; } if (this.isInterface()) { if (that.isInterface()) { return this.getReferenceName().equals(that.getReferenceName()); } return false; } if (that.isInterface()) { return false; } return this.typeOfThis.isEquivalentTo(that.typeOfThis) && this.call.isEquivalentTo(that.call); } @Override public int hashCode() { return isInterface() ? getReferenceName().hashCode() : call.hashCode(); } public boolean hasEqualCallType(FunctionType otherType) { return this.call.isEquivalentTo(otherType.call); } /** * Informally, a function is represented by * {@code function (params): returnType} where the {@code params} is a comma * separated list of types, the first one being a special * {@code this:T} if the function expects a known type for {@code this}. */ @Override public String toString() { if (!isPrettyPrint() || this == registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE)) { return "Function"; } setPrettyPrint(false); StringBuilder b = new StringBuilder(32); b.append("function ("); int paramNum = call.parameters.getChildCount(); boolean hasKnownTypeOfThis = !typeOfThis.isUnknownType(); if (hasKnownTypeOfThis) { if (isConstructor()) { b.append("new:"); } else { b.append("this:"); } b.append(typeOfThis.toString()); } if (paramNum > 0) { if (hasKnownTypeOfThis) { b.append(", "); } Node p = call.parameters.getFirstChild(); if (p.isVarArgs()) { appendVarArgsString(b, p.getJSType()); } else { b.append(p.getJSType().toString()); } p = p.getNext(); while (p != null) { b.append(", "); if (p.isVarArgs()) { appendVarArgsString(b, p.getJSType()); } else { b.append(p.getJSType().toString()); } p = p.getNext(); } } b.append("): "); b.append(call.returnType); setPrettyPrint(true); return b.toString(); } /** Gets the string representation of a var args param. */ private void appendVarArgsString(StringBuilder builder, JSType paramType) { if (paramType.isUnionType()) { // Remove the optionalness from the var arg. paramType = paramType.toMaybeUnionType().getRestrictedUnion( registry.getNativeType(JSTypeNative.VOID_TYPE)); } builder.append("...[").append(paramType.toString()).append("]"); } /** * A function is a subtype of another if their call methods are related via * subtyping and {@code this} is a subtype of {@code that} with regard to * the prototype chain. */ @Override public boolean isSubtype(JSType that) { if (JSType.isSubtypeHelper(this, that)) { return true; } if (that.isFunctionType()) { FunctionType other = that.toMaybeFunctionType(); if (other.isInterface()) { // Any function can be assigned to an interface function. return true; } if (this.isInterface()) { // An interface function cannot be assigned to anything. return false; } // If functionA is a subtype of functionB, then their "this" types // should be contravariant. However, this causes problems because // of the way we enforce overrides. Because function(this:SubFoo) // is not a subtype of function(this:Foo), our override check treats // this as an error. It also screws up out standard method // for aliasing constructors. Let's punt on all this for now. // TODO(nicksantos): fix this. boolean treatThisTypesAsCovariant = // If either one of these is a ctor, skip 'this' checking. this.isConstructor() || other.isConstructor() || // An interface 'this'-type is non-restrictive. // In practical terms, if C implements I, and I has a method m, // then any m doesn't necessarily have to C#m's 'this' // type doesn't need to match I. (other.typeOfThis.getConstructor() != null && other.typeOfThis.getConstructor().isInterface()) || // If one of the 'this' types is covariant of the other, // then we'll treat them as covariant (see comment above). other.typeOfThis.isSubtype(this.typeOfThis) || this.typeOfThis.isSubtype(other.typeOfThis); return treatThisTypesAsCovariant && this.call.isSubtype(other.call); } return getNativeType(JSTypeNative.FUNCTION_PROTOTYPE).isSubtype(that); } @Override public <T> T visit(Visitor<T> visitor) { return visitor.caseFunctionType(this); } /** * Gets the type of instance of this function. * @throws IllegalStateException if this function is not a constructor * (see {@link #isConstructor()}). */ public ObjectType getInstanceType() { Preconditions.checkState(hasInstanceType()); return typeOfThis; } /** * Sets the instance type. This should only be used for special * native types. */ void setInstanceType(ObjectType instanceType) { typeOfThis = instanceType; } /** * Returns whether this function type has an instance type. */ public boolean hasInstanceType() { return isConstructor() || isInterface(); } /** * Gets the type of {@code this} in this function. */ @Override public ObjectType getTypeOfThis() { return typeOfThis.isNoObjectType() ? registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE) : typeOfThis; } /** * Gets the source node or null if this is an unknown function. */ public Node getSource() { return source; } /** * Sets the source node. */ public void setSource(Node source) { if (prototypeSlot != null) { // NOTE(bashir): On one hand when source is null we want to drop any // references to old nodes retained in prototypeSlot. On the other hand // we cannot simply drop prototypeSlot, so we retain all information // except the propertyNode for which we use an approximation! These // details mostly matter in hot-swap passes. if (source == null || prototypeSlot.getNode() == null) { prototypeSlot = new Property(prototypeSlot.getName(), prototypeSlot.getType(), prototypeSlot.isTypeInferred(), source); } } this.source = source; } /** Adds a type to the list of subtypes for this type. */ private void addSubType(FunctionType subType) { if (subTypes == null) { subTypes = Lists.newArrayList(); } subTypes.add(subType); } @Override public void clearCachedValues() { super.clearCachedValues(); if (subTypes != null) { for (FunctionType subType : subTypes) { subType.clearCachedValues(); } } if (!isNativeObjectType()) { if (hasInstanceType()) { getInstanceType().clearCachedValues(); } if (prototypeSlot != null) { ((PrototypeObjectType) prototypeSlot.getType()).clearCachedValues(); } } } /** * Returns a list of types that are subtypes of this type. This is only valid * for constructor functions, and may be null. This allows a downward * traversal of the subtype graph. */ public List<FunctionType> getSubTypes() { return subTypes; } @Override public boolean hasCachedValues() { return prototypeSlot != null || super.hasCachedValues(); } /** * Gets the template type name. */ public String getTemplateTypeName() { return templateTypeName; } @Override JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) { setResolvedTypeInternal(this); call = (ArrowType) safeResolve(call, t, scope); if (prototypeSlot != null) { prototypeSlot.setType( safeResolve(prototypeSlot.getType(), t, scope)); } // Warning about typeOfThis if it doesn't resolve to an ObjectType // is handled further upstream. // // TODO(nicksantos): Handle this correctly if we have a UnionType. // // TODO(nicksantos): In ES3, the runtime coerces "null" to the global // activation object. In ES5, it leaves it as null. Just punt on this // issue for now by coercing out null. This is complicated by the // fact that when most people write @this {Foo}, they really don't // mean "nullable Foo". For certain tags (like @extends) we de-nullify // the name for them. JSType maybeTypeOfThis = safeResolve(typeOfThis, t, scope); if (maybeTypeOfThis != null) { maybeTypeOfThis = maybeTypeOfThis.restrictByNotNullOrUndefined(); } if (maybeTypeOfThis instanceof ObjectType) { typeOfThis = (ObjectType) maybeTypeOfThis; } boolean changed = false; ImmutableList.Builder<ObjectType> resolvedInterfaces = ImmutableList.builder(); for (ObjectType iface : implementedInterfaces) { ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope); resolvedInterfaces.add(resolvedIface); changed |= (resolvedIface != iface); } if (changed) { implementedInterfaces = resolvedInterfaces.build(); } if (subTypes != null) { for (int i = 0; i < subTypes.size(); i++) { subTypes.set( i, JSType.toMaybeFunctionType(subTypes.get(i).resolve(t, scope))); } } return super.resolveInternal(t, scope); } @Override public String toDebugHashCodeString() { if (this == registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE)) { return super.toDebugHashCodeString(); } StringBuilder b = new StringBuilder(32); b.append("function ("); int paramNum = call.parameters.getChildCount(); boolean hasKnownTypeOfThis = !typeOfThis.isUnknownType(); if (hasKnownTypeOfThis) { b.append("this:"); b.append(getDebugHashCodeStringOf(typeOfThis)); } if (paramNum > 0) { if (hasKnownTypeOfThis) { b.append(", "); } Node p = call.parameters.getFirstChild(); b.append(getDebugHashCodeStringOf(p.getJSType())); p = p.getNext(); while (p != null) { b.append(", "); b.append(getDebugHashCodeStringOf(p.getJSType())); p = p.getNext(); } } b.append(")"); b.append(": "); b.append(getDebugHashCodeStringOf(call.returnType)); return b.toString(); } private String getDebugHashCodeStringOf(JSType type) { if (type == this) { return "me"; } else { return type.toDebugHashCodeString(); } } } diff --git a/closure/closure-compiler/test/com/google/javascript/jscomp/TypeCheckTest.java b/closure/closure-compiler/test/com/google/javascript/jscomp/TypeCheckTest.java index 686051a22..6239f971b 100644 --- a/closure/closure-compiler/test/com/google/javascript/jscomp/TypeCheckTest.java +++ b/closure/closure-compiler/test/com/google/javascript/jscomp/TypeCheckTest.java @@ -1,9565 +1,9585 @@ /* * Copyright 2006 The Closure Compiler 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 com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferrable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode] :2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Tehnically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes thru this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } + public void testFunctionBind4() throws Exception { + testTypes( + "/** @param {...number} x */" + + "function f(x) {}" + + "f.bind(null, 3, 3, 3)(true);", + "actual parameter 1 of function does not match formal parameter\n" + + "found : boolean\n" + + "required: (number|undefined)"); + } + + public void testFunctionBind5() throws Exception { + testTypes( + "/** @param {...number} x */" + + "function f(x) {}" + + "f.bind(null, true)(3, 3, 3);", + "actual parameter 2 of f.bind does not match formal parameter\n" + + "found : boolean\n" + + "required: (number|undefined)"); + } + public void testGoogBind1() throws Exception { // We currently do not support goog.bind natively. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. May be it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n"+ "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n"+ "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // ok, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format()); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format("number")); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format()); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
false
false
null
null
diff --git a/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java b/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java index ec755fe..a9192a4 100644 --- a/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java +++ b/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java @@ -1,129 +1,129 @@ /******************************************************************************* * Copyright (c) 2009 Ketan Padegaonkar 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: * Ketan Padegaonkar - initial API and implementation *******************************************************************************/ package org.eclipse.swtbot.swt.finder.widgets; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swtbot.swt.finder.ReferenceBy; import org.eclipse.swtbot.swt.finder.SWTBotWidget; import org.eclipse.swtbot.swt.finder.Style; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.results.BoolResult; import org.eclipse.swtbot.swt.finder.results.VoidResult; import org.eclipse.swtbot.swt.finder.utils.MessageFormat; import org.eclipse.swtbot.swt.finder.utils.SWTUtils; import org.eclipse.swtbot.swt.finder.utils.internal.Assert; import org.hamcrest.SelfDescribing; /** * Represents a tool item of type checkbox * * @author Ketan Padegaonkar &lt;KetanPadegaonkar [at] gmail [dot] com&gt; * @version $Id$ */ @SWTBotWidget(clasz = ToolItem.class, preferredName = "toolbarToggleButton", style = @Style(name = "SWT.CHECK", value = SWT.CHECK), referenceBy = { ReferenceBy.MNEMONIC, ReferenceBy.TOOLTIP }) public class SWTBotToolbarCheckboxButton extends SWTBotToolbarButton { /** * Construcst an new instance of this item. * * @param w the tool item. * @throws WidgetNotFoundException if the widget is <code>null</code> or widget has been disposed. */ public SWTBotToolbarCheckboxButton(ToolItem w) throws WidgetNotFoundException { this(w, null); } /** * Construcst an new instance of this item. * * @param w the tool item. * @param description the description of the widget, this will be reported by {@link #toString()} * @throws WidgetNotFoundException if the widget is <code>null</code> or widget has been disposed. */ public SWTBotToolbarCheckboxButton(ToolItem w, SelfDescribing description) throws WidgetNotFoundException { super(w, description); Assert.isTrue(SWTUtils.hasStyle(w, SWT.CHECK), "Expecting a checkbox."); //$NON-NLS-1$ } /** * Click on the tool item. This will toggle the tool item. * * @return itself */ public SWTBotToolbarCheckboxButton toggle() { log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$ assertEnabled(); + internalToggle(); notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.MouseDown); notify(SWT.MouseUp); notify(SWT.Selection); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); - internalToggle(); log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$ return this; } public SWTBotToolbarCheckboxButton click() { return toggle(); } private void internalToggle() { syncExec(new VoidResult() { public void run() { widget.setSelection(!widget.getSelection()); } }); } /** * Selects the checkbox button. */ public void select() { if (!isChecked()) toggle(); } /** * Deselects the checkbox button. */ public void deselect() { if (isChecked()) toggle(); } /** * @return <code>true</code> if the button is checked, <code>false</code> otherwise. */ public boolean isChecked() { return syncExec(new BoolResult() { public Boolean run() { return widget.getSelection(); } }); } @Override public boolean isEnabled() { return syncExec(new BoolResult() { public Boolean run() { return widget.isEnabled(); } }); } }
false
true
public SWTBotToolbarCheckboxButton toggle() { log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$ assertEnabled(); notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.MouseDown); notify(SWT.MouseUp); notify(SWT.Selection); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); internalToggle(); log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$ return this; }
public SWTBotToolbarCheckboxButton toggle() { log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$ assertEnabled(); internalToggle(); notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.MouseDown); notify(SWT.MouseUp); notify(SWT.Selection); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$ return this; }
diff --git a/core/org.eclipse.ptp.proxy.protocol/util/org/eclipse/ptp/proxy/util/ProtocolUtil.java b/core/org.eclipse.ptp.proxy.protocol/util/org/eclipse/ptp/proxy/util/ProtocolUtil.java index 68d7de7ce..346c00150 100644 --- a/core/org.eclipse.ptp.proxy.protocol/util/org/eclipse/ptp/proxy/util/ProtocolUtil.java +++ b/core/org.eclipse.ptp.proxy.protocol/util/org/eclipse/ptp/proxy/util/ProtocolUtil.java @@ -1,336 +1,338 @@ /******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.ptp.proxy.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.List; import org.eclipse.ptp.proxy.util.messages.Messages; public class ProtocolUtil { /** * @since 5.0 */ public final static int TYPE_STRING_ATTR = 0; /** * @since 5.0 */ public final static int TYPE_INTEGER = 1; /** * @since 5.0 */ public final static int TYPE_BITSET = 2; /** * @since 5.0 */ public final static int TYPE_STRING = 3; /** * @since 5.0 */ public final static int TYPE_INTEGER_ATTR = 4; /** * @since 5.0 */ public final static int TYPE_BOOLEAN_ATTR = 5; private final static String EMPTY_STRING = ""; //$NON-NLS-1$ private final static int PACKET_ARG_LEN_SIZE = 8; // remove once protocol // changes have been // implemented /** * Decode a string into a BigInteger * * @param address * @return BigInteger */ @Deprecated public static BigInteger decodeAddress(String address) { int index = 0; int radix = 10; boolean negative = false; // Handle zero length address = address.trim(); if (address.length() == 0) { return BigInteger.ZERO; } // Handle minus sign, if present if (address.startsWith("-")) { //$NON-NLS-1$ negative = true; index++; } if (address.startsWith("0x", index) || address.startsWith("0X", index)) { //$NON-NLS-1$ //$NON-NLS-2$ index += 2; radix = 16; } else if (address.startsWith("#", index)) { //$NON-NLS-1$ index++; radix = 16; } else if (address.startsWith("0", index) && address.length() > 1 + index) { //$NON-NLS-1$ index++; radix = 8; } if (index > 0) { address = address.substring(index); } if (negative) { address = "-" + address; //$NON-NLS-1$ } try { return new BigInteger(address, radix); } catch (NumberFormatException e) { // ... // What can we do ??? } return BigInteger.ZERO; } /** * Convert as sequence of hexadecimal values to a Java byte array. * * @param str * @return byte array */ @Deprecated public static byte[] decodeBytes(String str) { int len = str.length() / 2; byte[] strBytes = new byte[len]; for (int i = 0, p = 0; i < len; i++, p += 2) { byte c = (byte) ((Character.digit(str.charAt(p), 16) & 0xf) << 4); c |= (byte) ((Character.digit(str.charAt(p + 1), 16) & 0xf)); strBytes[i] = c; } return strBytes; } /** * Convert a proxy representation of a string to a String. A string is * represented by a length in varint format followed by the string * characters. If the characters are multibyte, then the length will reflect * this. * * @param buf * byte buffer containing string to be decoded * @param decoder * charset decoder * @return decoded string or null if the field should be skipped * @throws IOException * if the string can't be decoded * * @since 5.0 */ public static String decodeString(ByteBuffer buf, CharsetDecoder decoder) throws IOException { String result = EMPTY_STRING; VarInt strLen = new VarInt(buf); if (!strLen.isValid()) { throw new IOException(Messages.getString("ProtocolUtil.0")); //$NON-NLS-1$ } int len = strLen.getValue(); if (len > 0) { ByteBuffer strBuf = buf.slice(); try { strBuf.limit(len); } catch (IllegalArgumentException e) { throw new IOException(e.getMessage()); } try { CharBuffer chars = decoder.decode(strBuf); result = chars.toString(); } catch (CharacterCodingException e) { throw new IOException(e.getMessage()); } try { buf.position(buf.position() + len); } catch (IllegalArgumentException e) { throw new IOException(e.getMessage()); } } return result; } /** * Convert a proxy representation of a string into a Java String * * @param buf * @param start * @return proxy string converted to Java String */ @Deprecated public static String decodeString(CharBuffer buf, int start) { int end = start + PACKET_ARG_LEN_SIZE; int len = Integer.parseInt(buf.subSequence(start, end).toString(), 16); start = end + 1; // Skip ':' end = start + len; return buf.subSequence(start, end).toString(); } /** * Convert a proxy representation of a string attribute into a Java String. * Assumes that the type byte as been removed from the buffer. * * Attributes are key/value pairs of the form "key=value". They are encoded * into a pair of length/value pairs, with the first length/value pair being * the key of a key=value pair and the second length/value pair being the * value of a key=value pair or a stand-alone string's value. * * @param buf * buffer containing bytes to decode * @param decoder * charset decoder * @return attribute converted to Java String * @throws IOException * if decoding failed * @since 5.0 */ public static String decodeStringAttributeType(ByteBuffer buf, CharsetDecoder decoder) throws IOException { String result = EMPTY_STRING; String key = decodeString(buf, decoder); if (key.length() > 0) { result = key; } String value = decodeString(buf, decoder); if (value.length() > 0) { if (result.length() > 0) { result += "="; //$NON-NLS-1$ } result += value; } return result; } /** * Convert an integer to it's proxy representation * * @param val * @param len * @return proxy representation */ @Deprecated public static String encodeIntVal(int val, int len) { char[] res = new char[len]; String str = Integer.toHexString(val); int rem = len - str.length(); for (int i = 0; i < len; i++) { if (i < rem) { res[i] = '0'; } else { res[i] = str.charAt(i - rem); } } return String.valueOf(res); } /** * Encode a string into it's proxy representation * * @param str * @return proxy representation */ @Deprecated public static String encodeString(String str) { int len; if (str == null) { len = 0; str = ""; //$NON-NLS-1$ } else { len = str.length(); } return encodeIntVal(len, PACKET_ARG_LEN_SIZE) + ":" + str; //$NON-NLS-1$ } /** * Encode a string attribute type and place the encoded bytes in buffer - * list. + * list. The string must be of the form "key=value" where key cannot contain + * an '=' character. The value can contain any characters. * * @param bufs * list of buffers containing encoded string * @param attribute * string attribute * @param charset * charset to map characters into bytes * @throws IOException * @since 5.0 */ public static void encodeStringAttributeType(List<ByteBuffer> bufs, String attribute, Charset charset) throws IOException { - String[] kv = attribute.split("="); //$NON-NLS-1$ + String[] kv = attribute.split("=", 2); //$NON-NLS-1$ bufs.add(encodeType(TYPE_STRING_ATTR)); - encodeString(bufs, kv[0], charset); if (kv.length == 1) { bufs.add(new VarInt(0).getBytes()); + encodeString(bufs, kv[0], charset); } else { + encodeString(bufs, kv[0], charset); encodeString(bufs, kv[1], charset); } } /** * Encode a string type and place the encoded bytes in buffer list. * * @param bufs * list of buffers containing encoded string * @param str * string to encode * @param charset * charset to map characters into bytes * @since 5.0 */ public static void encodeStringType(List<ByteBuffer> bufs, String str, Charset charset) { bufs.add(encodeType(TYPE_STRING)); encodeString(bufs, str, charset); } /** * Encode a string and place the encoded bytes in buffer list. * * @param bufs * list of buffers containing encoded string * @param str * string to encode * @param charset * charset to map characters into bytes */ private static void encodeString(List<ByteBuffer> bufs, String str, Charset charset) { bufs.add(new VarInt(str.length()).getBytes()); try { bufs.add(ByteBuffer.wrap(str.getBytes(charset.name()))); } catch (UnsupportedEncodingException e) { bufs.add(ByteBuffer.wrap(str.getBytes())); } } /** * Encode an attribute type in a byte buffer * * @param type * @return */ private static ByteBuffer encodeType(int type) { ByteBuffer b = ByteBuffer.allocate(1).put((byte) type); b.rewind(); return b; } }
false
false
null
null
diff --git a/plugins/linux/src/java/net/java/games/input/LinuxNativeTypesMap.java b/plugins/linux/src/java/net/java/games/input/LinuxNativeTypesMap.java index a739074..77d7da7 100644 --- a/plugins/linux/src/java/net/java/games/input/LinuxNativeTypesMap.java +++ b/plugins/linux/src/java/net/java/games/input/LinuxNativeTypesMap.java @@ -1,793 +1,795 @@ /** * Copyright (C) 2003 Jeremy Booth ([email protected]) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. Redistributions in binary * form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided * with the distribution. * The name of the author may not be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE */ package net.java.games.input; /** * Mapping utility class between native type ints and string names or * Key.Identifiers * @author Jeremy Booth ([email protected]) */ class LinuxNativeTypesMap { private static LinuxNativeTypesMap INSTANCE = new LinuxNativeTypesMap(); private final Component.Identifier relAxesIDs[]; private final Component.Identifier absAxesIDs[]; private final Component.Identifier buttonIDs[]; /** create an empty, uninitialsed map */ private LinuxNativeTypesMap() { buttonIDs = new Component.Identifier[NativeDefinitions.KEY_MAX]; relAxesIDs = new Component.Identifier[NativeDefinitions.REL_MAX]; absAxesIDs = new Component.Identifier[NativeDefinitions.ABS_MAX]; reInit(); } /** Do the work. */ private void reInit() { buttonIDs[NativeDefinitions.KEY_ESC] = Component.Identifier.Key.ESCAPE; buttonIDs[NativeDefinitions.KEY_1] = Component.Identifier.Key._1; buttonIDs[NativeDefinitions.KEY_2] = Component.Identifier.Key._2; buttonIDs[NativeDefinitions.KEY_3] = Component.Identifier.Key._3; buttonIDs[NativeDefinitions.KEY_4] = Component.Identifier.Key._4; buttonIDs[NativeDefinitions.KEY_5] = Component.Identifier.Key._5; buttonIDs[NativeDefinitions.KEY_6] = Component.Identifier.Key._6; buttonIDs[NativeDefinitions.KEY_7] = Component.Identifier.Key._7; buttonIDs[NativeDefinitions.KEY_8] = Component.Identifier.Key._8; buttonIDs[NativeDefinitions.KEY_9] = Component.Identifier.Key._9; buttonIDs[NativeDefinitions.KEY_0] = Component.Identifier.Key._0; buttonIDs[NativeDefinitions.KEY_MINUS] = Component.Identifier.Key.MINUS; buttonIDs[NativeDefinitions.KEY_EQUAL] = Component.Identifier.Key.EQUALS; buttonIDs[NativeDefinitions.KEY_BACKSPACE] = Component.Identifier.Key.BACK; buttonIDs[NativeDefinitions.KEY_TAB] = Component.Identifier.Key.TAB; buttonIDs[NativeDefinitions.KEY_Q] = Component.Identifier.Key.Q; buttonIDs[NativeDefinitions.KEY_W] = Component.Identifier.Key.W; buttonIDs[NativeDefinitions.KEY_E] = Component.Identifier.Key.E; buttonIDs[NativeDefinitions.KEY_R] = Component.Identifier.Key.R; buttonIDs[NativeDefinitions.KEY_T] = Component.Identifier.Key.T; buttonIDs[NativeDefinitions.KEY_Y] = Component.Identifier.Key.Y; buttonIDs[NativeDefinitions.KEY_U] = Component.Identifier.Key.U; buttonIDs[NativeDefinitions.KEY_I] = Component.Identifier.Key.I; buttonIDs[NativeDefinitions.KEY_O] = Component.Identifier.Key.O; buttonIDs[NativeDefinitions.KEY_P] = Component.Identifier.Key.P; buttonIDs[NativeDefinitions.KEY_LEFTBRACE] = Component.Identifier.Key.LBRACKET; buttonIDs[NativeDefinitions.KEY_RIGHTBRACE] = Component.Identifier.Key.RBRACKET; buttonIDs[NativeDefinitions.KEY_ENTER] = Component.Identifier.Key.RETURN; buttonIDs[NativeDefinitions.KEY_LEFTCTRL] = Component.Identifier.Key.LCONTROL; buttonIDs[NativeDefinitions.KEY_A] = Component.Identifier.Key.A; buttonIDs[NativeDefinitions.KEY_S] = Component.Identifier.Key.S; buttonIDs[NativeDefinitions.KEY_D] = Component.Identifier.Key.D; buttonIDs[NativeDefinitions.KEY_F] = Component.Identifier.Key.F; buttonIDs[NativeDefinitions.KEY_G] = Component.Identifier.Key.G; buttonIDs[NativeDefinitions.KEY_H] = Component.Identifier.Key.H; buttonIDs[NativeDefinitions.KEY_J] = Component.Identifier.Key.J; buttonIDs[NativeDefinitions.KEY_K] = Component.Identifier.Key.K; buttonIDs[NativeDefinitions.KEY_L] = Component.Identifier.Key.L; buttonIDs[NativeDefinitions.KEY_SEMICOLON] = Component.Identifier.Key.SEMICOLON; buttonIDs[NativeDefinitions.KEY_APOSTROPHE] = Component.Identifier.Key.APOSTROPHE; buttonIDs[NativeDefinitions.KEY_GRAVE] = Component.Identifier.Key.GRAVE; buttonIDs[NativeDefinitions.KEY_LEFTSHIFT] = Component.Identifier.Key.LSHIFT; buttonIDs[NativeDefinitions.KEY_BACKSLASH] = Component.Identifier.Key.BACKSLASH; buttonIDs[NativeDefinitions.KEY_Z] = Component.Identifier.Key.Z; buttonIDs[NativeDefinitions.KEY_X] = Component.Identifier.Key.X; buttonIDs[NativeDefinitions.KEY_C] = Component.Identifier.Key.C; buttonIDs[NativeDefinitions.KEY_V] = Component.Identifier.Key.V; buttonIDs[NativeDefinitions.KEY_B] = Component.Identifier.Key.B; buttonIDs[NativeDefinitions.KEY_N] = Component.Identifier.Key.N; buttonIDs[NativeDefinitions.KEY_M] = Component.Identifier.Key.M; buttonIDs[NativeDefinitions.KEY_COMMA] = Component.Identifier.Key.COMMA; buttonIDs[NativeDefinitions.KEY_DOT] = Component.Identifier.Key.PERIOD; buttonIDs[NativeDefinitions.KEY_SLASH] = Component.Identifier.Key.SLASH; buttonIDs[NativeDefinitions.KEY_RIGHTSHIFT] = Component.Identifier.Key.RSHIFT; buttonIDs[NativeDefinitions.KEY_KPASTERISK] = Component.Identifier.Key.MULTIPLY; buttonIDs[NativeDefinitions.KEY_LEFTALT] = Component.Identifier.Key.LALT; buttonIDs[NativeDefinitions.KEY_SPACE] = Component.Identifier.Key.SPACE; buttonIDs[NativeDefinitions.KEY_CAPSLOCK] = Component.Identifier.Key.CAPITAL; buttonIDs[NativeDefinitions.KEY_F1] = Component.Identifier.Key.F1; buttonIDs[NativeDefinitions.KEY_F2] = Component.Identifier.Key.F2; buttonIDs[NativeDefinitions.KEY_F3] = Component.Identifier.Key.F3; buttonIDs[NativeDefinitions.KEY_F4] = Component.Identifier.Key.F4; buttonIDs[NativeDefinitions.KEY_F5] = Component.Identifier.Key.F5; buttonIDs[NativeDefinitions.KEY_F6] = Component.Identifier.Key.F6; buttonIDs[NativeDefinitions.KEY_F7] = Component.Identifier.Key.F7; buttonIDs[NativeDefinitions.KEY_F8] = Component.Identifier.Key.F8; buttonIDs[NativeDefinitions.KEY_F9] = Component.Identifier.Key.F9; buttonIDs[NativeDefinitions.KEY_F10] = Component.Identifier.Key.F10; buttonIDs[NativeDefinitions.KEY_NUMLOCK] = Component.Identifier.Key.NUMLOCK; buttonIDs[NativeDefinitions.KEY_SCROLLLOCK] = Component.Identifier.Key.SCROLL; buttonIDs[NativeDefinitions.KEY_KP7] = Component.Identifier.Key.NUMPAD7; buttonIDs[NativeDefinitions.KEY_KP8] = Component.Identifier.Key.NUMPAD8; buttonIDs[NativeDefinitions.KEY_KP9] = Component.Identifier.Key.NUMPAD9; buttonIDs[NativeDefinitions.KEY_KPMINUS] = Component.Identifier.Key.SUBTRACT; buttonIDs[NativeDefinitions.KEY_KP4] = Component.Identifier.Key.NUMPAD4; buttonIDs[NativeDefinitions.KEY_KP5] = Component.Identifier.Key.NUMPAD5; buttonIDs[NativeDefinitions.KEY_KP6] = Component.Identifier.Key.NUMPAD6; buttonIDs[NativeDefinitions.KEY_KPPLUS] = Component.Identifier.Key.ADD; buttonIDs[NativeDefinitions.KEY_KP1] = Component.Identifier.Key.NUMPAD1; buttonIDs[NativeDefinitions.KEY_KP2] = Component.Identifier.Key.NUMPAD2; buttonIDs[NativeDefinitions.KEY_KP3] = Component.Identifier.Key.NUMPAD3; buttonIDs[NativeDefinitions.KEY_KP0] = Component.Identifier.Key.NUMPAD0; buttonIDs[NativeDefinitions.KEY_KPDOT] = Component.Identifier.Key.DECIMAL; // buttonIDs[NativeDefinitions.KEY_103RD] = null; buttonIDs[NativeDefinitions.KEY_F13] = Component.Identifier.Key.F13; buttonIDs[NativeDefinitions.KEY_102ND] = null; buttonIDs[NativeDefinitions.KEY_F11] = Component.Identifier.Key.F11; buttonIDs[NativeDefinitions.KEY_F12] = Component.Identifier.Key.F12; buttonIDs[NativeDefinitions.KEY_F14] = Component.Identifier.Key.F14; buttonIDs[NativeDefinitions.KEY_F15] = Component.Identifier.Key.F15; buttonIDs[NativeDefinitions.KEY_F16] = null; buttonIDs[NativeDefinitions.KEY_F17] = null; buttonIDs[NativeDefinitions.KEY_F18] = null; buttonIDs[NativeDefinitions.KEY_F19] = null; buttonIDs[NativeDefinitions.KEY_F20] = null; buttonIDs[NativeDefinitions.KEY_KPENTER] = Component.Identifier.Key.NUMPADENTER; buttonIDs[NativeDefinitions.KEY_RIGHTCTRL] = Component.Identifier.Key.RCONTROL; buttonIDs[NativeDefinitions.KEY_KPSLASH] = Component.Identifier.Key.DIVIDE; buttonIDs[NativeDefinitions.KEY_SYSRQ] = Component.Identifier.Key.SYSRQ; buttonIDs[NativeDefinitions.KEY_RIGHTALT] = Component.Identifier.Key.RALT; buttonIDs[NativeDefinitions.KEY_LINEFEED] = null; buttonIDs[NativeDefinitions.KEY_HOME] = Component.Identifier.Key.HOME; buttonIDs[NativeDefinitions.KEY_UP] = Component.Identifier.Key.UP; buttonIDs[NativeDefinitions.KEY_PAGEUP] = Component.Identifier.Key.PAGEUP; buttonIDs[NativeDefinitions.KEY_LEFT] = Component.Identifier.Key.LEFT; buttonIDs[NativeDefinitions.KEY_RIGHT] = Component.Identifier.Key.RIGHT; buttonIDs[NativeDefinitions.KEY_END] = Component.Identifier.Key.END; buttonIDs[NativeDefinitions.KEY_DOWN] = Component.Identifier.Key.DOWN; buttonIDs[NativeDefinitions.KEY_PAGEDOWN] = Component.Identifier.Key.PAGEDOWN; buttonIDs[NativeDefinitions.KEY_INSERT] = Component.Identifier.Key.INSERT; buttonIDs[NativeDefinitions.KEY_DELETE] = Component.Identifier.Key.DELETE; buttonIDs[NativeDefinitions.KEY_PAUSE] = Component.Identifier.Key.PAUSE; /* buttonIDs[NativeDefinitions.KEY_MACRO] = "Macro"; buttonIDs[NativeDefinitions.KEY_MUTE] = "Mute"; buttonIDs[NativeDefinitions.KEY_VOLUMEDOWN] = "Volume Down"; buttonIDs[NativeDefinitions.KEY_VOLUMEUP] = "Volume Up"; buttonIDs[NativeDefinitions.KEY_POWER] = "Power";*/ buttonIDs[NativeDefinitions.KEY_KPEQUAL] = Component.Identifier.Key.NUMPADEQUAL; //buttonIDs[NativeDefinitions.KEY_KPPLUSMINUS] = "KeyPad +/-"; /* buttonIDs[NativeDefinitions.KEY_F21] = "F21"; buttonIDs[NativeDefinitions.KEY_F22] = "F22"; buttonIDs[NativeDefinitions.KEY_F23] = "F23"; buttonIDs[NativeDefinitions.KEY_F24] = "F24"; buttonIDs[NativeDefinitions.KEY_KPCOMMA] = "KeyPad comma"; buttonIDs[NativeDefinitions.KEY_LEFTMETA] = "LH Meta"; buttonIDs[NativeDefinitions.KEY_RIGHTMETA] = "RH Meta"; buttonIDs[NativeDefinitions.KEY_COMPOSE] = "Compose"; buttonIDs[NativeDefinitions.KEY_STOP] = "Stop"; buttonIDs[NativeDefinitions.KEY_AGAIN] = "Again"; buttonIDs[NativeDefinitions.KEY_PROPS] = "Properties"; buttonIDs[NativeDefinitions.KEY_UNDO] = "Undo"; buttonIDs[NativeDefinitions.KEY_FRONT] = "Front"; buttonIDs[NativeDefinitions.KEY_COPY] = "Copy"; buttonIDs[NativeDefinitions.KEY_OPEN] = "Open"; buttonIDs[NativeDefinitions.KEY_PASTE] = "Paste"; buttonIDs[NativeDefinitions.KEY_FIND] = "Find"; buttonIDs[NativeDefinitions.KEY_CUT] = "Cut"; buttonIDs[NativeDefinitions.KEY_HELP] = "Help"; buttonIDs[NativeDefinitions.KEY_MENU] = "Menu"; buttonIDs[NativeDefinitions.KEY_CALC] = "Calculator"; buttonIDs[NativeDefinitions.KEY_SETUP] = "Setup";*/ buttonIDs[NativeDefinitions.KEY_SLEEP] = Component.Identifier.Key.SLEEP; /*buttonIDs[NativeDefinitions.KEY_WAKEUP] = "Wakeup"; buttonIDs[NativeDefinitions.KEY_FILE] = "File"; buttonIDs[NativeDefinitions.KEY_SENDFILE] = "Send File"; buttonIDs[NativeDefinitions.KEY_DELETEFILE] = "Delete File"; buttonIDs[NativeDefinitions.KEY_XFER] = "Transfer"; buttonIDs[NativeDefinitions.KEY_PROG1] = "Program 1"; buttonIDs[NativeDefinitions.KEY_PROG2] = "Program 2"; buttonIDs[NativeDefinitions.KEY_WWW] = "Web Browser"; buttonIDs[NativeDefinitions.KEY_MSDOS] = "DOS mode"; buttonIDs[NativeDefinitions.KEY_COFFEE] = "Coffee"; buttonIDs[NativeDefinitions.KEY_DIRECTION] = "Direction"; buttonIDs[NativeDefinitions.KEY_CYCLEWINDOWS] = "Window cycle"; buttonIDs[NativeDefinitions.KEY_MAIL] = "Mail"; buttonIDs[NativeDefinitions.KEY_BOOKMARKS] = "Book Marks"; buttonIDs[NativeDefinitions.KEY_COMPUTER] = "Computer"; buttonIDs[NativeDefinitions.KEY_BACK] = "Back"; buttonIDs[NativeDefinitions.KEY_FORWARD] = "Forward"; buttonIDs[NativeDefinitions.KEY_CLOSECD] = "Close CD"; buttonIDs[NativeDefinitions.KEY_EJECTCD] = "Eject CD"; buttonIDs[NativeDefinitions.KEY_EJECTCLOSECD] = "Eject / Close CD"; buttonIDs[NativeDefinitions.KEY_NEXTSONG] = "Next Song"; buttonIDs[NativeDefinitions.KEY_PLAYPAUSE] = "Play and Pause"; buttonIDs[NativeDefinitions.KEY_PREVIOUSSONG] = "Previous Song"; buttonIDs[NativeDefinitions.KEY_STOPCD] = "Stop CD"; buttonIDs[NativeDefinitions.KEY_RECORD] = "Record"; buttonIDs[NativeDefinitions.KEY_REWIND] = "Rewind"; buttonIDs[NativeDefinitions.KEY_PHONE] = "Phone"; buttonIDs[NativeDefinitions.KEY_ISO] = "ISO"; buttonIDs[NativeDefinitions.KEY_CONFIG] = "Config"; buttonIDs[NativeDefinitions.KEY_HOMEPAGE] = "Home"; buttonIDs[NativeDefinitions.KEY_REFRESH] = "Refresh"; buttonIDs[NativeDefinitions.KEY_EXIT] = "Exit"; buttonIDs[NativeDefinitions.KEY_MOVE] = "Move"; buttonIDs[NativeDefinitions.KEY_EDIT] = "Edit"; buttonIDs[NativeDefinitions.KEY_SCROLLUP] = "Scroll Up"; buttonIDs[NativeDefinitions.KEY_SCROLLDOWN] = "Scroll Down"; buttonIDs[NativeDefinitions.KEY_KPLEFTPAREN] = "KeyPad LH parenthesis"; buttonIDs[NativeDefinitions.KEY_KPRIGHTPAREN] = "KeyPad RH parenthesis"; buttonIDs[NativeDefinitions.KEY_INTL1] = "Intl 1"; buttonIDs[NativeDefinitions.KEY_INTL2] = "Intl 2"; buttonIDs[NativeDefinitions.KEY_INTL3] = "Intl 3"; buttonIDs[NativeDefinitions.KEY_INTL4] = "Intl 4"; buttonIDs[NativeDefinitions.KEY_INTL5] = "Intl 5"; buttonIDs[NativeDefinitions.KEY_INTL6] = "Intl 6"; buttonIDs[NativeDefinitions.KEY_INTL7] = "Intl 7"; buttonIDs[NativeDefinitions.KEY_INTL8] = "Intl 8"; buttonIDs[NativeDefinitions.KEY_INTL9] = "Intl 9"; buttonIDs[NativeDefinitions.KEY_LANG1] = "Language 1"; buttonIDs[NativeDefinitions.KEY_LANG2] = "Language 2"; buttonIDs[NativeDefinitions.KEY_LANG3] = "Language 3"; buttonIDs[NativeDefinitions.KEY_LANG4] = "Language 4"; buttonIDs[NativeDefinitions.KEY_LANG5] = "Language 5"; buttonIDs[NativeDefinitions.KEY_LANG6] = "Language 6"; buttonIDs[NativeDefinitions.KEY_LANG7] = "Language 7"; buttonIDs[NativeDefinitions.KEY_LANG8] = "Language 8"; buttonIDs[NativeDefinitions.KEY_LANG9] = "Language 9"; buttonIDs[NativeDefinitions.KEY_PLAYCD] = "Play CD"; buttonIDs[NativeDefinitions.KEY_PAUSECD] = "Pause CD"; buttonIDs[NativeDefinitions.KEY_PROG3] = "Program 3"; buttonIDs[NativeDefinitions.KEY_PROG4] = "Program 4"; buttonIDs[NativeDefinitions.KEY_SUSPEND] = "Suspend"; buttonIDs[NativeDefinitions.KEY_CLOSE] = "Close";*/ buttonIDs[NativeDefinitions.KEY_UNKNOWN] = Component.Identifier.Key.UNLABELED; /*buttonIDs[NativeDefinitions.KEY_BRIGHTNESSDOWN] = "Brightness Down"; buttonIDs[NativeDefinitions.KEY_BRIGHTNESSUP] = "Brightness Up";*/ //Misc keys buttonIDs[NativeDefinitions.BTN_0] = Component.Identifier.Button._0; buttonIDs[NativeDefinitions.BTN_1] = Component.Identifier.Button._1; buttonIDs[NativeDefinitions.BTN_2] = Component.Identifier.Button._2; buttonIDs[NativeDefinitions.BTN_3] = Component.Identifier.Button._3; buttonIDs[NativeDefinitions.BTN_4] = Component.Identifier.Button._4; buttonIDs[NativeDefinitions.BTN_5] = Component.Identifier.Button._5; buttonIDs[NativeDefinitions.BTN_6] = Component.Identifier.Button._6; buttonIDs[NativeDefinitions.BTN_7] = Component.Identifier.Button._7; buttonIDs[NativeDefinitions.BTN_8] = Component.Identifier.Button._8; buttonIDs[NativeDefinitions.BTN_9] = Component.Identifier.Button._9; // Mouse buttonIDs[NativeDefinitions.BTN_LEFT] = Component.Identifier.Button.LEFT; buttonIDs[NativeDefinitions.BTN_RIGHT] = Component.Identifier.Button.RIGHT; buttonIDs[NativeDefinitions.BTN_MIDDLE] = Component.Identifier.Button.MIDDLE; buttonIDs[NativeDefinitions.BTN_SIDE] = Component.Identifier.Button.SIDE; buttonIDs[NativeDefinitions.BTN_EXTRA] = Component.Identifier.Button.EXTRA; buttonIDs[NativeDefinitions.BTN_FORWARD] = Component.Identifier.Button.FORWARD; buttonIDs[NativeDefinitions.BTN_BACK] = Component.Identifier.Button.BACK; // Joystick buttonIDs[NativeDefinitions.BTN_TRIGGER] = Component.Identifier.Button.TRIGGER; buttonIDs[NativeDefinitions.BTN_THUMB] = Component.Identifier.Button.THUMB; buttonIDs[NativeDefinitions.BTN_THUMB2] = Component.Identifier.Button.THUMB2; buttonIDs[NativeDefinitions.BTN_TOP] = Component.Identifier.Button.TOP; buttonIDs[NativeDefinitions.BTN_TOP2] = Component.Identifier.Button.TOP2; buttonIDs[NativeDefinitions.BTN_PINKIE] = Component.Identifier.Button.PINKIE; buttonIDs[NativeDefinitions.BTN_BASE] = Component.Identifier.Button.BASE; buttonIDs[NativeDefinitions.BTN_BASE2] = Component.Identifier.Button.BASE2; buttonIDs[NativeDefinitions.BTN_BASE3] = Component.Identifier.Button.BASE3; buttonIDs[NativeDefinitions.BTN_BASE4] = Component.Identifier.Button.BASE4; buttonIDs[NativeDefinitions.BTN_BASE5] = Component.Identifier.Button.BASE5; buttonIDs[NativeDefinitions.BTN_BASE6] = Component.Identifier.Button.BASE6; buttonIDs[NativeDefinitions.BTN_DEAD] = Component.Identifier.Button.DEAD; // Gamepad buttonIDs[NativeDefinitions.BTN_A] = Component.Identifier.Button.A; buttonIDs[NativeDefinitions.BTN_B] = Component.Identifier.Button.B; buttonIDs[NativeDefinitions.BTN_C] = Component.Identifier.Button.C; buttonIDs[NativeDefinitions.BTN_X] = Component.Identifier.Button.X; buttonIDs[NativeDefinitions.BTN_Y] = Component.Identifier.Button.Y; buttonIDs[NativeDefinitions.BTN_Z] = Component.Identifier.Button.Z; buttonIDs[NativeDefinitions.BTN_TL] = Component.Identifier.Button.LEFT_THUMB; buttonIDs[NativeDefinitions.BTN_TR] = Component.Identifier.Button.RIGHT_THUMB; buttonIDs[NativeDefinitions.BTN_TL2] = Component.Identifier.Button.LEFT_THUMB2; buttonIDs[NativeDefinitions.BTN_TR2] = Component.Identifier.Button.RIGHT_THUMB2; buttonIDs[NativeDefinitions.BTN_SELECT] = Component.Identifier.Button.SELECT; buttonIDs[NativeDefinitions.BTN_MODE] = Component.Identifier.Button.MODE; buttonIDs[NativeDefinitions.BTN_THUMBL] = Component.Identifier.Button.LEFT_THUMB3; buttonIDs[NativeDefinitions.BTN_THUMBR] = Component.Identifier.Button.RIGHT_THUMB3; // Digitiser buttonIDs[NativeDefinitions.BTN_TOOL_PEN] = Component.Identifier.Button.TOOL_PEN; buttonIDs[NativeDefinitions.BTN_TOOL_RUBBER] = Component.Identifier.Button.TOOL_RUBBER; buttonIDs[NativeDefinitions.BTN_TOOL_BRUSH] = Component.Identifier.Button.TOOL_BRUSH; buttonIDs[NativeDefinitions.BTN_TOOL_PENCIL] = Component.Identifier.Button.TOOL_PENCIL; buttonIDs[NativeDefinitions.BTN_TOOL_AIRBRUSH] = Component.Identifier.Button.TOOL_AIRBRUSH; buttonIDs[NativeDefinitions.BTN_TOOL_FINGER] = Component.Identifier.Button.TOOL_FINGER; buttonIDs[NativeDefinitions.BTN_TOOL_MOUSE] = Component.Identifier.Button.TOOL_MOUSE; buttonIDs[NativeDefinitions.BTN_TOOL_LENS] = Component.Identifier.Button.TOOL_LENS; buttonIDs[NativeDefinitions.BTN_TOUCH] = Component.Identifier.Button.TOUCH; buttonIDs[NativeDefinitions.BTN_STYLUS] = Component.Identifier.Button.STYLUS; buttonIDs[NativeDefinitions.BTN_STYLUS2] = Component.Identifier.Button.STYLUS2; relAxesIDs[NativeDefinitions.REL_X] = Component.Identifier.Axis.X; relAxesIDs[NativeDefinitions.REL_Y] = Component.Identifier.Axis.Y; relAxesIDs[NativeDefinitions.REL_Z] = Component.Identifier.Axis.Z; relAxesIDs[NativeDefinitions.REL_WHEEL] = Component.Identifier.Axis.Z; // There are guesses as I have no idea what they would be used for relAxesIDs[NativeDefinitions.REL_HWHEEL] = Component.Identifier.Axis.SLIDER; relAxesIDs[NativeDefinitions.REL_DIAL] = Component.Identifier.Axis.SLIDER; relAxesIDs[NativeDefinitions.REL_MISC] = Component.Identifier.Axis.SLIDER; absAxesIDs[NativeDefinitions.ABS_X] = Component.Identifier.Axis.X; absAxesIDs[NativeDefinitions.ABS_Y] = Component.Identifier.Axis.Y; absAxesIDs[NativeDefinitions.ABS_Z] = Component.Identifier.Axis.Z; absAxesIDs[NativeDefinitions.ABS_RX] = Component.Identifier.Axis.RX; absAxesIDs[NativeDefinitions.ABS_RY] = Component.Identifier.Axis.RY; absAxesIDs[NativeDefinitions.ABS_RZ] = Component.Identifier.Axis.RZ; absAxesIDs[NativeDefinitions.ABS_THROTTLE] = Component.Identifier.Axis.SLIDER; absAxesIDs[NativeDefinitions.ABS_RUDDER] = Component.Identifier.Axis.RZ; absAxesIDs[NativeDefinitions.ABS_WHEEL] = Component.Identifier.Axis.Y; absAxesIDs[NativeDefinitions.ABS_GAS] = Component.Identifier.Axis.SLIDER; absAxesIDs[NativeDefinitions.ABS_BRAKE] = Component.Identifier.Axis.SLIDER; // Hats are done this way as they are mapped from two axis down to one absAxesIDs[NativeDefinitions.ABS_HAT0X] = Component.Identifier.Axis.POV; absAxesIDs[NativeDefinitions.ABS_HAT0Y] = Component.Identifier.Axis.POV; absAxesIDs[NativeDefinitions.ABS_HAT1X] = Component.Identifier.Axis.POV; absAxesIDs[NativeDefinitions.ABS_HAT1Y] = Component.Identifier.Axis.POV; absAxesIDs[NativeDefinitions.ABS_HAT2X] = Component.Identifier.Axis.POV; absAxesIDs[NativeDefinitions.ABS_HAT2Y] = Component.Identifier.Axis.POV; absAxesIDs[NativeDefinitions.ABS_HAT3X] = Component.Identifier.Axis.POV; absAxesIDs[NativeDefinitions.ABS_HAT3Y] = Component.Identifier.Axis.POV; // erm, yeah absAxesIDs[NativeDefinitions.ABS_PRESSURE] = null; absAxesIDs[NativeDefinitions.ABS_DISTANCE] = null; absAxesIDs[NativeDefinitions.ABS_TILT_X] = null; absAxesIDs[NativeDefinitions.ABS_TILT_Y] = null; absAxesIDs[NativeDefinitions.ABS_MISC] = null; } public final static Controller.Type guessButtonTrait(int button_code) { switch (button_code) { case NativeDefinitions.BTN_TRIGGER : case NativeDefinitions.BTN_THUMB : case NativeDefinitions.BTN_THUMB2 : case NativeDefinitions.BTN_TOP : case NativeDefinitions.BTN_TOP2 : case NativeDefinitions.BTN_PINKIE : case NativeDefinitions.BTN_BASE : case NativeDefinitions.BTN_BASE2 : case NativeDefinitions.BTN_BASE3 : case NativeDefinitions.BTN_BASE4 : case NativeDefinitions.BTN_BASE5 : case NativeDefinitions.BTN_BASE6 : case NativeDefinitions.BTN_DEAD : return Controller.Type.STICK; case NativeDefinitions.BTN_A : case NativeDefinitions.BTN_B : case NativeDefinitions.BTN_C : case NativeDefinitions.BTN_X : case NativeDefinitions.BTN_Y : case NativeDefinitions.BTN_Z : case NativeDefinitions.BTN_TL : case NativeDefinitions.BTN_TR : case NativeDefinitions.BTN_TL2 : case NativeDefinitions.BTN_TR2 : case NativeDefinitions.BTN_SELECT : case NativeDefinitions.BTN_MODE : case NativeDefinitions.BTN_THUMBL : case NativeDefinitions.BTN_THUMBR : return Controller.Type.GAMEPAD; case NativeDefinitions.BTN_0 : case NativeDefinitions.BTN_1 : case NativeDefinitions.BTN_2 : case NativeDefinitions.BTN_3 : case NativeDefinitions.BTN_4 : case NativeDefinitions.BTN_5 : case NativeDefinitions.BTN_6 : case NativeDefinitions.BTN_7 : case NativeDefinitions.BTN_8 : case NativeDefinitions.BTN_9 : return Controller.Type.UNKNOWN; case NativeDefinitions.BTN_LEFT : case NativeDefinitions.BTN_RIGHT : case NativeDefinitions.BTN_MIDDLE : case NativeDefinitions.BTN_SIDE : case NativeDefinitions.BTN_EXTRA : return Controller.Type.MOUSE; // case NativeDefinitions.KEY_RESERVED: case NativeDefinitions.KEY_ESC: case NativeDefinitions.KEY_1: case NativeDefinitions.KEY_2: case NativeDefinitions.KEY_3: case NativeDefinitions.KEY_4: case NativeDefinitions.KEY_5: case NativeDefinitions.KEY_6: case NativeDefinitions.KEY_7: case NativeDefinitions.KEY_8: case NativeDefinitions.KEY_9: case NativeDefinitions.KEY_0: case NativeDefinitions.KEY_MINUS: case NativeDefinitions.KEY_EQUAL: case NativeDefinitions.KEY_BACKSPACE: case NativeDefinitions.KEY_TAB: case NativeDefinitions.KEY_Q: case NativeDefinitions.KEY_W: case NativeDefinitions.KEY_E: case NativeDefinitions.KEY_R: case NativeDefinitions.KEY_T: case NativeDefinitions.KEY_Y: case NativeDefinitions.KEY_U: case NativeDefinitions.KEY_I: case NativeDefinitions.KEY_O: case NativeDefinitions.KEY_P: case NativeDefinitions.KEY_LEFTBRACE: case NativeDefinitions.KEY_RIGHTBRACE: case NativeDefinitions.KEY_ENTER: case NativeDefinitions.KEY_LEFTCTRL: case NativeDefinitions.KEY_A: case NativeDefinitions.KEY_S: case NativeDefinitions.KEY_D: case NativeDefinitions.KEY_F: case NativeDefinitions.KEY_G: case NativeDefinitions.KEY_H: case NativeDefinitions.KEY_J: case NativeDefinitions.KEY_K: case NativeDefinitions.KEY_L: case NativeDefinitions.KEY_SEMICOLON: case NativeDefinitions.KEY_APOSTROPHE: case NativeDefinitions.KEY_GRAVE: case NativeDefinitions.KEY_LEFTSHIFT: case NativeDefinitions.KEY_BACKSLASH: case NativeDefinitions.KEY_Z: case NativeDefinitions.KEY_X: case NativeDefinitions.KEY_C: case NativeDefinitions.KEY_V: case NativeDefinitions.KEY_B: case NativeDefinitions.KEY_N: case NativeDefinitions.KEY_M: case NativeDefinitions.KEY_COMMA: case NativeDefinitions.KEY_DOT: case NativeDefinitions.KEY_SLASH: case NativeDefinitions.KEY_RIGHTSHIFT: case NativeDefinitions.KEY_KPASTERISK: case NativeDefinitions.KEY_LEFTALT: case NativeDefinitions.KEY_SPACE: case NativeDefinitions.KEY_CAPSLOCK: case NativeDefinitions.KEY_F1: case NativeDefinitions.KEY_F2: case NativeDefinitions.KEY_F3: case NativeDefinitions.KEY_F4: case NativeDefinitions.KEY_F5: case NativeDefinitions.KEY_F6: case NativeDefinitions.KEY_F7: case NativeDefinitions.KEY_F8: case NativeDefinitions.KEY_F9: case NativeDefinitions.KEY_F10: case NativeDefinitions.KEY_NUMLOCK: case NativeDefinitions.KEY_SCROLLLOCK: case NativeDefinitions.KEY_KP7: case NativeDefinitions.KEY_KP8: case NativeDefinitions.KEY_KP9: case NativeDefinitions.KEY_KPMINUS: case NativeDefinitions.KEY_KP4: case NativeDefinitions.KEY_KP5: case NativeDefinitions.KEY_KP6: case NativeDefinitions.KEY_KPPLUS: case NativeDefinitions.KEY_KP1: case NativeDefinitions.KEY_KP2: case NativeDefinitions.KEY_KP3: case NativeDefinitions.KEY_KP0: case NativeDefinitions.KEY_KPDOT: case NativeDefinitions.KEY_ZENKAKUHANKAKU: case NativeDefinitions.KEY_102ND: case NativeDefinitions.KEY_F11: case NativeDefinitions.KEY_F12: case NativeDefinitions.KEY_RO: case NativeDefinitions.KEY_KATAKANA: case NativeDefinitions.KEY_HIRAGANA: case NativeDefinitions.KEY_HENKAN: case NativeDefinitions.KEY_KATAKANAHIRAGANA: case NativeDefinitions.KEY_MUHENKAN: case NativeDefinitions.KEY_KPJPCOMMA: case NativeDefinitions.KEY_KPENTER: case NativeDefinitions.KEY_RIGHTCTRL: case NativeDefinitions.KEY_KPSLASH: case NativeDefinitions.KEY_SYSRQ: case NativeDefinitions.KEY_RIGHTALT: case NativeDefinitions.KEY_LINEFEED: case NativeDefinitions.KEY_HOME: case NativeDefinitions.KEY_UP: case NativeDefinitions.KEY_PAGEUP: case NativeDefinitions.KEY_LEFT: case NativeDefinitions.KEY_RIGHT: case NativeDefinitions.KEY_END: case NativeDefinitions.KEY_DOWN: case NativeDefinitions.KEY_PAGEDOWN: case NativeDefinitions.KEY_INSERT: case NativeDefinitions.KEY_DELETE: case NativeDefinitions.KEY_MACRO: case NativeDefinitions.KEY_MUTE: case NativeDefinitions.KEY_VOLUMEDOWN: case NativeDefinitions.KEY_VOLUMEUP: case NativeDefinitions.KEY_POWER: case NativeDefinitions.KEY_KPEQUAL: case NativeDefinitions.KEY_KPPLUSMINUS: case NativeDefinitions.KEY_PAUSE: case NativeDefinitions.KEY_KPCOMMA: case NativeDefinitions.KEY_HANGUEL: case NativeDefinitions.KEY_HANJA: case NativeDefinitions.KEY_YEN: case NativeDefinitions.KEY_LEFTMETA: case NativeDefinitions.KEY_RIGHTMETA: case NativeDefinitions.KEY_COMPOSE: case NativeDefinitions.KEY_STOP: case NativeDefinitions.KEY_AGAIN: case NativeDefinitions.KEY_PROPS: case NativeDefinitions.KEY_UNDO: case NativeDefinitions.KEY_FRONT: case NativeDefinitions.KEY_COPY: case NativeDefinitions.KEY_OPEN: case NativeDefinitions.KEY_PASTE: case NativeDefinitions.KEY_FIND: case NativeDefinitions.KEY_CUT: case NativeDefinitions.KEY_HELP: case NativeDefinitions.KEY_MENU: case NativeDefinitions.KEY_CALC: case NativeDefinitions.KEY_SETUP: case NativeDefinitions.KEY_SLEEP: case NativeDefinitions.KEY_WAKEUP: case NativeDefinitions.KEY_FILE: case NativeDefinitions.KEY_SENDFILE: case NativeDefinitions.KEY_DELETEFILE: case NativeDefinitions.KEY_XFER: case NativeDefinitions.KEY_PROG1: case NativeDefinitions.KEY_PROG2: case NativeDefinitions.KEY_WWW: case NativeDefinitions.KEY_MSDOS: case NativeDefinitions.KEY_COFFEE: case NativeDefinitions.KEY_DIRECTION: case NativeDefinitions.KEY_CYCLEWINDOWS: case NativeDefinitions.KEY_MAIL: case NativeDefinitions.KEY_BOOKMARKS: case NativeDefinitions.KEY_COMPUTER: case NativeDefinitions.KEY_BACK: case NativeDefinitions.KEY_FORWARD: case NativeDefinitions.KEY_CLOSECD: case NativeDefinitions.KEY_EJECTCD: case NativeDefinitions.KEY_EJECTCLOSECD: case NativeDefinitions.KEY_NEXTSONG: case NativeDefinitions.KEY_PLAYPAUSE: case NativeDefinitions.KEY_PREVIOUSSONG: case NativeDefinitions.KEY_STOPCD: case NativeDefinitions.KEY_RECORD: case NativeDefinitions.KEY_REWIND: case NativeDefinitions.KEY_PHONE: case NativeDefinitions.KEY_ISO: case NativeDefinitions.KEY_CONFIG: case NativeDefinitions.KEY_HOMEPAGE: case NativeDefinitions.KEY_REFRESH: case NativeDefinitions.KEY_EXIT: case NativeDefinitions.KEY_MOVE: case NativeDefinitions.KEY_EDIT: case NativeDefinitions.KEY_SCROLLUP: case NativeDefinitions.KEY_SCROLLDOWN: case NativeDefinitions.KEY_KPLEFTPAREN: case NativeDefinitions.KEY_KPRIGHTPAREN: case NativeDefinitions.KEY_F13: case NativeDefinitions.KEY_F14: case NativeDefinitions.KEY_F15: case NativeDefinitions.KEY_F16: case NativeDefinitions.KEY_F17: case NativeDefinitions.KEY_F18: case NativeDefinitions.KEY_F19: case NativeDefinitions.KEY_F20: case NativeDefinitions.KEY_F21: case NativeDefinitions.KEY_F22: case NativeDefinitions.KEY_F23: case NativeDefinitions.KEY_F24: case NativeDefinitions.KEY_PLAYCD: case NativeDefinitions.KEY_PAUSECD: case NativeDefinitions.KEY_PROG3: case NativeDefinitions.KEY_PROG4: case NativeDefinitions.KEY_SUSPEND: case NativeDefinitions.KEY_CLOSE: case NativeDefinitions.KEY_PLAY: case NativeDefinitions.KEY_FASTFORWARD: case NativeDefinitions.KEY_BASSBOOST: case NativeDefinitions.KEY_PRINT: case NativeDefinitions.KEY_HP: case NativeDefinitions.KEY_CAMERA: case NativeDefinitions.KEY_SOUND: case NativeDefinitions.KEY_QUESTION: case NativeDefinitions.KEY_EMAIL: case NativeDefinitions.KEY_CHAT: case NativeDefinitions.KEY_SEARCH: case NativeDefinitions.KEY_CONNECT: case NativeDefinitions.KEY_FINANCE: case NativeDefinitions.KEY_SPORT: case NativeDefinitions.KEY_SHOP: case NativeDefinitions.KEY_ALTERASE: case NativeDefinitions.KEY_CANCEL: case NativeDefinitions.KEY_BRIGHTNESSDOWN: case NativeDefinitions.KEY_BRIGHTNESSUP: case NativeDefinitions.KEY_MEDIA: case NativeDefinitions.KEY_SWITCHVIDEOMODE: case NativeDefinitions.KEY_KBDILLUMTOGGLE: case NativeDefinitions.KEY_KBDILLUMDOWN: case NativeDefinitions.KEY_KBDILLUMUP: // case NativeDefinitions.KEY_UNKNOWN: case NativeDefinitions.KEY_OK: case NativeDefinitions.KEY_SELECT: case NativeDefinitions.KEY_GOTO: case NativeDefinitions.KEY_CLEAR: case NativeDefinitions.KEY_POWER2: case NativeDefinitions.KEY_OPTION: case NativeDefinitions.KEY_INFO: case NativeDefinitions.KEY_TIME: case NativeDefinitions.KEY_VENDOR: case NativeDefinitions.KEY_ARCHIVE: case NativeDefinitions.KEY_PROGRAM: case NativeDefinitions.KEY_CHANNEL: case NativeDefinitions.KEY_FAVORITES: case NativeDefinitions.KEY_EPG: case NativeDefinitions.KEY_PVR: case NativeDefinitions.KEY_MHP: case NativeDefinitions.KEY_LANGUAGE: case NativeDefinitions.KEY_TITLE: case NativeDefinitions.KEY_SUBTITLE: case NativeDefinitions.KEY_ANGLE: case NativeDefinitions.KEY_ZOOM: case NativeDefinitions.KEY_MODE: case NativeDefinitions.KEY_KEYBOARD: case NativeDefinitions.KEY_SCREEN: case NativeDefinitions.KEY_PC: case NativeDefinitions.KEY_TV: case NativeDefinitions.KEY_TV2: case NativeDefinitions.KEY_VCR: case NativeDefinitions.KEY_VCR2: case NativeDefinitions.KEY_SAT: case NativeDefinitions.KEY_SAT2: case NativeDefinitions.KEY_CD: case NativeDefinitions.KEY_TAPE: case NativeDefinitions.KEY_RADIO: case NativeDefinitions.KEY_TUNER: case NativeDefinitions.KEY_PLAYER: case NativeDefinitions.KEY_TEXT: case NativeDefinitions.KEY_DVD: case NativeDefinitions.KEY_AUX: case NativeDefinitions.KEY_MP3: case NativeDefinitions.KEY_AUDIO: case NativeDefinitions.KEY_VIDEO: case NativeDefinitions.KEY_DIRECTORY: case NativeDefinitions.KEY_LIST: case NativeDefinitions.KEY_MEMO: case NativeDefinitions.KEY_CALENDAR: case NativeDefinitions.KEY_RED: case NativeDefinitions.KEY_GREEN: case NativeDefinitions.KEY_YELLOW: case NativeDefinitions.KEY_BLUE: case NativeDefinitions.KEY_CHANNELUP: case NativeDefinitions.KEY_CHANNELDOWN: case NativeDefinitions.KEY_FIRST: case NativeDefinitions.KEY_LAST: case NativeDefinitions.KEY_AB: case NativeDefinitions.KEY_NEXT: case NativeDefinitions.KEY_RESTART: case NativeDefinitions.KEY_SLOW: case NativeDefinitions.KEY_SHUFFLE: case NativeDefinitions.KEY_BREAK: case NativeDefinitions.KEY_PREVIOUS: case NativeDefinitions.KEY_DIGITS: case NativeDefinitions.KEY_TEEN: case NativeDefinitions.KEY_TWEN: case NativeDefinitions.KEY_DEL_EOL: case NativeDefinitions.KEY_DEL_EOS: case NativeDefinitions.KEY_INS_LINE: case NativeDefinitions.KEY_DEL_LINE: case NativeDefinitions.KEY_FN: case NativeDefinitions.KEY_FN_ESC: case NativeDefinitions.KEY_FN_F1: case NativeDefinitions.KEY_FN_F2: case NativeDefinitions.KEY_FN_F3: case NativeDefinitions.KEY_FN_F4: case NativeDefinitions.KEY_FN_F5: case NativeDefinitions.KEY_FN_F6: case NativeDefinitions.KEY_FN_F7: case NativeDefinitions.KEY_FN_F8: case NativeDefinitions.KEY_FN_F9: case NativeDefinitions.KEY_FN_F10: case NativeDefinitions.KEY_FN_F11: case NativeDefinitions.KEY_FN_F12: case NativeDefinitions.KEY_FN_1: case NativeDefinitions.KEY_FN_2: case NativeDefinitions.KEY_FN_D: case NativeDefinitions.KEY_FN_E: case NativeDefinitions.KEY_FN_F: case NativeDefinitions.KEY_FN_S: case NativeDefinitions.KEY_FN_B: return Controller.Type.KEYBOARD; default: return Controller.Type.UNKNOWN; } } /** Return port type from a native port type int id * @param nativeid The native port type * @return The jinput port type */ public static Controller.PortType getPortType(int nativeid) { // Have to do this one this way as there is no BUS_MAX switch (nativeid) { case NativeDefinitions.BUS_GAMEPORT : return Controller.PortType.GAME; case NativeDefinitions.BUS_I8042 : return Controller.PortType.I8042; case NativeDefinitions.BUS_PARPORT : return Controller.PortType.PARALLEL; case NativeDefinitions.BUS_RS232 : return Controller.PortType.SERIAL; case NativeDefinitions.BUS_USB : return Controller.PortType.USB; default: return Controller.PortType.UNKNOWN; } } /** Gets the identifier for a relative axis * @param nativeID The axis type ID * @return The jinput id */ public static Component.Identifier getRelAxisID(int nativeID) { Component.Identifier retval = INSTANCE.relAxesIDs[nativeID]; if(retval == null) { retval = Component.Identifier.Axis.SLIDER_VELOCITY; INSTANCE.relAxesIDs[nativeID] = retval; } return retval; } /** Gets the identifier for a absolute axis * @param nativeID The native axis type id * @return The jinput id */ public static Component.Identifier getAbsAxisID(int nativeID) { Component.Identifier retval = null; try { retval = INSTANCE.absAxesIDs[nativeID]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("INSTANCE.absAxesIDs is only " + INSTANCE.absAxesIDs.length + " long, so " + nativeID + " not contained"); //ignore, pretend it was null } if(retval == null) { retval = Component.Identifier.Axis.SLIDER; INSTANCE.absAxesIDs[nativeID] = retval; } return retval; } /** Gets the identifier for a button * @param nativeID The native button type id * @return The jinput id */ public static Component.Identifier getButtonID(int nativeID) { - Component.Identifier retval = INSTANCE.buttonIDs[nativeID]; + Component.Identifier retval = null; + if (nativeID >= 0 && nativeID < INSTANCE.buttonIDs.length) + retval = INSTANCE.buttonIDs[nativeID]; if(retval == null) { retval = Component.Identifier.Key.UNKNOWN; INSTANCE.buttonIDs[nativeID] = retval; } return retval; } }
true
false
null
null
diff --git a/src/main/java/hudson/remoting/UserRequest.java b/src/main/java/hudson/remoting/UserRequest.java index 51b5f527..d4da1b7c 100644 --- a/src/main/java/hudson/remoting/UserRequest.java +++ b/src/main/java/hudson/remoting/UserRequest.java @@ -1,147 +1,149 @@ package hudson.remoting; import hudson.remoting.RemoteClassLoader.IClassLoader; import hudson.remoting.ExportTable.ExportList; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.NotSerializableException; /** * {@link Request} that can take {@link Callable} whose actual implementation * may not be known to the remote system in advance. * * <p> * This code assumes that the {@link Callable} object and all reachable code * are loaded by a single classloader. * * @author Kohsuke Kawaguchi */ final class UserRequest<RSP,EXC extends Throwable> extends Request<UserResponse<RSP,EXC>,EXC> { private final byte[] request; private final IClassLoader classLoaderProxy; private final String toString; /** * Objects exported by the request. This value will remain local * and won't be sent over to the remote side. */ private transient final ExportList exports; public UserRequest(Channel local, Callable<?,EXC> c) throws IOException { exports = local.startExportRecording(); try { request = serialize(c,local); } finally { exports.stopRecording(); } this.toString = c.toString(); ClassLoader cl = getClassLoader(c); classLoaderProxy = RemoteClassLoader.export(cl,local); } /*package*/ static ClassLoader getClassLoader(Callable<?,?> c) { ClassLoader cl = c.getClass().getClassLoader(); if(c instanceof DelegatingCallable) cl = ((DelegatingCallable)c).getClassLoader(); return cl; } protected UserResponse<RSP,EXC> perform(Channel channel) throws EXC { try { ClassLoader cl = channel.importedClassLoaders.get(classLoaderProxy); RSP r = null; Channel oldc = Channel.setCurrent(channel); try { Object o = new ObjectInputStreamEx(new ByteArrayInputStream(request), cl).readObject(); Callable<RSP,EXC> callable = (Callable<RSP,EXC>)o; ClassLoader old = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(cl); // execute the service try { r = callable.call(); } finally { Thread.currentThread().setContextClassLoader(old); } } finally { Channel.setCurrent(oldc); } return new UserResponse<RSP,EXC>(serialize(r,channel),false); } catch (Throwable e) { // propagate this to the calling process try { byte[] response; try { response = serialize(e, channel); } catch (NotSerializableException x) { // perhaps the thrown runtime exception is of time we can't handle response = serialize(new ProxyException(e), channel); } return new UserResponse<RSP,EXC>(response,true); } catch (IOException x) { // throw it as a lower-level exception throw (EXC)x; } } } private byte[] serialize(Object o, Channel localChannel) throws IOException { Channel old = Channel.setCurrent(localChannel); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); new ObjectOutputStream(baos).writeObject(o); return baos.toByteArray(); } catch( NotSerializableException e ) { IOException x = new IOException("Unable to serialize " + o); x.initCause(e); throw x; } finally { Channel.setCurrent(old); } } public void releaseExports() { exports.release(); } public String toString() { return "UserRequest:"+toString; } + + private static final long serialVersionUID = 1L; } final class UserResponse<RSP,EXC extends Throwable> implements Serializable { private final byte[] response; private final boolean isException; public UserResponse(byte[] response, boolean isException) { this.response = response; this.isException = isException; } /** * Deserializes the response byte stream into an object. */ public RSP retrieve(Channel channel, ClassLoader cl) throws IOException, ClassNotFoundException, EXC { Channel old = Channel.setCurrent(channel); try { Object o = new ObjectInputStreamEx(new ByteArrayInputStream(response), cl).readObject(); if(isException) throw (EXC)o; else return (RSP) o; } finally { Channel.setCurrent(old); } } private static final long serialVersionUID = 1L; }
true
false
null
null
diff --git a/src/cz/quinix/condroid/abstracts/CondroidListActivity.java b/src/cz/quinix/condroid/abstracts/CondroidListActivity.java index cf3b077..ca18d39 100644 --- a/src/cz/quinix/condroid/abstracts/CondroidListActivity.java +++ b/src/cz/quinix/condroid/abstracts/CondroidListActivity.java @@ -1,92 +1,93 @@ package cz.quinix.condroid.abstracts; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; +import java.util.TimeZone; import android.app.ListActivity; import android.content.Intent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import cz.quinix.condroid.R; import cz.quinix.condroid.database.DataProvider; import cz.quinix.condroid.model.Annotation; import cz.quinix.condroid.ui.AboutActivity; public abstract class CondroidListActivity extends ListActivity { protected DataProvider provider; public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflanter = this.getMenuInflater(); inflanter.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about: Intent intent2 = new Intent(this, AboutActivity.class); this.startActivity(intent2); return true; default: return super.onOptionsItemSelected(item); } } private static DateFormat todayFormat = new SimpleDateFormat("HH:mm"); private static DateFormat dayFormat = new SimpleDateFormat( "EE dd.MM. HH:mm", new Locale("cs","CZ")); public View inflanteAnnotation(View v, Annotation annotation) { TextView tw = (TextView) v.findViewById(R.id.alTitle); if (tw != null) { tw.setText(annotation.getTitle()); } TextView tw2 = (TextView) v.findViewById(R.id.alSecondLine); if (tw != null) { tw2.setText(annotation.getAuthor()); } TextView tw3 = (TextView) v.findViewById(R.id.alThirdLine); if (tw2 != null) { String date = ""; if (annotation.getStartTime() != null && annotation.getEndTime() != null) { date = ", " + formatDate(annotation.getStartTime()) + " - " + todayFormat.format(annotation.getEndTime()); } tw3.setText(provider.getProgramLine(annotation.getLid()).getName() + ", "+ annotation.getType() + date); } return v; } private String formatDate(Date date) { - Calendar today = Calendar.getInstance(new Locale("cs", "CZ")); + Calendar today = Calendar.getInstance(TimeZone.getTimeZone("Europe/Prague"), new Locale("cs", "CZ")); today.setTime(new Date()); Calendar compared = Calendar.getInstance(); compared.setTime(date); if (compared.get(Calendar.YEAR) == today.get(Calendar.YEAR) && compared.get(Calendar.MONTH) == today.get(Calendar.MONTH) && compared.get(Calendar.DAY_OF_MONTH) == today.get(Calendar.DAY_OF_MONTH)) { //its today return todayFormat.format(date); } else { return dayFormat.format(date); } } } diff --git a/src/cz/quinix/condroid/database/DataProvider.java b/src/cz/quinix/condroid/database/DataProvider.java index e5b074b..7da4ee9 100644 --- a/src/cz/quinix/condroid/database/DataProvider.java +++ b/src/cz/quinix/condroid/database/DataProvider.java @@ -1,208 +1,208 @@ package cz.quinix.condroid.database; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; import cz.quinix.condroid.model.Annotation; import cz.quinix.condroid.model.Convention; import cz.quinix.condroid.model.ProgramLine; import cz.quinix.condroid.ui.WelcomeActivity; public class DataProvider { public static String AUTHORITY = "cz.quinix.condroid.database.DataProvider"; public static Uri CONTENT_URI = Uri.parse("content://"+ AUTHORITY + "/database"); public static int ITEMS_PER_PAGE = 40; private CondroidDatabase mDatabase; private Convention con; private static volatile DataProvider instance; private static HashMap<Integer, String> programLines = null; private DataProvider(Context context) { mDatabase = new CondroidDatabase(context); } public static DataProvider getInstance(Context context) { if(instance == null) { synchronized (CondroidDatabase.class) { if(instance == null) { instance = new DataProvider(context); } } } return instance; } public boolean hasData() { return !mDatabase.isEmpty(); } public void setConvention(Convention convention) { con = convention; } public void insert(List<Annotation> result) { if(!mDatabase.isEmpty()) { mDatabase.purge(); programLines = null; } try { mDatabase.insert(con, result); } catch (Exception ex) { Log.w(WelcomeActivity.TAG, ex); mDatabase.purge(); } } public List<Annotation> getAnnotations(String condition, int page) { List<Annotation> ret = new ArrayList<Annotation>(); Cursor c = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, condition, null, "startTime ASC, lid ASC, title ASC", (page*ITEMS_PER_PAGE) + ","+ ITEMS_PER_PAGE); while(c.moveToNext()) { ret.add(readAnnotation(c)); } return ret; } public ProgramLine getProgramLine (int lid) { ProgramLine pl = new ProgramLine(); if(programLines == null) { this.loadProgramLines(); } if(programLines.containsKey(lid)) { pl.setLid(lid); pl.setName(programLines.get(lid)); } return pl; } public HashMap<Integer, String> getProgramLines() { if(programLines == null) { this.loadProgramLines(); } return programLines; } private void loadProgramLines() { programLines = new HashMap<Integer, String>(); Cursor c = this.mDatabase.query(CondroidDatabase.LINE_TABLE, null, null, null, "title ASC", null); while(c.moveToNext()) { programLines.put(c.getInt(c.getColumnIndex("id")), c.getString(c.getColumnIndex("title"))); } } public List<Date> getDates() { Cursor c = this.mDatabase.query("SELECT DISTINCT STRFTIME('%Y-%m-%d',startTime) AS sDate FROM "+CondroidDatabase.ANNOTATION_TABLE+" ORDER by STRFTIME('%Y-%m-%d',startTime) ASC"); List<Date> map = new ArrayList<Date>(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); while(c.moveToNext()) { try { map.add(df.parse(c.getString(c.getColumnIndex("sDate")))); } catch (ParseException e) { Log.w("DB", e); } } return map; } public List<Annotation> getRunningAndNext() { List<Annotation> l = new ArrayList<Annotation>(); - Cursor c = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, "startTime < DATETIME('now') AND endTime > DATETIME('now')", null, "startTime DESC", null, false, null); + Cursor c = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, "startTime < DATETIME('now','localtime') AND endTime > DATETIME('now','localtime')", null, "startTime DESC", null, false, null); while (c.moveToNext()) { if(c.isFirst()) { Annotation a = new Annotation(); a.setTitle("break"); a.setStartTime(c.getString(c.getColumnIndex("startTime"))); a.setAnnotation("now"); l.add(a); } Annotation annotation = readAnnotation(c); l.add(annotation); } - Cursor c2 = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, "startTime > DATETIME('now')", null, "startTime ASC, lid ASC", "0,100", false, null); + Cursor c2 = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, "startTime > DATETIME('now','localtime')", null, "startTime ASC, lid ASC", "0,100", false, null); String previous = ""; int hours = 0; while (c2.moveToNext()) { if (!previous.equals(c2.getString(c2.getColumnIndex("startTime")))) { if(hours++ > 5) break; Annotation a = new Annotation(); a.setTitle("break"); a.setStartTime(c2.getString(c2.getColumnIndex("startTime"))); l.add(a); previous = c2.getString(c2.getColumnIndex("startTime")); } Annotation annotation = readAnnotation(c2); l.add(annotation); } return l; } private Annotation readAnnotation(Cursor c) { Annotation annotation = new Annotation(); annotation.setPid(c.getString(c.getColumnIndex("pid"))); annotation.setTitle(c.getString(c.getColumnIndex("title"))); annotation.setAnnotation(c.getString(c.getColumnIndex("annotation"))); annotation.setAuthor(c.getString(c.getColumnIndex("talker"))); annotation.setEndTime(c.getString(c.getColumnIndex("endTime"))); annotation.setLength(c.getString(c.getColumnIndex("length"))); annotation.setLid(c.getInt(c.getColumnIndex("lid"))); annotation.setStartTime(c.getString(c.getColumnIndex("startTime"))); annotation.setType(c.getString(c.getColumnIndex("type"))); return annotation; } public Convention getCon() { if (this.con != null) { return con; } Cursor c = this.mDatabase.query(CondroidDatabase.CON_TABLE, null, null, null, null, null); Convention co = new Convention(); while (c.moveToNext()) { co.setCid(c.getInt(c.getColumnIndex("id"))); co.setDataUrl(c.getString(c.getColumnIndex("dataUrl"))); co.setDate(c.getString(c.getColumnIndex("date"))); co.setIconUrl(c.getString(c.getColumnIndex("iconUrl"))); co.setName(c.getString(c.getColumnIndex("name"))); co.setMessage(c.getString(c.getColumnIndex("message"))); } this.con = co; return co; } } diff --git a/src/cz/quinix/condroid/model/Annotation.java b/src/cz/quinix/condroid/model/Annotation.java index ee08d7e..ca65fba 100644 --- a/src/cz/quinix/condroid/model/Annotation.java +++ b/src/cz/quinix/condroid/model/Annotation.java @@ -1,147 +1,153 @@ package cz.quinix.condroid.model; import java.io.Serializable; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; import android.content.ContentValues; +import android.text.StaticLayout; import cz.quinix.condroid.abstracts.DBInsertable; public class Annotation implements Serializable, DBInsertable { /** * */ private static final long serialVersionUID = 29890241539328629L; private String pid; private String talker; private String title; private String length; private String type; private String programLine; private String annotation =""; private Date startTime; private Date endTime; - + static DateFormat df; private int lid; - static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + static { + df = new SimpleDateFormat("yyyy-MM-dd HH:mm", new Locale("cs", "CZ")); + df.setTimeZone(TimeZone.getDefault()); + } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public void setStartTime(String startTime) { this.startTime = parseDate(startTime); } public void setEndTime(String endTime) { this.endTime = parseDate(endTime); } private Date parseDate(String date) { if (date == null || date.equals("")) return null; try { return df.parse(date); } catch (ParseException e) { return null; } } public String getPid() { return pid; } public String getAuthor() { return talker; } public String getTitle() { return title; } public String getLength() { return length; } public String getType() { return type; } /** * Use only during processing new XML! * @return */ public String getProgramLine() { return programLine; } public String getAnnotation() { return annotation; } public void setPid(String pid) { this.pid = pid.trim(); } public void setAuthor(String talker) { this.talker = talker.trim(); } public void setTitle(String title) { this.title = title.trim(); } public void setLength(String length) { this.length = length.trim(); } public void setType(String type) { this.type = type.trim(); } public void setProgramLine(String programLine) { this.programLine = programLine.trim(); } public void setAnnotation(String annotation) { this.annotation = annotation.trim(); } public ContentValues getContentValues() { ContentValues ret = new ContentValues(); ret.put("pid", this.pid); ret.put("talker", talker); ret.put("title", title); ret.put("length", length); ret.put("type", type); ret.put("lid", lid); ret.put("annotation", annotation); if(startTime != null) { ret.put("startTime", df.format(startTime)); } if(endTime != null) { ret.put("endTime", df.format(endTime)); } return ret; } public void setLid(Integer integer) { lid = integer.intValue(); } public int getLid() { return lid; } }
false
false
null
null
diff --git a/api/src/main/java/org/openmrs/module/dataintegrity/db/hibernate/ResultDataType.java b/api/src/main/java/org/openmrs/module/dataintegrity/db/hibernate/ResultDataType.java index 88f37e5..0c27246 100644 --- a/api/src/main/java/org/openmrs/module/dataintegrity/db/hibernate/ResultDataType.java +++ b/api/src/main/java/org/openmrs/module/dataintegrity/db/hibernate/ResultDataType.java @@ -1,152 +1,152 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.dataintegrity.db.hibernate; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.usertype.UserType; import org.openmrs.module.dataintegrity.IntegrityCheckUtil; import org.openmrs.module.dataintegrity.QueryResult; /** * Hibernate's Custom Type for {@link QueryResult} */ public class ResultDataType implements UserType, Serializable { private static final long serialVersionUID = 1L; private static final int[] TYPES = new int[] { Types.VARCHAR }; /** * @see org.hibernate.usertype.UserType#returnedClass() */ public Class returnedClass() { return QueryResult.class; } /** * @see org.hibernate.usertype.UserType#sqlTypes() */ public int[] sqlTypes() { return TYPES; } /** * @see org.hibernate.usertype.UserType#isMutable() */ public boolean isMutable() { return true; } /** * @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object) */ public Object deepCopy(Object value) throws HibernateException { return new QueryResult((QueryResult) value); } /** * @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, * java.lang.Object) */ public Object assemble(Serializable cached, Object owner) throws HibernateException { return deepCopy(cached); } /** * @see org.hibernate.usertype.UserType#disassemble(java.lang.Object) */ public Serializable disassemble(Object value) throws HibernateException { return (Serializable) deepCopy(value); } /** * @see org.hibernate.usertype.UserType#replace(java.lang.Object, * java.lang.Object, java.lang.Object) */ public Object replace(Object original, Object target, Object owner) throws HibernateException { return deepCopy(original); } /** * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, * java.lang.String[], java.lang.Object) * @see QueryResult#valueOf(String) */ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { - String value = (String) Hibernate.STRING.nullSafeGet(rs, names[0]); + String value = (String) rs.getString(names[0]); if (value != null) return QueryResult.valueOf(value); else return null; } /** * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, * java.lang.Object, int) * @see IntegrityCheckUtil#serialize(LocalizedString) */ public void nullSafeSet(PreparedStatement ps, Object value, int index) throws HibernateException, SQLException { if (value != null) { if (value instanceof java.lang.String) { // only in query mode(e.g., Expression.like('queryResult', // value)), the type of value will be String // use this tricky here, in order to support Hibernate's // easy-reading query mode, such as // Expression.like(propertyName, value) ps.setString(index, value.toString()); } else { // only when create/update an OpenmrsMetadata object, the type // of value will be LocalizedString ps.setString(index, IntegrityCheckUtil.serializeResult((QueryResult) value)); } } else { ps.setString(index, null); } } /** * @see org.hibernate.usertype.UserType#equals(java.lang.Object, * java.lang.Object) */ public boolean equals(Object a, Object b) throws HibernateException { if (a == b) return true; if (a != null && b != null) { if (!(a instanceof QueryResult) || !(b instanceof QueryResult)) return false; else return a.equals(b); } return false; } /** * @see org.hibernate.usertype.UserType#hashCode(java.lang.Object) */ public int hashCode(Object x) throws HibernateException { return x.hashCode(); } } \ No newline at end of file
true
false
null
null
diff --git a/achartengine/src/org/achartengine/GraphicalView.java b/achartengine/src/org/achartengine/GraphicalView.java index 7e7ef18..7d73128 100644 --- a/achartengine/src/org/achartengine/GraphicalView.java +++ b/achartengine/src/org/achartengine/GraphicalView.java @@ -1,329 +1,335 @@ /** * Copyright (C) 2009, 2010 SC 4ViewSoft SRL * * 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.achartengine; import org.achartengine.chart.AbstractChart; import org.achartengine.chart.RoundChart; import org.achartengine.chart.XYChart; import org.achartengine.model.Point; import org.achartengine.model.SeriesSelection; import org.achartengine.renderer.DefaultRenderer; import org.achartengine.renderer.XYMultipleSeriesRenderer; import org.achartengine.tools.FitZoom; import org.achartengine.tools.PanListener; import org.achartengine.tools.Zoom; import org.achartengine.tools.ZoomListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.os.Build; import android.os.Handler; import android.view.MotionEvent; import android.view.View; /** * The view that encapsulates the graphical chart. */ public class GraphicalView extends View { /** The chart to be drawn. */ private AbstractChart mChart; /** The chart renderer. */ private DefaultRenderer mRenderer; /** The view bounds. */ private Rect mRect = new Rect(); /** The user interface thread handler. */ private Handler mHandler; /** The zoom buttons rectangle. */ private RectF mZoomR = new RectF(); /** The zoom in icon. */ private Bitmap zoomInImage; /** The zoom out icon. */ private Bitmap zoomOutImage; /** The fit zoom icon. */ private Bitmap fitZoomImage; /** The zoom area size. */ private int zoomSize = 50; /** The zoom buttons background color. */ private static final int ZOOM_BUTTONS_COLOR = Color.argb(175, 150, 150, 150); /** The zoom in tool. */ private Zoom mZoomIn; /** The zoom out tool. */ private Zoom mZoomOut; /** The fit zoom tool. */ private FitZoom mFitZoom; /** The paint to be used when drawing the chart. */ private Paint mPaint = new Paint(); /** The touch handler. */ private ITouchHandler mTouchHandler; /** The old x coordinate. */ private float oldX; /** The old y coordinate. */ private float oldY; /** * Creates a new graphical view. * * @param context the context * @param chart the chart to be drawn */ public GraphicalView(Context context, AbstractChart chart) { super(context); mChart = chart; mHandler = new Handler(); if (mChart instanceof XYChart) { mRenderer = ((XYChart) mChart).getRenderer(); } else { mRenderer = ((RoundChart) mChart).getRenderer(); } if (mRenderer.isZoomButtonsVisible()) { zoomInImage = BitmapFactory.decodeStream(GraphicalView.class .getResourceAsStream("image/zoom_in.png")); zoomOutImage = BitmapFactory.decodeStream(GraphicalView.class .getResourceAsStream("image/zoom_out.png")); fitZoomImage = BitmapFactory.decodeStream(GraphicalView.class .getResourceAsStream("image/zoom-1.png")); } if (mRenderer instanceof XYMultipleSeriesRenderer && ((XYMultipleSeriesRenderer) mRenderer).getMarginsColor() == XYMultipleSeriesRenderer.NO_COLOR) { ((XYMultipleSeriesRenderer) mRenderer).setMarginsColor(mPaint.getColor()); } if (mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible() || mRenderer.isExternalZoomEnabled()) { mZoomIn = new Zoom(mChart, true, mRenderer.getZoomRate()); mZoomOut = new Zoom(mChart, false, mRenderer.getZoomRate()); mFitZoom = new FitZoom(mChart); } int version = 7; try { version = Integer.valueOf(Build.VERSION.SDK); } catch (Exception e) { // do nothing } if (version < 7) { mTouchHandler = new TouchHandlerOld(this, mChart); } else { mTouchHandler = new TouchHandler(this, mChart); } } /** * Returns the current series selection object. * * @return the series selection */ public SeriesSelection getCurrentSeriesAndPoint() { return mChart.getSeriesAndPointForScreenCoordinate(new Point(oldX, oldY)); } /** * Transforms the currently selected screen point to a real point. * * @param scale the scale * @return the currently selected real point */ public double[] toRealPoint(int scale) { if (mChart instanceof XYChart) { XYChart chart = (XYChart) mChart; return chart.toRealPoint(oldX, oldY, scale); } return null; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.getClipBounds(mRect); int top = mRect.top; int left = mRect.left; int width = mRect.width(); int height = mRect.height(); + if (mRenderer.isInScroll()) { + top = 0; + left = 0; + width = getMeasuredWidth(); + height = getMeasuredHeight(); + } mChart.draw(canvas, left, top, width, height, mPaint); if (mRenderer != null && mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible()) { mPaint.setColor(ZOOM_BUTTONS_COLOR); zoomSize = Math.max(zoomSize, Math.min(width, height) / 7); mZoomR.set(left + width - zoomSize * 3, top + height - zoomSize * 0.775f, left + width, top + height); canvas.drawRoundRect(mZoomR, zoomSize / 3, zoomSize / 3, mPaint); float buttonY = top + height - zoomSize * 0.625f; canvas.drawBitmap(zoomInImage, left + width - zoomSize * 2.75f, buttonY, null); canvas.drawBitmap(zoomOutImage, left + width - zoomSize * 1.75f, buttonY, null); canvas.drawBitmap(fitZoomImage, left + width - zoomSize * 0.75f, buttonY, null); } } /** * Sets the zoom rate. * * @param rate the zoom rate */ public void setZoomRate(float rate) { if (mZoomIn != null && mZoomOut != null) { mZoomIn.setZoomRate(rate); mZoomOut.setZoomRate(rate); } } /** * Do a chart zoom in. */ public void zoomIn() { if (mZoomIn != null) { mZoomIn.apply(); repaint(); } } /** * Do a chart zoom out. */ public void zoomOut() { if (mZoomOut != null) { mZoomOut.apply(); repaint(); } } /** * Do a chart zoom reset / fit zoom. */ public void zoomReset() { if (mFitZoom != null) { mFitZoom.apply(); mZoomIn.notifyZoomResetListeners(); repaint(); } } /** * Adds a new zoom listener. * * @param listener zoom listener */ public void addZoomListener(ZoomListener listener, boolean onButtons, boolean onPinch) { if (onButtons) { if (mZoomIn != null) { mZoomIn.addZoomListener(listener); mZoomOut.addZoomListener(listener); } if (onPinch) { mTouchHandler.addZoomListener(listener); } } } /** * Removes a zoom listener. * * @param listener zoom listener */ public synchronized void removeZoomListener(ZoomListener listener) { if (mZoomIn != null) { mZoomIn.removeZoomListener(listener); mZoomOut.removeZoomListener(listener); } mTouchHandler.removeZoomListener(listener); } /** * Adds a new pan listener. * * @param listener pan listener */ public void addPanListener(PanListener listener) { mTouchHandler.addPanListener(listener); } /** * Removes a pan listener. * * @param listener pan listener */ public void removePanListener(PanListener listener) { mTouchHandler.removePanListener(listener); } protected RectF getZoomRectangle() { return mZoomR; } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { // save the x and y so they can be used in the click and long press // listeners oldX = event.getX(); oldY = event.getY(); } if (mRenderer != null && (mRenderer.isPanEnabled() || mRenderer.isZoomEnabled())) { if (mTouchHandler.handleTouch(event)) { return true; } } return super.onTouchEvent(event); } /** * Schedule a view content repaint. */ public void repaint() { mHandler.post(new Runnable() { public void run() { invalidate(); } }); } /** * Schedule a view content repaint, in the specified rectangle area. * * @param left the left position of the area to be repainted * @param top the top position of the area to be repainted * @param right the right position of the area to be repainted * @param bottom the bottom position of the area to be repainted */ public void repaint(final int left, final int top, final int right, final int bottom) { mHandler.post(new Runnable() { public void run() { invalidate(left, top, right, bottom); } }); } /** * Saves the content of the graphical view to a bitmap. * * @return the bitmap */ public Bitmap toBitmap() { setDrawingCacheEnabled(false); if (!isDrawingCacheEnabled()) { setDrawingCacheEnabled(true); } if (mRenderer.isApplyBackgroundColor()) { setDrawingCacheBackgroundColor(mRenderer.getBackgroundColor()); } setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); return getDrawingCache(true); } } \ No newline at end of file diff --git a/achartengine/src/org/achartengine/renderer/DefaultRenderer.java b/achartengine/src/org/achartengine/renderer/DefaultRenderer.java index f26ae59..fd117e7 100644 --- a/achartengine/src/org/achartengine/renderer/DefaultRenderer.java +++ b/achartengine/src/org/achartengine/renderer/DefaultRenderer.java @@ -1,644 +1,662 @@ /** * Copyright (C) 2009, 2010 SC 4ViewSoft SRL * * 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.achartengine.renderer; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import android.graphics.Color; import android.graphics.Typeface; /** * An abstract renderer to be extended by the multiple series classes. */ public class DefaultRenderer implements Serializable { /** The chart title. */ private String mChartTitle = ""; /** The chart title text size. */ private float mChartTitleTextSize = 15; /** A no color constant. */ public static final int NO_COLOR = 0; /** The default background color. */ public static final int BACKGROUND_COLOR = Color.BLACK; /** The default color for text. */ public static final int TEXT_COLOR = Color.LTGRAY; /** A text font for regular text, like the chart labels. */ private static final Typeface REGULAR_TEXT_FONT = Typeface .create(Typeface.SERIF, Typeface.NORMAL); /** The typeface name for the texts. */ private String mTextTypefaceName = REGULAR_TEXT_FONT.toString(); /** The typeface style for the texts. */ private int mTextTypefaceStyle = Typeface.NORMAL; /** The chart background color. */ private int mBackgroundColor; /** If the background color is applied. */ private boolean mApplyBackgroundColor; /** If the axes are visible. */ private boolean mShowAxes = true; /** The axes color. */ private int mAxesColor = TEXT_COLOR; /** If the labels are visible. */ private boolean mShowLabels = true; /** The labels color. */ private int mLabelsColor = TEXT_COLOR; /** The labels text size. */ private float mLabelsTextSize = 10; /** If the legend is visible. */ private boolean mShowLegend = true; /** The legend text size. */ private float mLegendTextSize = 12; /** If the legend should size to fit. */ private boolean mFitLegend = false; /** If the grid should be displayed. */ private boolean mShowGrid = false; /** If the custom text grid should be displayed. */ private boolean mShowCustomTextGrid = false; /** The simple renderers that are included in this multiple series renderer. */ private List<SimpleSeriesRenderer> mRenderers = new ArrayList<SimpleSeriesRenderer>(); /** The antialiasing flag. */ private boolean mAntialiasing = true; /** The legend height. */ private int mLegendHeight = 0; /** The margins size. */ private int[] mMargins = new int[] { 20, 30, 10, 20 }; /** A value to be used for scaling the chart. */ private float mScale = 1; /** A flag for enabling the pan. */ private boolean mPanEnabled = true; /** A flag for enabling the zoom. */ private boolean mZoomEnabled = true; /** A flag for enabling the visibility of the zoom buttons. */ private boolean mZoomButtonsVisible = false; /** The zoom rate. */ private float mZoomRate = 1.5f; /** A flag for enabling the external zoom. */ private boolean mExternalZoomEnabled = false; /** The original chart scale. */ private float mOriginalScale = mScale; /** A flag for enabling the click on elements. */ private boolean mClickEnabled = false; /** The selectable radius around a clickable point. */ private int selectableBuffer = 15; + /** A flag to be set if the chart is inside a scroll and doesn't need to shrink when not enough space. */ + private boolean mInScroll; /** * Returns the chart title. * * @return the chart title */ public String getChartTitle() { return mChartTitle; } /** * Sets the chart title. * * @param title the chart title */ public void setChartTitle(String title) { mChartTitle = title; } /** * Returns the chart title text size. * * @return the chart title text size */ public float getChartTitleTextSize() { return mChartTitleTextSize; } /** * Sets the chart title text size. * * @param textSize the chart title text size */ public void setChartTitleTextSize(float textSize) { mChartTitleTextSize = textSize; } /** * Adds a simple renderer to the multiple renderer. * * @param renderer the renderer to be added */ public void addSeriesRenderer(SimpleSeriesRenderer renderer) { mRenderers.add(renderer); } /** * Adds a simple renderer to the multiple renderer. * * @param index the index in the renderers list * @param renderer the renderer to be added */ public void addSeriesRenderer(int index, SimpleSeriesRenderer renderer) { mRenderers.add(index, renderer); } /** * Removes a simple renderer from the multiple renderer. * * @param renderer the renderer to be removed */ public void removeSeriesRenderer(SimpleSeriesRenderer renderer) { mRenderers.remove(renderer); } /** * Returns the simple renderer from the multiple renderer list. * * @param index the index in the simple renderers list * @return the simple renderer at the specified index */ public SimpleSeriesRenderer getSeriesRendererAt(int index) { return mRenderers.get(index); } /** * Returns the simple renderers count in the multiple renderer list. * * @return the simple renderers count */ public int getSeriesRendererCount() { return mRenderers.size(); } /** * Returns an array of the simple renderers in the multiple renderer list. * * @return the simple renderers array */ public SimpleSeriesRenderer[] getSeriesRenderers() { return mRenderers.toArray(new SimpleSeriesRenderer[0]); } /** * Returns the background color. * * @return the background color */ public int getBackgroundColor() { return mBackgroundColor; } /** * Sets the background color. * * @param color the background color */ public void setBackgroundColor(int color) { mBackgroundColor = color; } /** * Returns if the background color should be applied. * * @return the apply flag for the background color. */ public boolean isApplyBackgroundColor() { return mApplyBackgroundColor; } /** * Sets if the background color should be applied. * * @param apply the apply flag for the background color */ public void setApplyBackgroundColor(boolean apply) { mApplyBackgroundColor = apply; } /** * Returns the axes color. * * @return the axes color */ public int getAxesColor() { return mAxesColor; } /** * Sets the axes color. * * @param color the axes color */ public void setAxesColor(int color) { mAxesColor = color; } /** * Returns the labels color. * * @return the labels color */ public int getLabelsColor() { return mLabelsColor; } /** * Sets the labels color. * * @param color the labels color */ public void setLabelsColor(int color) { mLabelsColor = color; } /** * Returns the labels text size. * * @return the labels text size */ public float getLabelsTextSize() { return mLabelsTextSize; } /** * Sets the labels text size. * * @param textSize the labels text size */ public void setLabelsTextSize(float textSize) { mLabelsTextSize = textSize; } /** * Returns if the axes should be visible. * * @return the visibility flag for the axes */ public boolean isShowAxes() { return mShowAxes; } /** * Sets if the axes should be visible. * * @param showAxes the visibility flag for the axes */ public void setShowAxes(boolean showAxes) { mShowAxes = showAxes; } /** * Returns if the labels should be visible. * * @return the visibility flag for the labels */ public boolean isShowLabels() { return mShowLabels; } /** * Sets if the labels should be visible. * * @param showLabels the visibility flag for the labels */ public void setShowLabels(boolean showLabels) { mShowLabels = showLabels; } /** * Returns if the grid should be visible. * * @return the visibility flag for the grid */ public boolean isShowGrid() { return mShowGrid; } /** * Sets if the grid should be visible. * * @param showGrid the visibility flag for the grid */ public void setShowGrid(boolean showGrid) { mShowGrid = showGrid; } /** * Returns if the grid should be visible for custom X or Y labels. * * @return the visibility flag for the custom text grid */ public boolean isShowCustomTextGrid() { return mShowCustomTextGrid; } /** * Sets if the grid for custom X or Y labels should be visible. * * @param showGrid the visibility flag for the custom text grid */ public void setShowCustomTextGrid(boolean showGrid) { mShowCustomTextGrid = showGrid; } /** * Returns if the legend should be visible. * * @return the visibility flag for the legend */ public boolean isShowLegend() { return mShowLegend; } /** * Sets if the legend should be visible. * * @param showLegend the visibility flag for the legend */ public void setShowLegend(boolean showLegend) { mShowLegend = showLegend; } /** * Returns if the legend should size to fit. * * @return the fit behavior */ public boolean isFitLegend() { return mFitLegend; } /** * Sets if the legend should size to fit. * * @param fit the fit behavior */ public void setFitLegend(boolean fit) { mFitLegend = fit; } /** * Returns the text typeface name. * * @return the text typeface name */ public String getTextTypefaceName() { return mTextTypefaceName; } /** * Returns the text typeface style. * * @return the text typeface style */ public int getTextTypefaceStyle() { return mTextTypefaceStyle; } /** * Returns the legend text size. * * @return the legend text size */ public float getLegendTextSize() { return mLegendTextSize; } /** * Sets the legend text size. * * @param textSize the legend text size */ public void setLegendTextSize(float textSize) { mLegendTextSize = textSize; } /** * Sets the text typeface name and style. * * @param typefaceName the text typeface name * @param style the text typeface style */ public void setTextTypeface(String typefaceName, int style) { mTextTypefaceName = typefaceName; mTextTypefaceStyle = style; } /** * Returns the antialiasing flag value. * * @return the antialiasing value */ public boolean isAntialiasing() { return mAntialiasing; } /** * Sets the antialiasing value. * * @param antialiasing the antialiasing */ public void setAntialiasing(boolean antialiasing) { mAntialiasing = antialiasing; } /** * Returns the value to be used for scaling the chart. * * @return the scale value */ public float getScale() { return mScale; } /** * Returns the original value to be used for scaling the chart. * * @return the original scale value */ public float getOriginalScale() { return mOriginalScale; } /** * Sets the value to be used for scaling the chart. It works on some charts * like pie, doughnut, dial. * * @param scale the scale value */ public void setScale(float scale) { mScale = scale; } /** * Returns the enabled state of the zoom. * * @return if zoom is enabled */ public boolean isZoomEnabled() { return mZoomEnabled; } /** * Sets the enabled state of the zoom. * * @param enabled zoom enabled */ public void setZoomEnabled(boolean enabled) { mZoomEnabled = enabled; } /** * Returns the visible state of the zoom buttons. * * @return if zoom buttons are visible */ public boolean isZoomButtonsVisible() { return mZoomButtonsVisible; } /** * Sets the visible state of the zoom buttons. * * @param visible if the zoom buttons are visible */ public void setZoomButtonsVisible(boolean visible) { mZoomButtonsVisible = visible; } /** * Returns the enabled state of the external (application implemented) zoom. * * @return if external zoom is enabled */ public boolean isExternalZoomEnabled() { return mExternalZoomEnabled; } /** * Sets the enabled state of the external (application implemented) zoom. * * @param enabled external zoom enabled */ public void setExternalZoomEnabled(boolean enabled) { mExternalZoomEnabled = enabled; } /** * Returns the zoom rate. * * @return the zoom rate */ public float getZoomRate() { return mZoomRate; } /** * Returns the enabled state of the pan. * * @return if pan is enabled */ public boolean isPanEnabled() { return mPanEnabled; } /** * Sets the enabled state of the pan. * * @param enabled pan enabled */ public void setPanEnabled(boolean enabled) { mPanEnabled = enabled; } /** * Sets the zoom rate. * * @param rate the zoom rate */ public void setZoomRate(float rate) { mZoomRate = rate; } /** * Returns the enabled state of the click. * * @return if click is enabled */ public boolean isClickEnabled() { return mClickEnabled; } /** * Sets the enabled state of the click. * * @param enabled click enabled */ public void setClickEnabled(boolean enabled) { mClickEnabled = enabled; } /** * Returns the selectable radius value around clickable points. * * @return the selectable radius */ public int getSelectableBuffer() { return selectableBuffer; } /** * Sets the selectable radius value around clickable points. * * @param buffer the selectable radius */ public void setSelectableBuffer(int buffer) { selectableBuffer = buffer; } /** * Returns the legend height. * * @return the legend height */ public int getLegendHeight() { return mLegendHeight; } /** * Sets the legend height, in pixels. * * @param height the legend height */ public void setLegendHeight(int height) { mLegendHeight = height; } /** * Returns the margin sizes. An array containing the margins in this order: * top, left, bottom, right * * @return the margin sizes */ public int[] getMargins() { return mMargins; } /** * Sets the margins, in pixels. * * @param margins an array containing the margin size values, in this order: * top, left, bottom, right */ public void setMargins(int[] margins) { mMargins = margins; } + + /** + * Returns if the chart is inside a scroll view and doesn't need to shrink. + * @return if it is inside a scroll view + */ + public boolean isInScroll() { + return mInScroll; + } + + /** + * To be set if the chart is inside a scroll view and doesn't need to shrink when not enough space. + * @param inScroll if it is inside a scroll view + */ + public void setInScroll(boolean inScroll) { + mInScroll = inScroll; + } }
false
false
null
null
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/extensions/GLEEDTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/extensions/GLEEDTest.java index fa98ab43d..f6a220187 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/extensions/GLEEDTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/extensions/GLEEDTest.java @@ -1,78 +1,79 @@ package com.badlogic.gdx.tests.extensions; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver; import com.badlogic.gdx.gleed.Level; import com.badlogic.gdx.gleed.LevelLoader; import com.badlogic.gdx.gleed.LevelRenderer; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.utils.Logger; public class GLEEDTest extends GdxTest { enum State { Loading, Running } AssetManager manager; OrthographicCamera camera; LevelRenderer renderer; State state = State.Loading; @Override public boolean needsGL20() { return true; } @Override public void create() { super.create(); manager = new AssetManager(); camera = new OrthographicCamera(640, 480); camera.setToOrtho(false, 640, 480); + camera.zoom = 2.0f; LevelLoader.setLoggingLevel(Logger.INFO); manager.setLoader(Level.class, new LevelLoader(new InternalFileHandleResolver())); manager.load("data/gleedtest.xml", Level.class); } @Override public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); if (state == State.Loading && manager.update()) { state = State.Running; renderer = new LevelRenderer(manager.get("data/gleedtest.xml", Level.class), null, 1.0f); } if (state == State.Running) { camera.update(); renderer.render(camera); if (Gdx.input.isKeyPressed(Keys.UP)) { - camera.position.y += 0.2f; + camera.position.y += 5.0f; } else if (Gdx.input.isKeyPressed(Keys.DOWN)) { - camera.position.y -= 0.2f; + camera.position.y -= 5.0f; } if (Gdx.input.isKeyPressed(Keys.RIGHT)) { - camera.position.x += 0.2f; + camera.position.x += 5.0f; } else if (Gdx.input.isKeyPressed(Keys.LEFT)) { - camera.position.x -= 0.2f; + camera.position.x -= 5.0f; } if (Gdx.input.isKeyPressed(Keys.A)) { - camera.zoom += 0.2f; + camera.zoom += 0.05f; } else if (Gdx.input.isKeyPressed(Keys.S)) { - camera.zoom -= 0.2f; + camera.zoom -= 0.05f; } } } }
false
false
null
null
diff --git a/runtime/ceylon/language/List$impl.java b/runtime/ceylon/language/List$impl.java index 4a439d4d..19687dec 100644 --- a/runtime/ceylon/language/List$impl.java +++ b/runtime/ceylon/language/List$impl.java @@ -1,134 +1,134 @@ package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Ignore; @Ignore public final class List$impl<Element> { private final List<Element> $this; public List$impl(List<Element> $this) { this.$this = $this; } public boolean getEmpty(){ return List$impl.<Element>getEmpty($this); } static <Element> boolean getEmpty(List<Element> $this){ return false; } public long getSize(){ return List$impl.<Element>getSize($this); } static <Element> long getSize(List<Element> $this){ Integer lastIndex = $this.getLastIndex(); return lastIndex==null ? 0 : lastIndex.longValue()+1; } public boolean defines(Integer key){ return List$impl.<Element>_defines($this, key); } static <Element> boolean _defines(List<Element> $this, Integer key){ Integer lastIndex = $this.getLastIndex(); return lastIndex==null ? false : key.longValue() <= lastIndex.longValue(); } public Iterator<? extends Element> getIterator(){ return List$impl.<Element>_getIterator($this); } static <Element> Iterator<? extends Element> _getIterator(final List<Element> $this){ class ListIterator implements Iterator<Element> { private long index=0; public final java.lang.Object next() { Integer lastIndex = $this.getLastIndex(); if (lastIndex!=null && index <= lastIndex.longValue()) { return $this.item(Integer.instance(index++)); } else { return exhausted.getExhausted(); } } public final java.lang.String toString() { return "listIterator"; } } return new ListIterator(); } public boolean equals(java.lang.Object that) { return List$impl.<Element>_equals($this, that); } static <Element> boolean _equals(final List<Element> $this, java.lang.Object that) { if (that instanceof List) { List other = (List) that; if (other.getSize()==$this.getSize()) { for (int i=0; i<$this.getSize(); i++) { Element x = $this.item(Integer.instance(i)); java.lang.Object y = ((List) that).item(Integer.instance(i)); if (x!=y && (x==null || y==null || !x.equals(y))) { return false; } } return true; } } return false; } public int hashCode() { return List$impl.<Element>_hashCode($this); } static <Element> int _hashCode(final List<Element> $this) { int hashCode = 1; java.lang.Object elem; for (Iterator<? extends Element> iter=$this.getIterator(); !((elem = iter.next()) instanceof Finished);) { hashCode *= 31; if (elem != null) { hashCode += elem.hashCode(); } } return hashCode; } public Element findLast(Callable<? extends Boolean> sel) { return List$impl.<Element>_findLast($this, sel); } public static <Element> Element _findLast(List<Element> $this, Callable<? extends Boolean> sel) { Integer last = $this.getLastIndex(); if (last != null) { while (!last.getNegative()) { Element e = $this.item(last); if (e != null && sel.$call(e).booleanValue()) { return e; } last = last.getPredecessor(); } } return null; } @SuppressWarnings("rawtypes") - public <Other> Sequence withLeading(Other elements) { - return List$impl._withLeading($this, elements); + public <Other> Sequence withLeading(Other element) { + return List$impl._withLeading($this, element); } @SuppressWarnings({"rawtypes", "unchecked"}) public static <Element,Other> Sequence _withLeading(List<? extends Element> orig, Other elem) { SequenceBuilder sb = new SequenceBuilder(); sb.append(elem); sb.appendAll(orig); return (Sequence)sb.getSequence(); } @SuppressWarnings("rawtypes") public <Other> Sequence withTrailing(Other element) { return List$impl._withTrailing($this, element); } @SuppressWarnings({"rawtypes", "unchecked"}) public static <Element,Other> Sequence _withTrailing(List<? extends Element> orig, Other elem) { SequenceBuilder sb = new SequenceBuilder(); sb.appendAll(orig); sb.append(elem); return (Sequence)sb.getSequence(); } }
true
false
null
null
diff --git a/src/bsf-2.3/bsf/src/org/apache/bsf/engines/javascript/RhinoContextProxy.java b/src/bsf-2.3/bsf/src/org/apache/bsf/engines/javascript/RhinoContextProxy.java index 02ba3b7..5091782 100644 --- a/src/bsf-2.3/bsf/src/org/apache/bsf/engines/javascript/RhinoContextProxy.java +++ b/src/bsf-2.3/bsf/src/org/apache/bsf/engines/javascript/RhinoContextProxy.java @@ -1,303 +1,295 @@ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Apache BSF", "Apache", and "Apache Software Foundation" * must not be used to endorse or promote products derived from * this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many individuals * on behalf of the Apache Software Foundation and was originally created by * Sanjiva Weerawarana and others at International Business Machines * Corporation. For more information on the Apache Software Foundation, * please see <http://www.apache.org/>. */ package org.apache.bsf.engines.javascript; /** * Insert the type's description here. * Creation date: (8/23/2001 4:09:36 PM) * @author: Administrator */ import java.util.Hashtable; import org.apache.bsf.*; import org.apache.bsf.debug.jsdi.*; import org.mozilla.javascript.*; import org.mozilla.javascript.debug.*; import java.rmi.RemoteException; public class RhinoContextProxy { RhinoEngineDebugger m_reDbg; Context m_context; JsContextStub m_contextStub; DebuggableEngine m_engine; boolean m_atBreakpoint; int m_frameCount; JsContextStub m_frames[]; private static final int NO_STEP = 0, STEP_IN = 1, STEP_OVER = 2, STEP_OUT = 3, STOP_ENGINE = 4, RUNNING = 5; private int m_stepCmd, m_stepDepth; RhinoContextProxy(RhinoEngineDebugger reDbg, Context cx) { m_reDbg = reDbg; m_context = cx; m_engine = cx.getDebuggableEngine(); } public void cancelStepping() { m_stepCmd = NO_STEP; m_stepDepth = -1; m_engine.setBreakNextLine(false); } public JsContextStub getContext(int depth) { return m_frames[depth]; } public int getContextCount() { return m_frameCount; } public JsContextStub getFrame(int no) { if (no < 0 || no > m_frameCount) return null; if (no == m_frameCount) return m_contextStub; else return m_frames[no]; } public int getLineNumber() { DebugFrame frame = m_engine.getFrame(0); return frame.getLineNumber(); } public RhinoEngineDebugger getRhinoEngineDebugger() { return m_reDbg; } String getSourceName() { DebugFrame frame = m_engine.getFrame(0); return frame.getSourceName(); } // We hit a known breakpoint. // We need to update the stack. // Also, cancel any pending stepping operation. public JsContextStub hitBreakpoint() throws RemoteException { cancelStepping(); updateStack(); return m_frames[0]; } public JsContextStub exceptionThrown() throws RemoteException { cancelStepping(); updateStack(); return m_frames[0]; } public void resumed() { JsContextStub stub; DebugFrame frame; m_atBreakpoint = false; for (int f = 0; f < m_frameCount; f++) { stub = m_frames[f]; stub.atBreakpoint(false); } } public void run() { m_engine.setBreakNextLine(false); m_stepCmd = RUNNING; m_stepDepth = -1; } public void stepIn() { m_engine.setBreakNextLine(true); m_stepCmd = STEP_IN; m_stepDepth = m_frameCount; } public void stepOut() { m_engine.setBreakNextLine(true); m_stepCmd = STEP_OUT; m_stepDepth = m_frameCount; } public void stepOver() { m_engine.setBreakNextLine(true); m_stepCmd = STEP_OVER; m_stepDepth = m_frameCount; } public JsContextStub entry_exit_mode() throws RemoteException { cancelStepping(); updateStack(); return m_frames[0]; } public JsContextStub stepping() { // Did we hit a known breakpoint? int frameCount = m_engine.getFrameCount(); try { switch (m_stepCmd) { case NO_STEP : cancelStepping(); break; case STOP_ENGINE : updateStack(); cancelStepping(); return m_frames[0]; case STEP_IN : // OG if ((frameCount == m_stepDepth + 1) || // (frameCount == m_stepDepth)) { // step if we are in the same frame (nothing to step in... :-) // if we are in a called frame... // but also if we stepped out of the current frame... - if ((frameCount >= m_stepDepth) - || (frameCount < m_stepDepth)) { updateStack(); cancelStepping(); return m_frames[0]; - } - break; case STEP_OVER : // OG if (frameCount == m_stepDepth) { // step if we are in the same frame or above... // this basically avoids any children frame but // covers the return of the current frame. if (frameCount <= m_stepDepth) { updateStack(); cancelStepping(); return m_frames[0]; } break; case STEP_OUT : // OG if (frameCount == m_stepDepth - 1) { if (frameCount < m_stepDepth) { updateStack(); cancelStepping(); return m_frames[0]; } break; default : throw new Error("Unknown command."); } } catch (Throwable t) { t.printStackTrace(); cancelStepping(); } return null; } public void stopEngine() { m_engine.setBreakNextLine(true); m_stepCmd = STOP_ENGINE; m_stepDepth = -1; } public void updateStack() throws RemoteException { - JsContextStub frames[]; - JsContextStub stub; + int nf, of, frameCount = m_engine.getFrameCount(); + JsContextStub frames[] = new JsContextStub[frameCount]; DebugFrame frame; - int nf, of, frameCount; m_atBreakpoint = true; - frameCount = m_engine.getFrameCount(); - frames = new JsContextStub[frameCount]; - // scan the stacks from the outer frame down // to the inner one of the shortest of the old // and the new known stack. // The goal is to recognize the DebugFrame objects // that are the sames so that we can reuse the // stubs for those. // As soon as a DebugFrame object is found different, // the rest of the stack is different, all the old // stubs can be dropped and invalidated, new ones // must be created. - for (nf = frameCount - 1, of = m_frameCount - 1; - nf >= 0 && of >= 0; - nf--, of--) { + for (nf = 0, of = 0; + nf < frameCount && of < m_frameCount; + nf++, of++) { frame = m_engine.getFrame(nf); if (frame == m_frames[of].m_frame) { frames[nf] = m_frames[of]; } else break; } // now drop all old frames that diverged. // Also invalidate the frame stubs so to // tracked that they are no longer valid. - for (; of >= 0; of--) { + for (; of < m_frameCount; of++) { m_reDbg.dropStub(m_frames[of].m_frame); m_frames[of].invalidate(); } - for (; nf >= 0; nf--) { + for (; nf < frameCount; nf++) { frame = m_engine.getFrame(nf); frames[nf] = new JsContextStub(this, frame, nf); } m_frames = frames; m_frameCount = frameCount; } }
false
false
null
null
diff --git a/org/jruby/internal/runtime/builtin/definitions/FileStatDefinition.java b/org/jruby/internal/runtime/builtin/definitions/FileStatDefinition.java index 260cb0b3b..f6a7cafcd 100644 --- a/org/jruby/internal/runtime/builtin/definitions/FileStatDefinition.java +++ b/org/jruby/internal/runtime/builtin/definitions/FileStatDefinition.java @@ -1,56 +1,57 @@ /* * Copyright (C) 2002 Anders Bengtsson <[email protected]> * * JRuby - http://jruby.sourceforge.net * * This file is part of JRuby * * JRuby 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. * * JRuby 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 JRuby; if not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package org.jruby.internal.runtime.builtin.definitions; import org.jruby.runtime.builtin.definitions.ClassDefinition; import org.jruby.runtime.builtin.definitions.SingletonMethodContext; import org.jruby.runtime.builtin.definitions.MethodContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.util.Asserts; public class FileStatDefinition extends ClassDefinition { - private static final int FILE_STAT = 0x1200; // todo: what constant should i use? + private static final int FILE_STAT = 0x1600; + public static final int DIRECTORY_P = FILE_STAT | 0x01; public FileStatDefinition(Ruby runtime) { super(runtime); } protected RubyClass createType(Ruby runtime) { return runtime.defineClass("File::Stat", runtime.getClasses().getObjectClass()); } protected void defineSingletonMethods(SingletonMethodContext context) { } protected void defineMethods(MethodContext context) { context.create("directory?", DIRECTORY_P, 0); } public IRubyObject callIndexed(int index, IRubyObject receiver, IRubyObject[] args) { Asserts.notReached(); return null; } }
true
false
null
null
diff --git a/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/Sphinx3Loader.java b/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/Sphinx3Loader.java index ed431584..6b643883 100644 --- a/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/Sphinx3Loader.java +++ b/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/Sphinx3Loader.java @@ -1,1608 +1,1610 @@ /* * Copyright 1999-2004 Carnegie Mellon University. * Portions Copyright 2004 Sun Microsystems, Inc. * Portions Copyright 2004 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.linguist.acoustic.tiedstate; +// Placeholder for a package import + import edu.cmu.sphinx.linguist.acoustic.*; import edu.cmu.sphinx.util.*; import edu.cmu.sphinx.util.props.*; import java.io.*; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipException; /** * Loads a tied-state acoustic model generated by the Sphinx-3 trainer. * <p/> * The acoustic model should be packaged in a JAR file. The dictionary and language model files are not required to be * in the package. You can specify their locations separately. A text file called "model.props" and the data files that * make up the acoustic model are required. The model.props file is a file of key-value pairs, loadable as a Java * Properties file. It should minimally contain the following properties: <ul> <li><b>dataLocation</b> - this specifies * the directory where the actual model data files are, <i>relative to the model implementation class</i></li> * <li><b>modelDefinition</b> - this specifies the location where the model definition file is, <i>relative to the model * implementation class</i></li> </ul> The actual model data files are named "means", "variances", * "transition_matrices", "mixture_weights" for binary versions, or prepended with ".ascii" for the ASCII versions. * </p> * <p/> * As an example, lets look at the Wall Street Journal acoustic model JAR file, which is located at the * <code>sphinx4/lib</code> directory. If you run <code>"jar tvf lib/WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar"</code>, * you will find that its internal structure looks roughly like: * <pre> * WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar * | * +- edu * | * +- cmu * | * +- sphinx * | * +- model * | * + acoustic * | * +- model.props * | * +- WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.class * | * +- WSJLoader.class * | * +- cd_continuous_8gau * | | * | +- means * | +- variances * | +- mixture_weights * | +- transition_matrices * | * +- dict * | | * | +- alpha.dict * | +- cmudict.0.6d * | +- digits.dict * | +- fillerdict * | * +- etc * | * +- WSJ_clean_13dCep_16k_40mel_130Hz_6800Hz.4000.mdef * +- WSJ_clean_13dCep_16k_40mel_130Hz_6800Hz.ci.mdef * +- variables.def * <p/> * </pre> * <p/> * The model.props file looks like (note how the 'dataLocation' and 'modelDefinition' properties are defined relative to * the WSJ_clean_13dCep_16k_40mel_130Hz_6800Hz.class): </p> * <pre> * description = Wall Street Journal acoustic models * <p/> * isBinary = true * featureType = cepstra_delta_doubledelta * vectorLength = 39 * sparseForm = false * <p/> * numberFftPoints = 512 * filters = 40 * gaussians = 8 * maxFreq = 6800 * minFreq. = 130 * sampleRate = 16000 * <p/> * dataLocation = cd_continuous_8gau * modelDefinition = etc/WSJ_clean_13dCep_16k_40mel_130Hz_6800Hz.4000.mdef * </pre> * <p/> * <p/> * Note that although most of the properties of this class are already defined in the model.props file, it is still * possible (but not recommended) to override those values by specifying them in the configuration file. </p> */ public class Sphinx3Loader implements Loader { /** The log math component for the system. */ @S4Component(type = LogMath.class) public final static String PROP_LOG_MATH = "logMath"; /** The unit manager */ @S4Component(type = UnitManager.class) public final static String PROP_UNIT_MANAGER = "unitManager"; /** Specifies whether the model to be loaded is in ASCII or binary format */ @S4Boolean(defaultValue = true, isNotDefined = true) public final static String PROP_IS_BINARY = "isBinary"; /** The default value of PROP_IS_BINARY */ public final static boolean PROP_IS_BINARY_DEFAULT = true; /** The name of the model definition file (contains the HMM data) */ @S4String(mandatory = false) public final static String PROP_MODEL = "modelDefinition"; /** The default value of PROP_MODEL. */ public final static String PROP_MODEL_DEFAULT = "model.mdef"; /** Subdirectory where the acoustic model can be found */ @S4String(mandatory = false) public final static String PROP_DATA_LOCATION = "dataLocation"; /** The default value of PROP_DATA_LOCATION. */ public final static String PROP_DATA_LOCATION_DEFAULT = "data"; /** The SphinxProperty for the name of the acoustic properties file. */ @S4String(defaultValue = "model.props") public final static String PROP_PROPERTIES_FILE = "propertiesFile"; /** The default value of PROP_PROPERTIES_FILE. */ public final static String PROP_PROPERTIES_FILE_DEFAULT = "model.props"; /** The SphinxProperty for the length of feature vectors. */ @S4Integer(defaultValue = -1) public final static String PROP_VECTOR_LENGTH = "vectorLength"; /** The default value of PROP_VECTOR_LENGTH. */ public final static int PROP_VECTOR_LENGTH_DEFAULT = 39; /** * The SphinxProperty specifying whether the transition matrices of the acoustic model is in sparse form, i.e., * omitting the zeros of the non-transitioning states. */ @S4Boolean(defaultValue = true, isNotDefined = true) public final static String PROP_SPARSE_FORM = "sparseForm"; /** The default value of PROP_SPARSE_FORM. */ public final static boolean PROP_SPARSE_FORM_DEFAULT = true; /** The SphinxProperty specifying whether context-dependent units should be used. */ @S4Boolean(defaultValue = true) public final static String PROP_USE_CD_UNITS = "useCDUnits"; /** The default value of PROP_USE_CD_UNITS. */ public final static boolean PROP_USE_CD_UNITS_DEFAULT = true; /** Mixture component score floor. */ @S4Double(defaultValue = 0.0) public final static String PROP_MC_FLOOR = "MixtureComponentScoreFloor"; /** Mixture component score floor default value. */ public final static float PROP_MC_FLOOR_DEFAULT = 0.0f; /** Variance floor. */ @S4Double(defaultValue = 0.0001) public final static String PROP_VARIANCE_FLOOR = "varianceFloor"; /** Variance floor default value. */ public final static float PROP_VARIANCE_FLOOR_DEFAULT = 0.0001f; /** Mixture weight floor. */ @S4Double(defaultValue = 1e-7) public final static String PROP_MW_FLOOR = "mixtureWeightFloor"; /** Mixture weight floor default value. */ public final static float PROP_MW_FLOOR_DEFAULT = 1e-7f; protected final static String NUM_SENONES = "num_senones"; protected final static String NUM_GAUSSIANS_PER_STATE = "num_gaussians"; protected final static String NUM_STREAMS = "num_streams"; protected final static String FILLER = "filler"; protected final static String SILENCE_CIPHONE = "SIL"; protected final static int BYTE_ORDER_MAGIC = 0x11223344; /** Supports this version of the acoustic model */ public final static String MODEL_VERSION = "0.3"; protected final static int CONTEXT_SIZE = 1; private Pool meansPool; private Pool variancePool; private Pool matrixPool; private Pool meanTransformationMatrixPool; private Pool meanTransformationVectorPool; private Pool varianceTransformationMatrixPool; private Pool varianceTransformationVectorPool; private Pool mixtureWeightsPool; private Pool senonePool; private float[][] transformMatrix; private Map<String, Unit> contextIndependentUnits; private HMMManager hmmManager; private LogMath logMath; private UnitManager unitManager; private Properties properties; private boolean swap; protected final static String DENSITY_FILE_VERSION = "1.0"; protected final static String MIXW_FILE_VERSION = "1.0"; protected final static String TMAT_FILE_VERSION = "1.0"; protected final static String TRANSFORM_FILE_VERSION = "0.1"; // -------------------------------------- // Configuration variables // -------------------------------------- private String name; private Logger logger; private boolean binary; private boolean sparseForm; private int vectorLength; private String location; private String model; private String dataDir; private String propsFile; private float distFloor; private float mixtureWeightFloor; private float varianceFloor; private boolean useCDUnits; /* * (non-Javadoc) * * @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet) */ public void newProperties(PropertySheet ps) throws PropertyException { logger = ps.getLogger(); propsFile = ps.getString(PROP_PROPERTIES_FILE); logMath = (LogMath) ps.getComponent(PROP_LOG_MATH); unitManager = (UnitManager) ps.getComponent(PROP_UNIT_MANAGER); Boolean isBinary = ps.getBoolean(PROP_IS_BINARY); binary = isBinary != null ? isBinary : getIsBinaryDefault(); Boolean isSparse = ps.getBoolean(PROP_IS_BINARY); sparseForm = isSparse != null ? isSparse : getSparseFormDefault(); vectorLength = ps.getInt(PROP_VECTOR_LENGTH); vectorLength = vectorLength > 0 ? vectorLength : getVectorLengthDefault(); model = ps.getString(PROP_MODEL); model = model == null ? getModelDefault() : model; dataDir = ps.getString(PROP_DATA_LOCATION); dataDir = (dataDir == null ? getDataLocationDefault() : dataDir) + "/"; distFloor = ps.getFloat(PROP_MC_FLOOR); mixtureWeightFloor = ps.getFloat(PROP_MW_FLOOR); varianceFloor = ps.getFloat(PROP_VARIANCE_FLOOR); useCDUnits = ps.getBoolean(PROP_USE_CD_UNITS); } private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); // System.out.println(getClass() + " " + url); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * Returns whether the models are binary by default * * @return true if the models are binary by default */ private boolean getIsBinaryDefault() { loadProperties(); String binary = (String) properties.get(PROP_IS_BINARY); if (binary != null) { return (Boolean.valueOf(binary).equals(Boolean.TRUE)); } else { return PROP_IS_BINARY_DEFAULT; } } /** * Returns whether the matrices are in sparse form by default. * * @return true if the matrices are in sparse form by default */ private boolean getSparseFormDefault() { loadProperties(); String sparse = (String) properties.get(PROP_SPARSE_FORM); if (sparse != null) { return (Boolean.valueOf(binary).equals(Boolean.TRUE)); } else { return PROP_SPARSE_FORM_DEFAULT; } } /** Returns the default vector length. */ private int getVectorLengthDefault() { loadProperties(); String length = (String) properties.get(PROP_VECTOR_LENGTH); if (length != null) { return Integer.parseInt(length); } else { return PROP_VECTOR_LENGTH_DEFAULT; } } /** * Returns the default model definition file. * * @return the default model definition file */ private String getModelDefault() { loadProperties(); String mdef = (String) properties.get(PROP_MODEL); if (mdef != null) { return mdef; } else { return PROP_MODEL_DEFAULT; } } /** * Returns the default data location. * * @return the default data location */ private String getDataLocationDefault() { loadProperties(); String location = (String) properties.get(PROP_DATA_LOCATION); if (location != null) { return location; } else { return PROP_DATA_LOCATION_DEFAULT; } } /* * (non-Javadoc) * * @see edu.cmu.sphinx.util.props.Configurable#getName() */ public String getName() { return name; } public void load() throws IOException { // TODO: what is this all about? hmmManager = new HMMManager(); contextIndependentUnits = new LinkedHashMap<String, Unit>(); // dummy pools for these elements meanTransformationMatrixPool = createDummyMatrixPool("meanTransformationMatrix"); meanTransformationVectorPool = createDummyVectorPool("meanTransformationMatrix"); varianceTransformationMatrixPool = createDummyMatrixPool("varianceTransformationMatrix"); varianceTransformationVectorPool = createDummyVectorPool("varianceTransformationMatrix"); transformMatrix = null; // do the actual acoustic model loading loadModelFiles(model); } /** * Return the HmmManager. * * @return the hmmManager */ protected HMMManager getHmmManager() { return hmmManager; } /** * Return the MatrixPool. * * @return the matrixPool */ protected Pool getMatrixPool() { return matrixPool; } /** * Return the MixtureWeightsPool. * * @return the mixtureWeightsPool */ protected Pool getMixtureWeightsPool() { return mixtureWeightsPool; } /** * Return the acoustic model properties. * * @return the acoustic model properties */ protected Properties getProperties() { if (properties == null) { loadProperties(); } return properties; } /** * Return the location. * * @return the location */ protected String getLocation() { return location; } /** * Loads the AcousticModel from a directory in the file system. * * @param modelName the name of the acoustic model; if null we just load from the default location */ private void loadModelFiles(String modelName) throws FileNotFoundException, IOException, ZipException { logger.config("Loading Sphinx3 acoustic model: " + modelName); logger.config(" Path : " + location); logger.config(" modellName: " + model); logger.config(" dataDir : " + dataDir); if (binary) { meansPool = loadDensityFileBinary (dataDir + "means", -Float.MAX_VALUE); variancePool = loadDensityFileBinary (dataDir + "variances", varianceFloor); mixtureWeightsPool = loadMixtureWeightsBinary (dataDir + "mixture_weights", mixtureWeightFloor); matrixPool = loadTransitionMatricesBinary (dataDir + "transition_matrices"); transformMatrix = loadTransformMatrix (dataDir + "feature_transform"); } else { meansPool = loadDensityFileAscii (dataDir + "means.ascii", -Float.MAX_VALUE); variancePool = loadDensityFileAscii (dataDir + "variances.ascii", varianceFloor); mixtureWeightsPool = loadMixtureWeightsAscii (dataDir + "mixture_weights.ascii", mixtureWeightFloor); matrixPool = loadTransitionMatricesAscii (dataDir + "transition_matrices.ascii"); } senonePool = createSenonePool(distFloor, varianceFloor); // load the HMM model file InputStream modelStream = getClass().getResourceAsStream(model); if (modelStream == null) { throw new IOException("can't find model " + model); } loadHMMPool(useCDUnits, modelStream, location + File.separator + model); } /** * Returns the map of context indepent units. The map can be accessed by unit name. * * @return the map of context independent units. */ public Map<String, Unit> getContextIndependentUnits() { return contextIndependentUnits; } /** * Creates the senone pool from the rest of the pools. * * @param distFloor the lowest allowed score * @param varianceFloor the lowest allowed variance * @return the senone pool */ private Pool createSenonePool(float distFloor, float varianceFloor) { Pool pool = new Pool("senones"); int numMixtureWeights = mixtureWeightsPool.size(); int numMeans = meansPool.size(); int numVariances = variancePool.size(); int numGaussiansPerSenone = mixtureWeightsPool.getFeature(NUM_GAUSSIANS_PER_STATE, 0); int numSenones = mixtureWeightsPool.getFeature(NUM_SENONES, 0); int whichGaussian = 0; logger.fine("NG " + numGaussiansPerSenone); logger.fine("NS " + numSenones); logger.fine("NMIX " + numMixtureWeights); logger.fine("NMNS " + numMeans); logger.fine("NMNS " + numVariances); assert numGaussiansPerSenone > 0; assert numMixtureWeights == numSenones; assert numVariances == numSenones * numGaussiansPerSenone; assert numMeans == numSenones * numGaussiansPerSenone; for (int i = 0; i < numSenones; i++) { MixtureComponent[] mixtureComponents = new MixtureComponent[numGaussiansPerSenone]; for (int j = 0; j < numGaussiansPerSenone; j++) { mixtureComponents[j] = new MixtureComponent( logMath, (float[]) meansPool.get(whichGaussian), (float[][]) meanTransformationMatrixPool.get(0), (float[]) meanTransformationVectorPool.get(0), (float[]) variancePool.get(whichGaussian), (float[][]) varianceTransformationMatrixPool.get(0), (float[]) varianceTransformationVectorPool.get(0), distFloor, varianceFloor); whichGaussian++; } Senone senone = new GaussianMixture( logMath, (float[]) mixtureWeightsPool.get(i), mixtureComponents, i); pool.put(i, senone); } return pool; } /** * Loads the Sphinx 3 acoustic model properties file, which is basically a normal system properties file. * * @param url the path to the acoustic properties file * @return a SphinxProperty object containing the acoustic properties, or null if there are no acoustic model * properties * @throws FileNotFoundException if the file cannot be found * @throws IOException if an error occurs while loading the data */ private SphinxProperties loadAcousticPropertiesFile(URL url) throws FileNotFoundException, IOException { //TODO what to do for prefix here // Ultimately we will be getting rid of this embedded // sphinx properties sheet. In the mean time String context = "acoustic." + getName() + "." + url; SphinxProperties.initContext(context, url); return (SphinxProperties.getSphinxProperties(context)); } /** * Loads the sphinx3 densityfile, a set of density arrays are created and placed in the given pool. * * @param path the name of the data * @param floor the minimum density allowed * @return a pool of loaded densities * @throws FileNotFoundException if a file cannot be found * @throws IOException if an error occurs while loading the data */ private Pool loadDensityFileAscii(String path, float floor) throws FileNotFoundException, IOException { int token_type; int numStates; int numStreams; int numGaussiansPerState; InputStream inputStream = getClass().getResourceAsStream(path); if (inputStream == null) { throw new FileNotFoundException("Error trying to read file " + location + path); } // 'false' argument refers to EOL is insignificant ExtendedStreamTokenizer est = new ExtendedStreamTokenizer(inputStream, '#', false); Pool pool = new Pool(path); logger.fine("Loading density file from: " + path); est.expectString("param"); numStates = est.getInt("numStates"); numStreams = est.getInt("numStreams"); numGaussiansPerState = est.getInt("numGaussiansPerState"); pool.setFeature(NUM_SENONES, numStates); pool.setFeature(NUM_STREAMS, numStreams); pool.setFeature(NUM_GAUSSIANS_PER_STATE, numGaussiansPerState); for (int i = 0; i < numStates; i++) { est.expectString("mgau"); est.expectInt("mgau index", i); est.expectString("feat"); est.expectInt("feat index", 0); for (int j = 0; j < numGaussiansPerState; j++) { est.expectString("density"); est.expectInt("densityValue", j); float[] density = new float[vectorLength]; for (int k = 0; k < vectorLength; k++) { density[k] = est.getFloat("val"); if (density[k] < floor) { density[k] = floor; } // System.out.println(" " + i + " " + j + " " + k + // " " + density[k]); } int id = i * numGaussiansPerState + j; pool.put(id, density); } } est.close(); return pool; } /** * Loads the sphinx3 densityfile, a set of density arrays are created and placed in the given pool. * * @param path the name of the data * @param floor the minimum density allowed * @return a pool of loaded densities * @throws FileNotFoundException if a file cannot be found * @throws IOException if an error occurs while loading the data */ private Pool loadDensityFileBinary(String path, float floor) throws FileNotFoundException, IOException { int token_type; int numStates; int numStreams; int numGaussiansPerState; Properties props = new Properties(); int blockSize = 0; DataInputStream dis = readS3BinaryHeader(location, path, props); String version = props.getProperty("version"); boolean doCheckSum; if (version == null || !version.equals(DENSITY_FILE_VERSION)) { throw new IOException("Unsupported version in " + path); } String checksum = props.getProperty("chksum0"); doCheckSum = (checksum != null && checksum.equals("yes")); numStates = readInt(dis); numStreams = readInt(dis); numGaussiansPerState = readInt(dis); int[] vectorLength = new int[numStreams]; for (int i = 0; i < numStreams; i++) { vectorLength[i] = readInt(dis); } int rawLength = readInt(dis); //System.out.println("Nstates " + numStates); //System.out.println("Nstreams " + numStreams); //System.out.println("NgaussiansPerState " + numGaussiansPerState); //System.out.println("vectorLength " + vectorLength.length); //System.out.println("rawLength " + rawLength); for (int i = 0; i < numStreams; i++) { blockSize += vectorLength[i]; } assert rawLength == numGaussiansPerState * blockSize * numStates; assert numStreams == 1; Pool pool = new Pool(path); pool.setFeature(NUM_SENONES, numStates); pool.setFeature(NUM_STREAMS, numStreams); pool.setFeature(NUM_GAUSSIANS_PER_STATE, numGaussiansPerState); int r = 0; for (int i = 0; i < numStates; i++) { for (int j = 0; j < numStreams; j++) { for (int k = 0; k < numGaussiansPerState; k++) { float[] density = readFloatArray(dis, vectorLength[j]); floorData(density, floor); pool.put(i * numGaussiansPerState + k, density); } } } int checkSum = readInt(dis); // BUG: not checking the check sum yet. dis.close(); return pool; } /** * Reads the S3 binary hearder from the given location+path. Adds header information to the given set of * properties. * * @param location the location of the file * @param path the name of the file * @param props the properties * @return the input stream positioned after the header * @throws IOException on error */ protected DataInputStream readS3BinaryHeader(String location, String path, Properties props) throws IOException { // System.out.println("resource: " + path + ", " + getClass()); InputStream inputStream = getClass().getResourceAsStream(path); if (inputStream == null) { throw new IOException("Can't open " + path); } DataInputStream dis = new DataInputStream(new BufferedInputStream( inputStream)); String id = readWord(dis); if (!id.equals("s3")) { throw new IOException("Not proper s3 binary file " + location + path); } String name; while ((name = readWord(dis)) != null) { if (!name.equals("endhdr")) { String value = readWord(dis); props.setProperty(name, value); } else { break; } } int byteOrderMagic = dis.readInt(); if (byteOrderMagic == BYTE_ORDER_MAGIC) { // System.out.println("Not swapping " + path); swap = false; } else if (byteSwap(byteOrderMagic) == BYTE_ORDER_MAGIC) { // System.out.println("SWAPPING " + path); swap = true; } else { throw new IOException("Corrupt S3 file " + location + path); } return dis; } /** * Reads the next word (text separated by whitespace) from the given stream * * @param dis the input stream * @return the next word * @throws IOException on error */ String readWord(DataInputStream dis) throws IOException { StringBuffer sb = new StringBuffer(); char c; // skip leading whitespace do { c = readChar(dis); } while (Character.isWhitespace(c)); // read the word do { sb.append(c); c = readChar(dis); } while (!Character.isWhitespace(c)); return sb.toString(); } /** * Reads a single char from the stream * * @param dis the stream to read * @return the next character on the stream * @throws IOException if an error occurs */ private char readChar(DataInputStream dis) throws IOException { return (char) dis.readByte(); } /** * swap a 32 bit word * * @param val the value to swap * @return the swapped value */ private int byteSwap(int val) { return ((0xff & (val >> 24)) | (0xff00 & (val >> 8)) | (0xff0000 & (val << 8)) | (0xff000000 & (val << 24))); } /** * Read an integer from the input stream, byte-swapping as necessary * * @param dis the inputstream * @return an integer value * @throws IOException on error */ protected int readInt(DataInputStream dis) throws IOException { if (swap) { return Utilities.readLittleEndianInt(dis); } else { return dis.readInt(); } } /** * Read a float from the input stream, byte-swapping as necessary * * @param dis the inputstream * @return a floating pint value * @throws IOException on error */ protected float readFloat(DataInputStream dis) throws IOException { float val; if (swap) { val = Utilities.readLittleEndianFloat(dis); } else { val = dis.readFloat(); } return val; } // Do we need the method nonZeroFloor?? /** * If a data point is non-zero and below 'floor' make it equal to floor (don't floor zero values though). * * @param data the data to floor * @param floor the floored value */ protected void nonZeroFloor(float[] data, float floor) { for (int i = 0; i < data.length; i++) { if (data[i] != 0.0 && data[i] < floor) { data[i] = floor; } } } /** * If a data point is below 'floor' make it equal to floor. * * @param data the data to floor * @param floor the floored value */ private void floorData(float[] data, float floor) { for (int i = 0; i < data.length; i++) { if (data[i] < floor) { data[i] = floor; } } } /** * Normalize the given data * * @param data the data to normalize */ protected void normalize(float[] data) { float sum = 0; for (int i = 0; i < data.length; i++) { sum += data[i]; } if (sum != 0.0f) { for (int i = 0; i < data.length; i++) { data[i] = data[i] / sum; } } } /** * Dump the data * * @param name the name of the data * @param data the data itself */ private void dumpData(String name, float[] data) { System.out.println(" ----- " + name + " -----------"); for (int i = 0; i < data.length; i++) { System.out.println(name + " " + i + ": " + data[i]); } } /** * Convert to log math * * @param data the data to normalize */ // linearToLog returns a float, so zero values in linear scale // should return -Float.MAX_VALUE. protected void convertToLogMath(float[] data) { for (int i = 0; i < data.length; i++) { data[i] = logMath.linearToLog(data[i]); } } /** * Reads the given number of floats from the stream and returns them in an array of floats * * @param dis the stream to read data from * @param size the number of floats to read * @return an array of size float elements * @throws IOException if an exception occurs */ protected float[] readFloatArray(DataInputStream dis, int size) throws IOException { float[] data = new float[size]; for (int i = 0; i < size; i++) { data[i] = readFloat(dis); } return data; } /** * Loads the sphinx3 densityfile, a set of density arrays are created and placed in the given pool. * * @param useCDUnits if true, loads also the context dependent units * @param inputStream the open input stream to use * @param path the path to a density file * @return a pool of loaded densities * @throws FileNotFoundException if a file cannot be found * @throws IOException if an error occurs while loading the data */ protected Pool loadHMMPool(boolean useCDUnits, InputStream inputStream, String path) throws FileNotFoundException, IOException { int token_type; int numBase; int numTri; int numStateMap; int numTiedState; int numStatePerHMM; int numContextIndependentTiedState; int numTiedTransitionMatrices; ExtendedStreamTokenizer est = new ExtendedStreamTokenizer (inputStream, '#', false); Pool pool = new Pool(path); logger.fine("Loading HMM file from: " + path); est.expectString(MODEL_VERSION); numBase = est.getInt("numBase"); est.expectString("n_base"); numTri = est.getInt("numTri"); est.expectString("n_tri"); numStateMap = est.getInt("numStateMap"); est.expectString("n_state_map"); numTiedState = est.getInt("numTiedState"); est.expectString("n_tied_state"); numContextIndependentTiedState = est.getInt("numContextIndependentTiedState"); est.expectString("n_tied_ci_state"); numTiedTransitionMatrices = est.getInt("numTiedTransitionMatrices"); est.expectString("n_tied_tmat"); numStatePerHMM = numStateMap / (numTri + numBase); assert numTiedState == mixtureWeightsPool.getFeature(NUM_SENONES, 0); assert numTiedTransitionMatrices == matrixPool.size(); // Load the base phones for (int i = 0; i < numBase; i++) { String name = est.getString(); String left = est.getString(); String right = est.getString(); String position = est.getString(); String attribute = est.getString(); int tmat = est.getInt("tmat"); int[] stid = new int[numStatePerHMM - 1]; for (int j = 0; j < numStatePerHMM - 1; j++) { stid[j] = est.getInt("j"); assert stid[j] >= 0 && stid[j] < numContextIndependentTiedState; } est.expectString("N"); assert left.equals("-"); assert right.equals("-"); assert position.equals("-"); assert tmat < numTiedTransitionMatrices; Unit unit = unitManager.getUnit(name, attribute.equals(FILLER)); contextIndependentUnits.put(unit.getName(), unit); if (logger.isLoggable(Level.FINE)) { logger.fine("Loaded " + unit); } // The first filler if (unit.isFiller() && unit.getName().equals(SILENCE_CIPHONE)) { unit = UnitManager.SILENCE; } float[][] transitionMatrix = (float[][]) matrixPool.get(tmat); SenoneSequence ss = getSenoneSequence(stid); HMM hmm = new SenoneHMM(unit, ss, transitionMatrix, HMMPosition.lookup(position)); hmmManager.put(hmm); } // Load the context dependent phones. If the useCDUnits // property is false, the CD phones will not be created, but // the values still need to be read in from the file. String lastUnitName = ""; Unit lastUnit = null; int[] lastStid = null; SenoneSequence lastSenoneSequence = null; for (int i = 0; i < numTri; i++) { String name = est.getString(); String left = est.getString(); String right = est.getString(); String position = est.getString(); String attribute = est.getString(); int tmat = est.getInt("tmat"); int[] stid = new int[numStatePerHMM - 1]; for (int j = 0; j < numStatePerHMM - 1; j++) { stid[j] = est.getInt("j"); assert stid[j] >= numContextIndependentTiedState && stid[j] < numTiedState; } est.expectString("N"); assert !left.equals("-"); assert !right.equals("-"); assert !position.equals("-"); assert attribute.equals("n/a"); assert tmat < numTiedTransitionMatrices; if (useCDUnits) { Unit unit = null; String unitName = (name + " " + left + " " + right); if (unitName.equals(lastUnitName)) { unit = lastUnit; } else { Unit[] leftContext = new Unit[1]; leftContext[0] = contextIndependentUnits.get(left); Unit[] rightContext = new Unit[1]; rightContext[0] = contextIndependentUnits.get(right); Context context = LeftRightContext.get(leftContext, rightContext); unit = unitManager.getUnit(name, false, context); } lastUnitName = unitName; lastUnit = unit; if (logger.isLoggable(Level.FINE)) { logger.fine("Loaded " + unit); } float[][] transitionMatrix = (float[][]) matrixPool.get(tmat); SenoneSequence ss = lastSenoneSequence; if (ss == null || !sameSenoneSequence(stid, lastStid)) { ss = getSenoneSequence(stid); } lastSenoneSequence = ss; lastStid = stid; HMM hmm = new SenoneHMM(unit, ss, transitionMatrix, HMMPosition.lookup(position)); hmmManager.put(hmm); } } est.close(); return pool; } /** * Returns true if the given senone sequence IDs are the same. * * @return true if the given senone sequence IDs are the same, false otherwise */ protected boolean sameSenoneSequence(int[] ssid1, int[] ssid2) { if (ssid1.length == ssid2.length) { for (int i = 0; i < ssid1.length; i++) { if (ssid1[i] != ssid2[i]) { return false; } } return true; } else { return false; } } /** * Gets the senone sequence representing the given senones * * @param stateid is the array of senone state ids * @return the senone sequence associated with the states */ protected SenoneSequence getSenoneSequence(int[] stateid) { Senone[] senones = new Senone[stateid.length]; for (int i = 0; i < stateid.length; i++) { senones[i] = (Senone) senonePool.get(stateid[i]); } return new SenoneSequence(senones); } /** * Loads the mixture weights * * @param path the path to the mixture weight file * @param floor the minimum mixture weight allowed * @return a pool of mixture weights * @throws FileNotFoundException if a file cannot be found * @throws IOException if an error occurs while loading the data */ private Pool loadMixtureWeightsAscii(String path, float floor) throws FileNotFoundException, IOException { logger.fine("Loading mixture weights from: " + path); int numStates; int numStreams; int numGaussiansPerState; InputStream inputStream = StreamFactory.getInputStream(location, path); Pool pool = new Pool(path); ExtendedStreamTokenizer est = new ExtendedStreamTokenizer(inputStream, '#', false); est.expectString("mixw"); numStates = est.getInt("numStates"); numStreams = est.getInt("numStreams"); numGaussiansPerState = est.getInt("numGaussiansPerState"); pool.setFeature(NUM_SENONES, numStates); pool.setFeature(NUM_STREAMS, numStreams); pool.setFeature(NUM_GAUSSIANS_PER_STATE, numGaussiansPerState); for (int i = 0; i < numStates; i++) { est.expectString("mixw"); est.expectString("[" + i); est.expectString("0]"); float total = est.getFloat("total"); float[] logMixtureWeight = new float[numGaussiansPerState]; for (int j = 0; j < numGaussiansPerState; j++) { float val = est.getFloat("mixwVal"); if (val < floor) { val = floor; } logMixtureWeight[j] = val; } convertToLogMath(logMixtureWeight); pool.put(i, logMixtureWeight); } est.close(); return pool; } /** * Loads the mixture weights (Binary) * * @param path the path to the mixture weight file * @param floor the minimum mixture weight allowed * @return a pool of mixture weights * @throws FileNotFoundException if a file cannot be found * @throws IOException if an error occurs while loading the data */ private Pool loadMixtureWeightsBinary(String path, float floor) throws FileNotFoundException, IOException { logger.fine("Loading mixture weights from: " + path); int numStates; int numStreams; int numGaussiansPerState; int numValues; Properties props = new Properties(); DataInputStream dis = readS3BinaryHeader(location, path, props); String version = props.getProperty("version"); boolean doCheckSum; if (version == null || !version.equals(MIXW_FILE_VERSION)) { throw new IOException("Unsupported version in " + path); } String checksum = props.getProperty("chksum0"); doCheckSum = (checksum != null && checksum.equals("yes")); Pool pool = new Pool(path); numStates = readInt(dis); numStreams = readInt(dis); numGaussiansPerState = readInt(dis); numValues = readInt(dis); assert numValues == numStates * numStreams * numGaussiansPerState; assert numStreams == 1; pool.setFeature(NUM_SENONES, numStates); pool.setFeature(NUM_STREAMS, numStreams); pool.setFeature(NUM_GAUSSIANS_PER_STATE, numGaussiansPerState); for (int i = 0; i < numStates; i++) { float[] logMixtureWeight = readFloatArray(dis, numGaussiansPerState); normalize(logMixtureWeight); floorData(logMixtureWeight, floor); convertToLogMath(logMixtureWeight); pool.put(i, logMixtureWeight); } dis.close(); return pool; } /** * Loads the transition matrices * * @param path the path to the transitions matrices * @return a pool of transition matrices * @throws FileNotFoundException if a file cannot be found * @throws IOException if an error occurs while loading the data */ protected Pool loadTransitionMatricesAscii(String path) throws FileNotFoundException, IOException { InputStream inputStream = StreamFactory.getInputStream(location, path); logger.fine("Loading transition matrices from: " + path); int numMatrices; int numStates; Pool pool = new Pool(path); ExtendedStreamTokenizer est = new ExtendedStreamTokenizer(inputStream, '#', false); est.expectString("tmat"); numMatrices = est.getInt("numMatrices"); numStates = est.getInt("numStates"); logger.fine("with " + numMatrices + " and " + numStates + " states, in " + (sparseForm ? "sparse" : "dense") + " form"); // read in the matrices for (int i = 0; i < numMatrices; i++) { est.expectString("tmat"); est.expectString("[" + i + "]"); float[][] tmat = new float[numStates][numStates]; for (int j = 0; j < numStates; j++) { for (int k = 0; k < numStates; k++) { // the last row is just zeros, so we just do // the first (numStates - 1) rows if (j < numStates - 1) { if (sparseForm) { if (k == j || k == j + 1) { tmat[j][k] = est.getFloat("tmat value"); } } else { tmat[j][k] = est.getFloat("tmat value"); } } tmat[j][k] = logMath.linearToLog(tmat[j][k]); if (logger.isLoggable(Level.FINE)) { logger.fine("tmat j " + j + " k " + k + " tm " + tmat[j][k]); } } } pool.put(i, tmat); } est.close(); return pool; } /** * Loads the transition matrices (Binary) * * @param path the path to the transitions matrices * @return a pool of transition matrices * @throws FileNotFoundException if a file cannot be found * @throws IOException if an error occurs while loading the data */ protected Pool loadTransitionMatricesBinary(String path) throws FileNotFoundException, IOException { logger.fine("Loading transition matrices from: " + path); int numMatrices; int numStates; int numRows; int numValues; Properties props = new Properties(); DataInputStream dis = readS3BinaryHeader(location, path, props); String version = props.getProperty("version"); boolean doCheckSum; if (version == null || !version.equals(TMAT_FILE_VERSION)) { throw new IOException("Unsupported version in " + path); } String checksum = props.getProperty("chksum0"); doCheckSum = (checksum != null && checksum.equals("yes")); Pool pool = new Pool(path); numMatrices = readInt(dis); numRows = readInt(dis); numStates = readInt(dis); numValues = readInt(dis); assert numValues == numStates * numRows * numMatrices; for (int i = 0; i < numMatrices; i++) { float[][] tmat = new float[numStates][]; // last row should be zeros tmat[numStates - 1] = new float[numStates]; convertToLogMath(tmat[numStates - 1]); for (int j = 0; j < numRows; j++) { tmat[j] = readFloatArray(dis, numStates); nonZeroFloor(tmat[j], 0f); normalize(tmat[j]); convertToLogMath(tmat[j]); } pool.put(i, tmat); } dis.close(); return pool; } /** * Loads the transform matrices (Binary) * * @param path the path to the transform matrix * @return a transform matrix * @throws java.io.FileNotFoundException if a file cannot be found * @throws java.io.IOException if an error occurs while loading the data */ protected float[][] loadTransformMatrix(String path) throws FileNotFoundException, IOException { logger.fine("Loading transform matrix from: " + path); int numRows; int numValues; int num; Properties props = new Properties(); DataInputStream dis; try { dis = readS3BinaryHeader(location, path, props); } catch (Exception e) { return null; } String version = props.getProperty("version"); boolean doCheckSum; if (version == null || !version.equals(TRANSFORM_FILE_VERSION)) { throw new IOException("Unsupported version in " + path); } String checksum = props.getProperty("chksum0"); doCheckSum = (checksum != null && checksum.equals("yes")); readInt(dis); numRows = readInt(dis); numValues = readInt(dis); num = readInt(dis); assert num == numRows * numValues; float[][] result = new float[numRows][]; for (int i = 0; i < numRows; i++) { result[i] = readFloatArray(dis, numValues); } dis.close(); return result; } /** * Creates a pool with a single identity matrix in it. * * @param name the name of the pool * @return the pool with the matrix */ private Pool createDummyMatrixPool(String name) { Pool pool = new Pool(name); float[][] matrix = new float[vectorLength][vectorLength]; logger.fine("creating dummy matrix pool " + name); for (int i = 0; i < vectorLength; i++) { for (int j = 0; j < vectorLength; j++) { if (i == j) { matrix[i][j] = 1.0F; } else { matrix[i][j] = 0.0F; } } } pool.put(0, matrix); return pool; } /** * Creates a pool with a single zero vector in it. * * @param name the name of the pool * @return the pool with the vector */ private Pool createDummyVectorPool(String name) { logger.fine("creating dummy vector pool " + name); Pool pool = new Pool(name); float[] vector = new float[vectorLength]; for (int i = 0; i < vectorLength; i++) { vector[i] = 0.0f; } pool.put(0, vector); return pool; } /** * Gets the pool of means for this loader * * @return the pool */ public Pool getMeansPool() { return meansPool; } /** * Gets the pool of means transformation matrices for this loader * * @return the pool */ public Pool getMeansTransformationMatrixPool() { return meanTransformationMatrixPool; } /** * Gets the pool of means transformation vectors for this loader * * @return the pool */ public Pool getMeansTransformationVectorPool() { return meanTransformationVectorPool; } /* * Gets the variance pool * * @return the pool */ public Pool getVariancePool() { return variancePool; } /** * Gets the variance transformation matrix pool * * @return the pool */ public Pool getVarianceTransformationMatrixPool() { return varianceTransformationMatrixPool; } /** * Gets the pool of variance transformation vectors for this loader * * @return the pool */ public Pool getVarianceTransformationVectorPool() { return varianceTransformationVectorPool; } /* * Gets the mixture weight pool * * @return the pool */ public Pool getMixtureWeightPool() { return mixtureWeightsPool; } /* * Gets the transition matrix pool * * @return the pool */ public Pool getTransitionMatrixPool() { return matrixPool; } /* * Gets the senone pool for this loader * * @return the pool */ public Pool getSenonePool() { return senonePool; } /* * Gets the transform matrix for this loader * * @return the pool */ public float[][] getTransformMatrix() { return transformMatrix; } /** * Returns the size of the left context for context dependent units * * @return the left context size */ public int getLeftContextSize() { return CONTEXT_SIZE; } /** * Returns the size of the right context for context dependent units * * @return the left context size */ public int getRightContextSize() { return CONTEXT_SIZE; } /** * Returns the hmm manager associated with this loader * * @return the hmm Manager */ public HMMManager getHMMManager() { return hmmManager; } /** Log info about this loader */ public void logInfo() { logger.info("Sphinx3Loader"); meansPool.logInfo(logger); variancePool.logInfo(logger); matrixPool.logInfo(logger); senonePool.logInfo(logger); meanTransformationMatrixPool.logInfo(logger); meanTransformationVectorPool.logInfo(logger); varianceTransformationMatrixPool.logInfo(logger); varianceTransformationVectorPool.logInfo(logger); mixtureWeightsPool.logInfo(logger); senonePool.logInfo(logger); logger.info("Context Independent Unit Entries: " + contextIndependentUnits.size()); hmmManager.logInfo(logger); } } diff --git a/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/TiedStateAcousticModel.java b/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/TiedStateAcousticModel.java index 29028b32..b6ed2a35 100644 --- a/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/TiedStateAcousticModel.java +++ b/src/sphinx4/edu/cmu/sphinx/linguist/acoustic/tiedstate/TiedStateAcousticModel.java @@ -1,606 +1,608 @@ /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.linguist.acoustic.tiedstate; +// Placeholder for a package import + import edu.cmu.sphinx.linguist.acoustic.*; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.util.props.*; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Loads a tied-state acoustic model generated by the Sphinx-3 trainer. * <p/> * <p/> * It is not the goal of this documentation to provide an explanation about the concept of HMMs. The explanation below * is superficial, and provided only in a way that the files in the acoustic model package make sense. * <p/> * An HMM models a process using a sequence of states. Associated with each state, there is a probability density * function. A popular choice for this function is a Gaussian mixture, that is, a summation of Gaussians. As you may * recall, a single Gaussian is defined by a mean and a variance, or, in the case of a multidimensional Gaussian, by a * mean vector and a covariance matrix, or, under some simplifying assumptions, a variance vector. The "means" and * "variances" files in the "continuous" directory contain exactly this: a table in which each line contains a mean * vector or a variance vector respectively. The dimension of these vectors is the same as the incoming data, the * encoded speech signal. The Gaussian mixture is a summation of Gaussians, with different weights for different * Gaussians. The "mixture_weights" file contains this: each line contains the weights for a combination of Gaussians. * <p/> * The HMM is a model with a set of states. The transitions between states have an associated probability. These * probabilities make up the transition matrices stored in the "transition_matrices" file. * <p/> * The files in the "continuous" directory are, therefore, tables, or pools, of means, variances, mixture weights, and * transition probabilities. * <p/> * The dictionary is a file that maps words to their phonetic transcriptions, that is, it maps words to sequences of * phonemes. * <p/> * The language model contains information about probabilities of words in a language. These probabilities could be for * individual words or for sequences of two or three words. * <p/> * The model definition file in a way ties everything together. If the recognition system models phonemes, there is an * HMM for each phoneme. The model definition file has one line for each phoneme. The phoneme could be in a context * dependent or independent. Each line, therefore, identifies a unique HMM. This line has the phoneme identification, * the non-required left or right context, the index of a transition matrix, and, for each state, the index of a mean * vector, a variance vector, and a set of mixture weights. */ @SuppressWarnings({"UnnecessaryLocalVariable"}) public class TiedStateAcousticModel implements AcousticModel { /** The property that defines the component used to load the acoustic model */ @S4Component(type = Loader.class) public final static String PROP_LOADER = "loader"; /** The property that defines the unit manager */ @S4Component(type = UnitManager.class) public final static String PROP_UNIT_MANAGER = "unitManager"; /** Controls whether we generate composites or CI units when no context is given during a lookup. */ @S4Boolean(defaultValue = true) public final static String PROP_USE_COMPOSITES = "useComposites"; /** The default value of PROP_USE_COMPOSITES. */ public final static boolean PROP_USE_COMPOSITES_DEFAULT = true; /** Model load timer */ protected final static String TIMER_LOAD = "AM_Load"; // ----------------------------- // Configured variables // ----------------------------- protected String name; private Logger logger; protected Loader loader; protected UnitManager unitManager; private boolean useComposites = false; private Properties properties; // ---------------------------- // internal variables // ----------------------------- transient protected Timer loadTimer; transient private Map<String, SenoneSequence> compositeSenoneSequenceCache = new HashMap<String, SenoneSequence>(); private boolean allocated = false; /* (non-Javadoc) * @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet) */ public void newProperties(PropertySheet ps) throws PropertyException { loader = (Loader) ps.getComponent(PROP_LOADER); unitManager = (UnitManager) ps.getComponent(PROP_UNIT_MANAGER ); useComposites = ps.getBoolean(PROP_USE_COMPOSITES); logger = ps.getLogger(); } /** * initialize this acoustic model with the given name and context. * * @throws IOException if the model could not be loaded */ public void allocate() throws IOException { if (!allocated) { this.loadTimer = Timer.getTimer(TIMER_LOAD); loadTimer.start(); loader.load(); loadTimer.stop(); logInfo(); allocated = true; } } /* (non-Javadoc) * @see edu.cmu.sphinx.linguist.acoustic.AcousticModel#deallocate() */ public void deallocate() { } /** * Returns the name of this AcousticModel, or null if it has no name. * * @return the name of this AcousticModel, or null if it has no name */ public String getName() { return name; } /** * Gets a composite HMM for the given unit and context * * @param unit the unit for the hmm * @param position the position of the unit within the word * @return a composite HMM */ private HMM getCompositeHMM(Unit unit, HMMPosition position) { if (true) { // use a true composite Unit ciUnit = unitManager.getUnit(unit.getName(), unit.isFiller(), Context.EMPTY_CONTEXT); SenoneSequence compositeSequence = getCompositeSenoneSequence(unit, position); SenoneHMM contextIndependentHMM = (SenoneHMM) lookupNearestHMM(ciUnit, HMMPosition.UNDEFINED, true); float[][] tmat = contextIndependentHMM.getTransitionMatrix(); return new SenoneHMM(unit, compositeSequence, tmat, position); } else { // BUG: just a test. use CI units instead of composites Unit ciUnit = lookupUnit(unit.getName()); assert unit.isContextDependent(); if (ciUnit == null) { logger.severe("Can't find HMM for " + unit.getName()); } assert ciUnit != null; assert !ciUnit.isContextDependent(); HMMManager mgr = loader.getHMMManager(); HMM hmm = mgr.get(HMMPosition.UNDEFINED, ciUnit); return hmm; } } /** * Given a unit, returns the HMM that best matches the given unit. If exactMatch is false and an exact match is not * found, then different word positions are used. If any of the contexts are non-silence filler units. a silence * filler unit is tried instead. * * @param unit the unit of interest * @param position the position of the unit of interest * @param exactMatch if true, only an exact match is acceptable. * @return the HMM that best matches, or null if no match could be found. */ public HMM lookupNearestHMM(Unit unit, HMMPosition position, boolean exactMatch) { if (exactMatch) { return lookupHMM(unit, position); } else { HMMManager mgr = loader.getHMMManager(); HMM hmm = mgr.get(position, unit); if (hmm != null) { return hmm; } // no match, try a composite if (useComposites && hmm == null) { if (isComposite(unit)) { hmm = getCompositeHMM(unit, position); if (hmm != null) { mgr.put(hmm); } } } // no match, try at other positions if (hmm == null) { hmm = getHMMAtAnyPosition(unit); } // still no match, try different filler if (hmm == null) { hmm = getHMMInSilenceContext(unit, position); } // still no match, backoff to base phone if (hmm == null) { Unit ciUnit = lookupUnit(unit.getName()); assert unit.isContextDependent(); if (ciUnit == null) { logger.severe("Can't find HMM for " + unit.getName()); } assert ciUnit != null; assert !ciUnit.isContextDependent(); hmm = mgr.get(HMMPosition.UNDEFINED, ciUnit); } assert hmm != null; // System.out.println("PROX match for " // + unit + " at " + position + ":" + hmm); return hmm; } } /** * Determines if a unit is a composite unit * * @param unit the unit to test * @return true if the unit is missing a right context */ private boolean isComposite(Unit unit) { if (unit.isFiller()) { return false; } Context context = unit.getContext(); if (context instanceof LeftRightContext) { LeftRightContext lrContext = (LeftRightContext) context; if (lrContext.getRightContext() == null) { return true; } if (lrContext.getLeftContext() == null) { return true; } } return false; } /** * Looks up the context independent unit given the name * * @param name the name of the unit * @return the unit or null if the unit was not found */ private Unit lookupUnit(String name) { return loader.getContextIndependentUnits().get(name); } /** * Returns an iterator that can be used to iterate through all the HMMs of the acoustic model * * @return an iterator that can be used to iterate through all HMMs in the model. The iterator returns objects of * type <code>HMM</code>. */ public Iterator getHMMIterator() { return loader.getHMMManager().getIterator(); } /** * Returns an iterator that can be used to iterate through all the CI units in the acoustic model * * @return an iterator that can be used to iterate through all CI units. The iterator returns objects of type * <code>Unit</code> */ public Iterator<Unit> getContextIndependentUnitIterator() { return loader.getContextIndependentUnits().values().iterator(); } /** * Get a composite senone sequence given the unit The unit should have a LeftRightContext, where one or two of * 'left' or 'right' may be null to indicate that the match should succeed on any context. * * @param unit the unit */ public SenoneSequence getCompositeSenoneSequence(Unit unit, HMMPosition position) { Context context = unit.getContext(); SenoneSequence compositeSenoneSequence = null; compositeSenoneSequence = compositeSenoneSequenceCache.get(unit.toString()); if (logger.isLoggable(Level.FINE)) { logger.fine("getCompositeSenoneSequence: " + unit.toString() + ((compositeSenoneSequence != null) ? "Cached" : "")); } if (compositeSenoneSequence != null) { return compositeSenoneSequence; } // Iterate through all HMMs looking for // a) An hmm with a unit that has the proper base // b) matches the non-null context List<SenoneSequence> senoneSequenceList = new ArrayList<SenoneSequence>(); // collect all senone sequences that match the pattern for (Iterator i = getHMMIterator(); i.hasNext();) { SenoneHMM hmm = (SenoneHMM) i.next(); if (hmm.getPosition() == position) { Unit hmmUnit = hmm.getUnit(); if (hmmUnit.isPartialMatch(unit.getName(), context)) { if (logger.isLoggable(Level.FINE)) { logger.fine("collected: " + hmm.getUnit().toString()); } senoneSequenceList.add(hmm.getSenoneSequence()); } } } // couldn't find any matches, so at least include the CI unit if (senoneSequenceList.size() == 0) { Unit ciUnit = unitManager.getUnit(unit.getName(), unit.isFiller()); SenoneHMM baseHMM = lookupHMM(ciUnit, HMMPosition.UNDEFINED); senoneSequenceList.add(baseHMM.getSenoneSequence()); } // Add this point we have all of the senone sequences that // match the base/context pattern collected into the list. // Next we build a CompositeSenone consisting of all of the // senones in each position of the list. // First find the longest senone sequence int longestSequence = 0; for (int i = 0; i < senoneSequenceList.size(); i++) { SenoneSequence ss = senoneSequenceList.get(i); if (ss.getSenones().length > longestSequence) { longestSequence = ss.getSenones().length; } } // now collect all of the senones at each position into // arrays so we can create CompositeSenones from them // QUESTION: is is possible to have different size senone // sequences. For now lets assume the worst case. List<CompositeSenone> compositeSenones = new ArrayList<CompositeSenone>(); float logWeight = 0.0f; for (int i = 0; i < longestSequence; i++) { Set<Senone> compositeSenoneSet = new HashSet<Senone>(); for (int j = 0; j < senoneSequenceList.size(); j++) { SenoneSequence senoneSequence = senoneSequenceList.get(j); if (i < senoneSequence.getSenones().length) { Senone senone = senoneSequence.getSenones()[i]; compositeSenoneSet.add(senone); } } compositeSenones.add(CompositeSenone.create( compositeSenoneSet, logWeight)); } compositeSenoneSequence = SenoneSequence.create(compositeSenones); compositeSenoneSequenceCache.put(unit.toString(), compositeSenoneSequence); if (logger.isLoggable(Level.FINE)) { logger.fine(unit.toString() + " consists of " + compositeSenones.size() + " composite senones"); if (logger.isLoggable(Level.FINEST)) { compositeSenoneSequence.dump("am"); } } return compositeSenoneSequence; } /** * Returns the size of the left context for context dependent units * * @return the left context size */ public int getLeftContextSize() { return loader.getLeftContextSize(); } /** * Returns the size of the right context for context dependent units * * @return the left context size */ public int getRightContextSize() { return loader.getRightContextSize(); } /** * Given a unit, returns the HMM that exactly matches the given unit. * * @param unit the unit of interest * @param position the position of the unit of interest * @return the HMM that exactly matches, or null if no match could be found. */ private SenoneHMM lookupHMM(Unit unit, HMMPosition position) { return (SenoneHMM) loader.getHMMManager().get(position, unit); } /** * Creates a string useful for tagging a composite senone sequence * * @param base the base unit * @param context the context * @return the tag associated with the composite senone sequence */ private String makeTag(Unit base, Context context) { StringBuffer sb = new StringBuffer(); sb.append("("); sb.append(base.getName()); sb.append("-"); sb.append(context.toString()); sb.append(")"); return sb.toString(); } /** Dumps information about this model to the logger */ protected void logInfo() { if (loader != null) { loader.logInfo(); } logger.info("CompositeSenoneSequences: " + compositeSenoneSequenceCache.size()); } /** * Searches an hmm at any position * * @param unit the unit to search for * @return hmm the hmm or null if it was not found */ private SenoneHMM getHMMAtAnyPosition(Unit unit) { SenoneHMM hmm = null; HMMManager mgr = loader.getHMMManager(); for (Iterator i = HMMPosition.iterator(); hmm == null && i.hasNext();) { HMMPosition pos = (HMMPosition) i.next(); hmm = (SenoneHMM) mgr.get(pos, unit); } return hmm; } /** * Given a unit, search for the HMM associated with this unit by replacing all non-silence filler contexts with the * silence filler context * * @param unit the unit of interest * @return the associated hmm or null */ private SenoneHMM getHMMInSilenceContext(Unit unit, HMMPosition position) { SenoneHMM hmm = null; HMMManager mgr = loader.getHMMManager(); Context context = unit.getContext(); if (context instanceof LeftRightContext) { LeftRightContext lrContext = (LeftRightContext) context; Unit[] lc = lrContext.getLeftContext(); Unit[] rc = lrContext.getRightContext(); Unit[] nlc; Unit[] nrc; if (hasNonSilenceFiller(lc)) { nlc = replaceNonSilenceFillerWithSilence(lc); } else { nlc = lc; } if (hasNonSilenceFiller(rc)) { nrc = replaceNonSilenceFillerWithSilence(rc); } else { nrc = rc; } if (nlc != lc || nrc != rc) { Context newContext = LeftRightContext.get(nlc, nrc); Unit newUnit = unitManager.getUnit(unit.getName(), unit.isFiller(), newContext); hmm = (SenoneHMM) mgr.get(position, newUnit); if (hmm == null) { hmm = getHMMAtAnyPosition(newUnit); } } } return hmm; } /** * Some debugging code that looks for illformed contexts * * @param msg the message associated with the check * @param c the context to check */ private void checkNull(String msg, Unit[] c) { for (int i = 0; i < c.length; i++) { if (c[i] == null) { System.out.println("null at index " + i + " of " + msg); } } } /** * Returns true if the array of units contains a non-silence filler * * @param units the units to check * @return true if the array contains a filler that is not the silence filler */ private boolean hasNonSilenceFiller(Unit[] units) { if (units == null) { return false; } for (int i = 0; i < units.length; i++) { if (units[i].isFiller() && !units[i].equals(UnitManager.SILENCE)) { return true; } } return false; } /** * Returns a unit array with all non-silence filler units replaced with the silence filler a non-silence filler * * @param context the context to check * @return true if the array contains a filler that is not the silence filler */ private Unit[] replaceNonSilenceFillerWithSilence(Unit[] context) { Unit[] replacementContext = new Unit[context.length]; for (int i = 0; i < context.length; i++) { if (context[i].isFiller() && !context[i].equals(UnitManager.SILENCE)) { replacementContext[i] = UnitManager.SILENCE; } else { replacementContext[i] = context[i]; } } return replacementContext; } /** * Returns the properties of this acoustic model. * * @return the properties of this acoustic model */ public Properties getProperties() { if (properties == null) { properties = new Properties(); try { properties.load (getClass().getResource("model.props").openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } return properties; } }
false
false
null
null
diff --git a/luni/src/main/java/java/net/InetAddress.java b/luni/src/main/java/java/net/InetAddress.java index 1b06638f0..16e3a0c77 100644 --- a/luni/src/main/java/java/net/InetAddress.java +++ b/luni/src/main/java/java/net/InetAddress.java @@ -1,1092 +1,1092 @@ /* * 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 java.net; import dalvik.system.BlockGuard; import java.io.FileDescriptor; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.ObjectStreamField; import java.io.Serializable; import java.security.AccessController; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import org.apache.harmony.luni.platform.INetworkSystem; import org.apache.harmony.luni.platform.Platform; import org.apache.harmony.luni.util.PriviAction; /** * An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and * in practice you'll have an instance of either {@code Inet4Address} or {@code Inet6Address} (this * class cannot be instantiated directly). Most code does not need to distinguish between the two * families, and should use {@code InetAddress}. * * <p>An {@code InetAddress} may have a hostname (accessible via {@code getHostName}), but may not, * depending on how the {@code InetAddress} was created. * * <h4>IPv4 numeric address formats</h4> * <p>The {@code getAllByName} method accepts IPv4 addresses in the following forms: * <ul> * <li>{@code "1.2.3.4"} - 1.2.3.4 * <li>{@code "1.2.3"} - 1.2.0.3 * <li>{@code "1.2"} - 1.0.0.2 * <li>{@code "16909060"} - 1.2.3.4 * </ul> * <p>In the first three cases, each number is treated as an 8-bit value between 0 and 255. * In the fourth case, the single number is treated as a 32-bit value representing the entire * address. * <p>Note that each numeric part can be expressed in decimal (as above) or hex. For example, * {@code "0x01020304"} is equivalent to 1.2.3.4 and {@code "0xa.0xb.0xc.0xd"} is equivalent * to 10.11.12.13. * * <p>Typically, only the four-dot decimal form ({@code "1.2.3.4"}) is ever used. Any method that * <i>returns</i> a textual numeric address will use four-dot decimal form. * * <h4>IPv6 numeric address formats</h4> * <p>The {@code getAllByName} method accepts IPv6 addresses in the following forms (this text * comes from <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a>, which you should consult * for full details of IPv6 addressing): * <ul> * <li><p>The preferred form is {@code x:x:x:x:x:x:x:x}, where the 'x's are the * hexadecimal values of the eight 16-bit pieces of the address. * Note that it is not necessary to write the leading zeros in an * individual field, but there must be at least one numeral in every * field (except for the case described in the next bullet). * Examples: * <pre> * FEDC:BA98:7654:3210:FEDC:BA98:7654:3210 * 1080:0:0:0:8:800:200C:417A</pre> * </li> * <li>Due to some methods of allocating certain styles of IPv6 * addresses, it will be common for addresses to contain long strings * of zero bits. In order to make writing addresses containing zero * bits easier a special syntax is available to compress the zeros. * The use of "::" indicates multiple groups of 16-bits of zeros. * The "::" can only appear once in an address. The "::" can also be * used to compress the leading and/or trailing zeros in an address. * * For example the following addresses: * <pre> * 1080:0:0:0:8:800:200C:417A a unicast address * FF01:0:0:0:0:0:0:101 a multicast address * 0:0:0:0:0:0:0:1 the loopback address * 0:0:0:0:0:0:0:0 the unspecified addresses</pre> * may be represented as: * <pre> * 1080::8:800:200C:417A a unicast address * FF01::101 a multicast address * ::1 the loopback address * :: the unspecified addresses</pre> * </li> * <li><p>An alternative form that is sometimes more convenient when dealing * with a mixed environment of IPv4 and IPv6 nodes is * {@code x:x:x:x:x:x:d.d.d.d}, where the 'x's are the hexadecimal values of * the six high-order 16-bit pieces of the address, and the 'd's are * the decimal values of the four low-order 8-bit pieces of the * address (standard IPv4 representation). Examples: * <pre> * 0:0:0:0:0:0:13.1.68.3 * 0:0:0:0:0:FFFF:129.144.52.38</pre> * or in compressed form: * <pre> * ::13.1.68.3 * ::FFFF:129.144.52.38</pre> * </li> * </ul> * <p>Scopes are given using a trailing {@code %} followed by the scope id, as in * {@code 1080::8:800:200C:417A%2} or {@code 1080::8:800:200C:417A%en0}. * See <a href="https://www.ietf.org/rfc/rfc4007.txt">RFC 4007</a> for more on IPv6's scoped * address architecture. * * <h4>DNS caching</h4> * <p>On Android, addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are * cached for 10 seconds. The underlying C library or OS may cache for longer, but you can control * the Java-level caching with the usual {@code "networkaddress.cache.ttl"} and * {@code "networkaddress.cache.negative.ttl"} system properties. These are parsed as integer * numbers of seconds, where the special value 0 means "don't cache" and -1 means "cache forever". * * <p>Note also that on Android &ndash; unlike the RI &ndash; the cache is not unbounded. The * current implementation caches around 512 entries, removed on a least-recently-used basis. * (Obviously, you should not rely on these details.) * * @see Inet4Address * @see Inet6Address */ public class InetAddress implements Serializable { /** Our Java-side DNS cache. */ private static final AddressCache addressCache = new AddressCache(); private final static INetworkSystem NETIMPL = Platform.getNetworkSystem(); private static final String ERRMSG_CONNECTION_REFUSED = "Connection refused"; private static final long serialVersionUID = 3286316764910316507L; String hostName; private static class WaitReachable { } private transient Object waitReachable = new WaitReachable(); private boolean reached; private int addrCount; int family = 0; byte[] ipaddress; /** * Constructs an {@code InetAddress}. * * Note: this constructor should not be used. Creating an InetAddress * without specifying whether it's an IPv4 or IPv6 address does not make * sense, because subsequent code cannot know which of of the subclasses' * methods need to be called to implement a given InetAddress method. The * proper way to create an InetAddress is to call new Inet4Address or * Inet6Address or to use one of the static methods that return * InetAddresses (e.g., getByAddress). That is why the API does not have * public constructors for any of these classes. */ InetAddress() {} /** * Compares this {@code InetAddress} instance against the specified address * in {@code obj}. Two addresses are equal if their address byte arrays have * the same length and if the bytes in the arrays are equal. * * @param obj * the object to be tested for equality. * @return {@code true} if both objects are equal, {@code false} otherwise. */ @Override public boolean equals(Object obj) { if (!(obj instanceof InetAddress)) { return false; } return Arrays.equals(this.ipaddress, ((InetAddress) obj).ipaddress); } /** * Returns the IP address represented by this {@code InetAddress} instance * as a byte array. The elements are in network order (the highest order * address byte is in the zeroth element). * * @return the address in form of a byte array. */ public byte[] getAddress() { return ipaddress.clone(); } static final Comparator<byte[]> SHORTEST_FIRST = new Comparator<byte[]>() { public int compare(byte[] a1, byte[] a2) { return a1.length - a2.length; } }; /** * Converts an array of byte arrays representing raw IP addresses of a host * to an array of InetAddress objects, sorting to respect the value of the * system property {@code "java.net.preferIPv6Addresses"}. * * @param rawAddresses the raw addresses to convert. * @param hostName the hostname corresponding to the IP address. * @return the corresponding InetAddresses, appropriately sorted. */ static InetAddress[] bytesToInetAddresses(byte[][] rawAddresses, String hostName) { // If we prefer IPv4, ignore the RFC3484 ordering we get from getaddrinfo // and always put IPv4 addresses first. Arrays.sort() is stable, so the // internal ordering will not be changed. if (!preferIPv6Addresses()) { Arrays.sort(rawAddresses, SHORTEST_FIRST); } // Convert the byte arrays to InetAddresses. InetAddress[] returnedAddresses = new InetAddress[rawAddresses.length]; for (int i = 0; i < rawAddresses.length; i++) { byte[] rawAddress = rawAddresses[i]; if (rawAddress.length == 16) { returnedAddresses[i] = new Inet6Address(rawAddress, hostName); } else if (rawAddress.length == 4) { returnedAddresses[i] = new Inet4Address(rawAddress, hostName); } else { // Cannot happen, because the underlying code only returns // addresses that are 4 or 16 bytes long. throw new AssertionError("Impossible address length " + rawAddress.length); } } return returnedAddresses; } /** * Gets all IP addresses associated with the given {@code host} identified * by name or literal IP address. The IP address is resolved by the * configured name service. If the host name is empty or {@code null} an * {@code UnknownHostException} is thrown. If the host name is a literal IP * address string an array with the corresponding single {@code InetAddress} * is returned. * * @param host the hostname or literal IP string to be resolved. * @return the array of addresses associated with the specified host. * @throws UnknownHostException if the address lookup fails. */ public static InetAddress[] getAllByName(String host) throws UnknownHostException { return getAllByNameImpl(host).clone(); } /** * Returns the InetAddresses for {@code host}. The returned array is shared * and must be cloned before it is returned to application code. */ static InetAddress[] getAllByNameImpl(String host) throws UnknownHostException { if (host == null || host.isEmpty()) { if (preferIPv6Addresses()) { return new InetAddress[] { Inet6Address.LOOPBACK, Inet4Address.LOOPBACK }; } else { return new InetAddress[] { Inet4Address.LOOPBACK, Inet6Address.LOOPBACK }; } } // Special-case "0" for legacy IPv4 applications. if (host.equals("0")) { return new InetAddress[] { Inet4Address.ANY }; } try { byte[] hBytes = ipStringToByteArray(host); if (hBytes.length == 4) { return (new InetAddress[] { new Inet4Address(hBytes) }); } else if (hBytes.length == 16) { return (new InetAddress[] { new Inet6Address(hBytes) }); } else { throw new UnknownHostException(wrongAddressLength()); } } catch (UnknownHostException e) { } SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkConnect(host, -1); } return lookupHostByName(host); } private static native String byteArrayToIpString(byte[] address); static native byte[] ipStringToByteArray(String address) throws UnknownHostException; private static String wrongAddressLength() { return "Invalid IP Address is neither 4 or 16 bytes"; } static boolean preferIPv6Addresses() { String propertyName = "java.net.preferIPv6Addresses"; String propertyValue = AccessController.doPrivileged(new PriviAction<String>(propertyName)); - return Boolean.getBoolean(propertyValue); + return Boolean.parseBoolean(propertyValue); } /** * Returns the address of a host according to the given host string name * {@code host}. The host string may be either a machine name or a dotted * string IP address. If the latter, the {@code hostName} field is * determined upon demand. {@code host} can be {@code null} which means that * an address of the loopback interface is returned. * * @param host * the hostName to be resolved to an address or {@code null}. * @return the {@code InetAddress} instance representing the host. * @throws UnknownHostException * if the address lookup fails. */ public static InetAddress getByName(String host) throws UnknownHostException { return getAllByNameImpl(host)[0]; } /** * Gets the textual representation of this IP address. * * @return the textual representation of host's IP address. */ public String getHostAddress() { return byteArrayToIpString(ipaddress); } /** * Gets the host name of this IP address. If the IP address could not be * resolved, the textual representation in a dotted-quad-notation is * returned. * * @return the corresponding string name of this IP address. */ public String getHostName() { try { if (hostName == null) { int address = 0; if (ipaddress.length == 4) { address = bytesToInt(ipaddress, 0); if (address == 0) { return hostName = byteArrayToIpString(ipaddress); } } hostName = getHostByAddrImpl(ipaddress).hostName; if (hostName.equals("localhost") && ipaddress.length == 4 && address != 0x7f000001) { return hostName = byteArrayToIpString(ipaddress); } } } catch (UnknownHostException e) { return hostName = byteArrayToIpString(ipaddress); } SecurityManager security = System.getSecurityManager(); try { // Only check host names, not addresses if (security != null && isHostName(hostName)) { security.checkConnect(hostName, -1); } } catch (SecurityException e) { return byteArrayToIpString(ipaddress); } return hostName; } /** * Gets the fully qualified domain name for the host associated with this IP * address. If a security manager is set, it is checked if the method caller * is allowed to get the hostname. Otherwise, the textual representation in * a dotted-quad-notation is returned. * * @return the fully qualified domain name of this IP address. */ public String getCanonicalHostName() { String canonicalName; try { int address = 0; if (ipaddress.length == 4) { address = bytesToInt(ipaddress, 0); if (address == 0) { return byteArrayToIpString(ipaddress); } } canonicalName = getHostByAddrImpl(ipaddress).hostName; } catch (UnknownHostException e) { return byteArrayToIpString(ipaddress); } SecurityManager security = System.getSecurityManager(); try { // Only check host names, not addresses if (security != null && isHostName(canonicalName)) { security.checkConnect(canonicalName, -1); } } catch (SecurityException e) { return byteArrayToIpString(ipaddress); } return canonicalName; } /** * Returns an {@code InetAddress} for the local host if possible, or the * loopback address otherwise. This method works by getting the hostname, * performing a DNS lookup, and then taking the first returned address. * For devices with multiple network interfaces and/or multiple addresses * per interface, this does not necessarily return the {@code InetAddress} * you want. * * <p>Multiple interface/address configurations were relatively rare * when this API was designed, but multiple interfaces are the default for * modern mobile devices (with separate wifi and radio interfaces), and * the need to support both IPv4 and IPv6 has made multiple addresses * commonplace. New code should thus avoid this method except where it's * basically being used to get a loopback address or equivalent. * * <p>There are two main ways to get a more specific answer: * <ul> * <li>If you have a connected socket, you should probably use * {@link Socket#getLocalAddress} instead: that will give you the address * that's actually in use for that connection. (It's not possible to ask * the question "what local address would a connection to a given remote * address use?"; you have to actually make the connection and see.)</li> * <li>For other use cases, see {@link NetworkInterface}, which lets you * enumerate all available network interfaces and their addresses.</li> * </ul> * * <p>Note that if the host doesn't have a hostname set&nbsp;&ndash; as * Android devices typically don't&nbsp;&ndash; this method will * effectively return the loopback address, albeit by getting the name * {@code localhost} and then doing a lookup to translate that to * {@code 127.0.0.1}. * * @return an {@code InetAddress} representing the local host, or the * loopback address. * @throws UnknownHostException * if the address lookup fails. */ public static InetAddress getLocalHost() throws UnknownHostException { String host = gethostname(); SecurityManager security = System.getSecurityManager(); try { if (security != null) { security.checkConnect(host, -1); } } catch (SecurityException e) { return Inet4Address.LOOPBACK; } return lookupHostByName(host)[0]; } private static native String gethostname(); /** * Gets the hashcode of the represented IP address. * * @return the appropriate hashcode value. */ @Override public int hashCode() { return Arrays.hashCode(ipaddress); } /* * Returns whether this address is an IP multicast address or not. This * implementation returns always {@code false}. * * @return {@code true} if this address is in the multicast group, {@code * false} otherwise. */ public boolean isMulticastAddress() { return false; } /** * Resolves a hostname to its IP addresses using a cache. * * @param host the hostname to resolve. * @return the IP addresses of the host. */ private static InetAddress[] lookupHostByName(String host) throws UnknownHostException { BlockGuard.getThreadPolicy().onNetwork(); // Do we have a result cached? InetAddress[] cachedResult = addressCache.get(host); if (cachedResult != null) { if (cachedResult.length > 0) { // A cached positive result. return cachedResult; } else { // A cached negative result. throw new UnknownHostException(host); } } try { InetAddress[] addresses = bytesToInetAddresses(getaddrinfo(host), host); addressCache.put(host, addresses); return addresses; } catch (UnknownHostException e) { addressCache.putUnknownHost(host); throw new UnknownHostException(host); } } private static native byte[][] getaddrinfo(String name) throws UnknownHostException; /** * Query the IP stack for the host address. The host is in address form. * * @param addr * the host address to lookup. * @throws UnknownHostException * if an error occurs during lookup. */ static InetAddress getHostByAddrImpl(byte[] addr) throws UnknownHostException { BlockGuard.getThreadPolicy().onNetwork(); if (addr.length == 4) { return new Inet4Address(addr, getnameinfo(addr)); } else if (addr.length == 16) { return new Inet6Address(addr, getnameinfo(addr)); } else { throw new UnknownHostException(wrongAddressLength()); } } /** * Resolves an IP address to a hostname. Thread safe. */ private static native String getnameinfo(byte[] addr); static String getHostNameInternal(String host, boolean isCheck) throws UnknownHostException { if (host == null || 0 == host.length()) { return Inet4Address.LOOPBACK.getHostAddress(); } if (isHostName(host)) { if (isCheck) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkConnect(host, -1); } } return lookupHostByName(host)[0].getHostAddress(); } return host; } /** * Returns a string containing a concise, human-readable description of this * IP address. * * @return the description, as host/address. */ @Override public String toString() { return (hostName == null ? "" : hostName) + "/" + getHostAddress(); } /** * Returns true if the string is a host name, false if it is an IP Address. */ static boolean isHostName(String value) { try { ipStringToByteArray(value); return false; } catch (UnknownHostException e) { return true; } } /** * Returns whether this address is a loopback address or not. This * implementation returns always {@code false}. Valid IPv4 loopback * addresses are 127.d.d.d The only valid IPv6 loopback address is ::1. * * @return {@code true} if this instance represents a loopback address, * {@code false} otherwise. */ public boolean isLoopbackAddress() { return false; } /** * Returns whether this address is a link-local address or not. This * implementation returns always {@code false}. * <p> * Valid IPv6 link-local addresses are FE80::0 through to * FEBF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF. * <p> * There are no valid IPv4 link-local addresses. * * @return {@code true} if this instance represents a link-local address, * {@code false} otherwise. */ public boolean isLinkLocalAddress() { return false; } /** * Returns whether this address is a site-local address or not. This * implementation returns always {@code false}. * <p> * Valid IPv6 site-local addresses are FEC0::0 through to * FEFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF. * <p> * There are no valid IPv4 site-local addresses. * * @return {@code true} if this instance represents a site-local address, * {@code false} otherwise. */ public boolean isSiteLocalAddress() { return false; } /** * Returns whether this address is a global multicast address or not. This * implementation returns always {@code false}. * <p> * Valid IPv6 link-global multicast addresses are FFxE:/112 where x is a set * of flags, and the additional 112 bits make up the global multicast * address space. * <p> * Valid IPv4 global multicast addresses are between: 224.0.1.0 to * 238.255.255.255. * * @return {@code true} if this instance represents a global multicast * address, {@code false} otherwise. */ public boolean isMCGlobal() { return false; } /** * Returns whether this address is a node-local multicast address or not. * This implementation returns always {@code false}. * <p> * Valid IPv6 node-local multicast addresses are FFx1:/112 where x is a set * of flags, and the additional 112 bits make up the node-local multicast * address space. * <p> * There are no valid IPv4 node-local multicast addresses. * * @return {@code true} if this instance represents a node-local multicast * address, {@code false} otherwise. */ public boolean isMCNodeLocal() { return false; } /** * Returns whether this address is a link-local multicast address or not. * This implementation returns always {@code false}. * <p> * Valid IPv6 link-local multicast addresses are FFx2:/112 where x is a set * of flags, and the additional 112 bits make up the link-local multicast * address space. * <p> * Valid IPv4 link-local addresses are between: 224.0.0.0 to 224.0.0.255 * * @return {@code true} if this instance represents a link-local multicast * address, {@code false} otherwise. */ public boolean isMCLinkLocal() { return false; } /** * Returns whether this address is a site-local multicast address or not. * This implementation returns always {@code false}. * <p> * Valid IPv6 site-local multicast addresses are FFx5:/112 where x is a set * of flags, and the additional 112 bits make up the site-local multicast * address space. * <p> * Valid IPv4 site-local addresses are between: 239.252.0.0 to * 239.255.255.255 * * @return {@code true} if this instance represents a site-local multicast * address, {@code false} otherwise. */ public boolean isMCSiteLocal() { return false; } /** * Returns whether this address is a organization-local multicast address or * not. This implementation returns always {@code false}. * <p> * Valid IPv6 organization-local multicast addresses are FFx8:/112 where x * is a set of flags, and the additional 112 bits make up the * organization-local multicast address space. * <p> * Valid IPv4 organization-local addresses are between: 239.192.0.0 to * 239.251.255.255 * * @return {@code true} if this instance represents a organization-local * multicast address, {@code false} otherwise. */ public boolean isMCOrgLocal() { return false; } /** * Returns whether this is a wildcard address or not. This implementation * returns always {@code false}. * * @return {@code true} if this instance represents a wildcard address, * {@code false} otherwise. */ public boolean isAnyLocalAddress() { return false; } /** * Tries to reach this {@code InetAddress}. This method first tries to use * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection * on port 7 (Echo) of the remote host is established. * * @param timeout * timeout in milliseconds before the test fails if no connection * could be established. * @return {@code true} if this address is reachable, {@code false} * otherwise. * @throws IOException * if an error occurs during an I/O operation. * @throws IllegalArgumentException * if timeout is less than zero. */ public boolean isReachable(int timeout) throws IOException { return isReachable(null, 0, timeout); } /** * Tries to reach this {@code InetAddress}. This method first tries to use * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection * on port 7 (Echo) of the remote host is established. * * @param networkInterface * the network interface on which to connection should be * established. * @param ttl * the maximum count of hops (time-to-live). * @param timeout * timeout in milliseconds before the test fails if no connection * could be established. * @return {@code true} if this address is reachable, {@code false} * otherwise. * @throws IOException * if an error occurs during an I/O operation. * @throws IllegalArgumentException * if ttl or timeout is less than zero. */ public boolean isReachable(NetworkInterface networkInterface, final int ttl, final int timeout) throws IOException { if (ttl < 0 || timeout < 0) { throw new IllegalArgumentException("ttl < 0 || timeout < 0"); } if (networkInterface == null) { return isReachableByTCP(this, null, timeout); } else { return isReachableByMultiThread(networkInterface, ttl, timeout); } } /* * Uses multi-Thread to try if isReachable, returns true if any of threads * returns in time */ private boolean isReachableByMultiThread(NetworkInterface netif, final int ttl, final int timeout) throws IOException { List<InetAddress> addresses = Collections.list(netif.getInetAddresses()); if (addresses.isEmpty()) { return false; } reached = false; addrCount = addresses.size(); boolean needWait = false; for (final InetAddress addr : addresses) { // loopback interface can only reach to local addresses if (addr.isLoopbackAddress()) { Enumeration<NetworkInterface> NetworkInterfaces = NetworkInterface .getNetworkInterfaces(); while (NetworkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = NetworkInterfaces .nextElement(); Enumeration<InetAddress> localAddresses = networkInterface .getInetAddresses(); while (localAddresses.hasMoreElements()) { if (InetAddress.this.equals(localAddresses .nextElement())) { return true; } } } synchronized (waitReachable) { addrCount--; if (addrCount == 0) { // if count equals zero, all thread // expired,notifies main thread waitReachable.notifyAll(); } } continue; } needWait = true; new Thread() { @Override public void run() { /* * Spec violation! This implementation doesn't attempt an * ICMP; it skips right to TCP echo. */ boolean threadReached = false; try { threadReached = isReachableByTCP(addr, InetAddress.this, timeout); } catch (IOException e) { } synchronized (waitReachable) { if (threadReached) { // if thread reached this address, sets reached to // true and notifies main thread reached = true; waitReachable.notifyAll(); } else { addrCount--; if (0 == addrCount) { // if count equals zero, all thread // expired,notifies main thread waitReachable.notifyAll(); } } } } }.start(); } if (needWait) { synchronized (waitReachable) { try { while (!reached && (addrCount != 0)) { // wait for notification waitReachable.wait(1000); } } catch (InterruptedException e) { // do nothing } return reached; } } return false; } private boolean isReachableByTCP(InetAddress destination, InetAddress source, int timeout) throws IOException { FileDescriptor fd = new FileDescriptor(); boolean reached = false; NETIMPL.socket(fd, true); try { if (null != source) { NETIMPL.bind(fd, source, 0); } NETIMPL.connect(fd, destination, 7, timeout); reached = true; } catch (IOException e) { if (ERRMSG_CONNECTION_REFUSED.equals(e.getMessage())) { // Connection refused means the IP is reachable reached = true; } } NETIMPL.close(fd); return reached; } /** * Returns the {@code InetAddress} corresponding to the array of bytes. In * the case of an IPv4 address there must be exactly 4 bytes and for IPv6 * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown. * <p> * The IP address is not validated by a name service. * <p> * The high order byte is {@code ipAddress[0]}. * * @param ipAddress * is either a 4 (IPv4) or 16 (IPv6) byte long array. * @return an {@code InetAddress} instance representing the given IP address * {@code ipAddress}. * @throws UnknownHostException * if the given byte array has no valid length. */ public static InetAddress getByAddress(byte[] ipAddress) throws UnknownHostException { // simply call the method by the same name specifying the default scope // id of 0 return getByAddressInternal(null, ipAddress, 0); } /** * Returns the {@code InetAddress} corresponding to the array of bytes. In * the case of an IPv4 address there must be exactly 4 bytes and for IPv6 * exactly 16 bytes. If not, an {@code UnknownHostException} is thrown. The * IP address is not validated by a name service. The high order byte is * {@code ipAddress[0]}. * * @param ipAddress * either a 4 (IPv4) or 16 (IPv6) byte array. * @param scope_id * the scope id for an IPV6 scoped address. If not a scoped * address just pass in 0. * @return the InetAddress * @throws UnknownHostException */ static InetAddress getByAddress(byte[] ipAddress, int scope_id) throws UnknownHostException { return getByAddressInternal(null, ipAddress, scope_id); } private static boolean isIPv4MappedAddress(byte ipAddress[]) { // Check if the address matches ::FFFF:d.d.d.d // The first 10 bytes are 0. The next to are -1 (FF). // The last 4 bytes are varied. if (ipAddress == null || ipAddress.length != 16) { return false; } for (int i = 0; i < 10; i++) { if (ipAddress[i] != 0) { return false; } } if (ipAddress[10] != -1 || ipAddress[11] != -1) { return false; } return true; } private static byte[] ipv4MappedToIPv4(byte[] mappedAddress) { byte[] ipv4Address = new byte[4]; for(int i = 0; i < 4; i++) { ipv4Address[i] = mappedAddress[12 + i]; } return ipv4Address; } /** * Returns the {@code InetAddress} corresponding to the array of bytes, and * the given hostname. In the case of an IPv4 address there must be exactly * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code * UnknownHostException} will be thrown. * <p> * The host name and IP address are not validated. * <p> * The hostname either be a machine alias or a valid IPv6 or IPv4 address * format. * <p> * The high order byte is {@code ipAddress[0]}. * * @param hostName * the string representation of hostname or IP address. * @param ipAddress * either a 4 (IPv4) or 16 (IPv6) byte long array. * @return an {@code InetAddress} instance representing the given IP address * and hostname. * @throws UnknownHostException * if the given byte array has no valid length. */ public static InetAddress getByAddress(String hostName, byte[] ipAddress) throws UnknownHostException { // just call the method by the same name passing in a default scope id // of 0 return getByAddressInternal(hostName, ipAddress, 0); } /** * Returns the {@code InetAddress} corresponding to the array of bytes, and * the given hostname. In the case of an IPv4 address there must be exactly * 4 bytes and for IPv6 exactly 16 bytes. If not, an {@code * UnknownHostException} is thrown. The host name and IP address are not * validated. The hostname either be a machine alias or a valid IPv6 or IPv4 * address format. The high order byte is {@code ipAddress[0]}. * * @param hostName * string representation of hostname or IP address. * @param ipAddress * either a 4 (IPv4) or 16 (IPv6) byte array. * @param scope_id * the scope id for a scoped address. If not a scoped address * just pass in 0. * @return the InetAddress * @throws UnknownHostException */ static InetAddress getByAddressInternal(String hostName, byte[] ipAddress, int scope_id) throws UnknownHostException { if (ipAddress == null) { throw new UnknownHostException("ipAddress == null"); } switch (ipAddress.length) { case 4: return new Inet4Address(ipAddress.clone()); case 16: // First check to see if the address is an IPv6-mapped // IPv4 address. If it is, then we can make it a IPv4 // address, otherwise, we'll create an IPv6 address. if (isIPv4MappedAddress(ipAddress)) { return new Inet4Address(ipv4MappedToIPv4(ipAddress)); } else { return new Inet6Address(ipAddress.clone(), scope_id); } default: throw new UnknownHostException( "Invalid IP Address is neither 4 or 16 bytes: " + hostName); } } /** * Takes the integer and chops it into 4 bytes, putting it into the byte * array starting with the high order byte at the index start. This method * makes no checks on the validity of the parameters. */ static void intToBytes(int value, byte bytes[], int start) { // Shift the int so the current byte is right-most // Use a byte mask of 255 to single out the last byte. bytes[start] = (byte) ((value >> 24) & 255); bytes[start + 1] = (byte) ((value >> 16) & 255); bytes[start + 2] = (byte) ((value >> 8) & 255); bytes[start + 3] = (byte) (value & 255); } /** * Takes the byte array and creates an integer out of four bytes starting at * start as the high-order byte. This method makes no checks on the validity * of the parameters. */ static int bytesToInt(byte bytes[], int start) { // First mask the byte with 255, as when a negative // signed byte converts to an integer, it has bits // on in the first 3 bytes, we are only concerned // about the right-most 8 bits. // Then shift the rightmost byte to align with its // position in the integer. int value = ((bytes[start + 3] & 255)) | ((bytes[start + 2] & 255) << 8) | ((bytes[start + 1] & 255) << 16) | ((bytes[start] & 255) << 24); return value; } private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("address", Integer.TYPE), new ObjectStreamField("family", Integer.TYPE), new ObjectStreamField("hostName", String.class) }; private void writeObject(ObjectOutputStream stream) throws IOException { ObjectOutputStream.PutField fields = stream.putFields(); if (ipaddress == null) { fields.put("address", 0); } else { fields.put("address", bytesToInt(ipaddress, 0)); } fields.put("family", family); fields.put("hostName", hostName); stream.writeFields(); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = stream.readFields(); int addr = fields.get("address", 0); ipaddress = new byte[4]; intToBytes(addr, ipaddress, 0); hostName = (String) fields.get("hostName", null); family = fields.get("family", 2); } /* * The spec requires that if we encounter a generic InetAddress in * serialized form then we should interpret it as an Inet4 address. */ private Object readResolve() throws ObjectStreamException { return new Inet4Address(ipaddress, hostName); } }
true
false
null
null
diff --git a/wheelmap/wheelmap/src/main/java/org/wheelmap/android/fragment/LoginDialogFragment.java b/wheelmap/wheelmap/src/main/java/org/wheelmap/android/fragment/LoginDialogFragment.java index 01329469..1554e035 100644 --- a/wheelmap/wheelmap/src/main/java/org/wheelmap/android/fragment/LoginDialogFragment.java +++ b/wheelmap/wheelmap/src/main/java/org/wheelmap/android/fragment/LoginDialogFragment.java @@ -1,238 +1,230 @@ /* * #%L * Wheelmap - App * %% * Copyright (C) 2011 - 2012 Michal Harakal - Michael Kroez - Sozialhelden e.V. * %% * Wheelmap App based on the Wheelmap Service by Sozialhelden e.V. * * 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. * #L% */ package org.wheelmap.android.fragment; +import de.neofonie.mobile.app.android.widget.crouton.Crouton; +import de.neofonie.mobile.app.android.widget.crouton.Style; import org.wheelmap.android.model.Extra; import org.wheelmap.android.online.R; import org.wheelmap.android.service.SyncService; import org.wheelmap.android.service.SyncServiceException; import org.wheelmap.android.service.SyncServiceHelper; import org.wheelmap.android.utils.DetachableResultReceiver; import org.wheelmap.android.utils.UtilsMisc; import android.app.Activity; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.FragmentManager; import android.text.Html; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.WazaBe.HoloEverywhere.app.AlertDialog; import com.WazaBe.HoloEverywhere.app.Dialog; import com.actionbarsherlock.app.SherlockDialogFragment; import de.akquinet.android.androlog.Log; public class LoginDialogFragment extends SherlockDialogFragment implements OnClickListener, DetachableResultReceiver.Receiver, OnEditorActionListener { public final static String TAG = LoginDialogFragment.class.getSimpleName(); private EditText mEmailText; private EditText mPasswordText; private TextView mRegisterText; private ProgressBar mProgressBar; private boolean mSyncing; private DetachableResultReceiver mReceiver; private OnLoginDialogListener mListener; public interface OnLoginDialogListener { public void onLoginSuccessful(); public void onLoginCancelled(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mReceiver = new DetachableResultReceiver(new Handler()); mReceiver.setReceiver(this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof OnLoginDialogListener) { mListener = (OnLoginDialogListener) activity; } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.title_login); builder.setIcon(R.drawable.ic_login_wheelmap); builder.setNeutralButton(R.string.login_submit, null); builder.setOnCancelListener(this); View view = getActivity().getLayoutInflater().inflate( R.layout.fragment_dialog_login, null); builder.setView(view); Dialog d = builder.create(); return d; } @Override public void onResume() { super.onResume(); AlertDialog dialog = (AlertDialog) getDialog(); Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL); button.setOnClickListener(this); mEmailText = (EditText) dialog.findViewById(R.id.login_email); mEmailText.setOnEditorActionListener(this); mPasswordText = (EditText) dialog.findViewById(R.id.login_password); mPasswordText.setOnEditorActionListener(this); String formattedHtml = UtilsMisc.formatHtmlLink( getString(R.string.login_link_wheelmap), getString(R.string.login_link_text)); Spanned spannedText = Html.fromHtml(formattedHtml); mRegisterText = (TextView) dialog.findViewById(R.id.login_register); mRegisterText.setText(spannedText); mRegisterText.setMovementMethod(LinkMovementMethod.getInstance()); load(); mProgressBar = (ProgressBar) dialog.findViewById(R.id.progressbar); } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); if (mListener != null) mListener.onLoginCancelled(); } private void load() { mEmailText.setText(""); mPasswordText.setText(""); } @Override public void onReceiveResult(int resultCode, Bundle resultData) { Log.d(TAG, "onReceiveResult in list resultCode = " + resultCode); switch (resultCode) { case SyncService.STATUS_RUNNING: mSyncing = true; updateRefreshStatus(); break; case SyncService.STATUS_FINISHED: mSyncing = false; updateRefreshStatus(); loginSuccessful(); break; case SyncService.STATUS_ERROR: - // Error happened down in SyncService, show as toast. + // Error happened down in SyncService, show as crouton. mSyncing = false; updateRefreshStatus(); final SyncServiceException e = resultData .getParcelable(Extra.EXCEPTION); - showErrorDialog(e); + Crouton.makeText(getActivity(), e.getRessourceString(), Style.ALERT).show(); break; default: // noop } } private void updateRefreshStatus() { if (mSyncing) mProgressBar.setVisibility(View.VISIBLE); else mProgressBar.setVisibility(View.INVISIBLE); } - private void showErrorDialog(SyncServiceException e) { - FragmentManager fm = getFragmentManager(); - ErrorDialogFragment errorDialog = ErrorDialogFragment.newInstance(e, - Extra.UNKNOWN); - if (errorDialog == null) - return; - - errorDialog.show(fm, ErrorDialogFragment.TAG); - } - private void loginSuccessful() { dismiss(); if (mListener != null) mListener.onLoginSuccessful(); } @Override public void onClick(View v) { login(); } private void login() { String email = mEmailText.getText().toString(); String password = mPasswordText.getText().toString(); if (email.length() == 0 || password.length() == 0) return; SyncServiceHelper.executeRetrieveApiKey(getActivity(), email, password, mReceiver); } private boolean checkInputFields(TextView v) { if (v.getText().toString().length() == 0) return false; EditText otherText; if (v == mEmailText) otherText = mPasswordText; else otherText = mEmailText; if (otherText.getText().toString().length() == 0) { otherText.requestFocus(); return false; } return true; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (EditorInfo.IME_ACTION_DONE == actionId) { if (checkInputFields(v)) login(); return true; } return false; } }
false
false
null
null
diff --git a/MyLogger/src/com/example/mylogger/MainActivity.java b/MyLogger/src/com/example/mylogger/MainActivity.java index 3336baa..049d474 100644 --- a/MyLogger/src/com/example/mylogger/MainActivity.java +++ b/MyLogger/src/com/example/mylogger/MainActivity.java @@ -1,22 +1,30 @@ package com.example.mylogger; import android.os.Bundle; import android.app.Activity; +import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { + private static final String TAG = "LoggerActivity"; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - } + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + Log.d(TAG, "THIS IS MY LOGGING LINE --- IT’S GREAT FOR DEBUGGING"); + } - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - getMenuInflater().inflate(R.menu.main, menu); - return true; - } + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.main, menu); + return true; + } + @Override + protected void onPause() { + super.onPause(); + Log.d(TAG, "I got onPause!!!"); + } }
false
false
null
null
diff --git a/src/main/java/org/illithid/cccp/ActorList.java b/src/main/java/org/illithid/cccp/ActorList.java index 0617418..dd70629 100755 --- a/src/main/java/org/illithid/cccp/ActorList.java +++ b/src/main/java/org/illithid/cccp/ActorList.java @@ -1,29 +1,29 @@ package org.illithid.cccp; import java.util.ArrayList; import org.illithid.cccp.bestiary.Actor; public class ActorList { ArrayList<Actor> actors = new ArrayList<Actor>(); private static final long serialVersionUID = -574013274149584937L; public Actor[] getAll() { Actor[] a = new Actor[actors.size()]; - for(int i = 0; i<actors.size()-1;i++) + for(int i = 0; i<actors.size();i++) a[i] = actors.get(i); return a; } public void add(Actor a) { actors.add(a); } public void act() { for(Actor a : actors) a.act(); } } diff --git a/src/main/java/org/illithid/cccp/world/BaseLevel.java b/src/main/java/org/illithid/cccp/world/BaseLevel.java index 7907f47..638aa01 100755 --- a/src/main/java/org/illithid/cccp/world/BaseLevel.java +++ b/src/main/java/org/illithid/cccp/world/BaseLevel.java @@ -1,141 +1,140 @@ package org.illithid.cccp.world; import org.illithid.cccp.ActorList; import org.illithid.cccp.bestiary.Actor; public abstract class BaseLevel implements Level { public static ActorList actors = new ActorList(); final int X = 80; final int Y = 25; Cell[][] cells = new Cell[X][Y]; public BaseLevel() { for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[i].length; j++) { cells[i][j] = new Cell(); } } } public Actor[] getActors(){ return actors.getAll(); } public void act(){ for(Actor a : actors.getAll()){ if(a!=null) a.act(); } } public int getXof(Actor a){ for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[i].length; j++) { if(cells[i][j].isOccupiedBy(a)) return i; - } - + } } return -1; } public void move(int distance, Direction d, Actor a){ int ax = getXof(a); int ay = getYof(a); int tx = -1; try { tx = calcX(distance, d, ax); } catch (UnsupportedDirectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } int ty = -1; try { ty = calcY(distance, d, ay); } catch (UnsupportedDirectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(cells[tx][ty].isWalkable()){ doMove(cells[ax][ay], cells[tx][ty]); } } private void doMove(Cell from, Cell to) { to.place(from.getOccupant()); from.removeOccupant(); } private int calcX(int dist, Direction d, int ax) throws UnsupportedDirectionException { switch (d) { case NORTH: case SOUTH: return ax; case NORTHEAST: case EAST: case SOUTHEAST: return ax+dist; case NORTHWEST: case WEST: case SOUTHWEST: return ax-dist; default: throw new UnsupportedDirectionException(); } } private int calcY(int dist, Direction d, int ay) throws UnsupportedDirectionException { switch (d) { case WEST: case EAST: return ay; case NORTHEAST: case NORTH: case NORTHWEST: return ay-dist; case SOUTHEAST: case SOUTH: case SOUTHWEST: return ay+dist; default: throw new UnsupportedDirectionException(); } } public int getYof(Actor a){ for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[i].length; j++) { if(cells[i][j].isOccupiedBy(a)) return j; } } return -1; } public void add(Actor a){ actors.add(a); place(a); } public int getX(){ return X; } public int getY(){ return Y; } public void add(Actor[] all) { for (Actor a : all) add(a); } }
false
false
null
null
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java index 437eaa431..ca25c305f 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java @@ -1,708 +1,708 @@ /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache POI" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache POI", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.poi.hssf.usermodel; import junit.framework.TestCase; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.EOFRecord; import org.apache.poi.hssf.util.ReferenceUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.List; import java.util.Iterator; import java.util.Date; import java.util.GregorianCalendar; /** * @author Andrew C. Oliver (acoliver at apache dot org) * @author Avik Sengupta */ public class TestFormulas extends TestCase { public TestFormulas(String s) { super(s); } /** * Add 1+1 -- WHoohoo! */ public void testBasicAddIntegers() throws Exception { short rownum = 0; File file = File.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; //get our minimum values r = s.createRow((short)1); c = r.createCell((short)1); c.setCellFormula(1 + "+" + 1); wb.write(out); out.close(); FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow((short)1); c = r.getCell((short)1); assertTrue("Formula is as expected",("1+1".equals(c.getCellFormula()))); in.close(); } /** * Add various integers */ public void testAddIntegers() throws Exception { binomialOperator("+"); } /** * Multiply various integers */ public void testMultplyIntegers() throws Exception { binomialOperator("*"); } /** * Subtract various integers */ public void testSubtractIntegers() throws Exception { binomialOperator("-"); } /** * Subtract various integers */ public void testDivideIntegers() throws Exception { binomialOperator("/"); } /** * Exponentialize various integers; */ public void testPowerIntegers() throws Exception { binomialOperator("^"); } /** * Concatinate two numbers 1&2 = 12 */ public void testConcatIntegers() throws Exception { binomialOperator("&"); } /** * tests 1*2+3*4 */ public void testOrderOfOperationsMultiply() throws Exception { orderTest("1*2+3*4"); } /** * tests 1*2+3^4 */ public void testOrderOfOperationsPower() throws Exception { orderTest("1*2+3^4"); } /** * Tests that parenthesis are obeyed */ public void testParenthesis() throws Exception { orderTest("(1*3)+2+(1+2)*(3^4)^5"); } public void testReferencesOpr() throws Exception { String[] operation = new String[] { "+", "-", "*", "/", "^", "&" }; for (int k = 0; k < operation.length; k++) { operationRefTest(operation[k]); } } /** * Tests creating a file with floating point in a formula. * */ public void testFloat() throws Exception { floatTest("*"); floatTest("/"); } private void floatTest(String operator) throws Exception { short rownum = 0; File file = File.createTempFile("testFormulaFloat",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; //get our minimum values r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula(""+Float.MIN_VALUE + operator + Float.MIN_VALUE); for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2) ) { r = s.createRow((short) x); for (short y = 1; y < 256 && y > 0; y= (short) (y +2)) { c = r.createCell((short) y); c.setCellFormula("" + x+"."+y + operator + y +"."+x); } } if (s.getLastRowNum() < Short.MAX_VALUE) { r = s.createRow((short)0); c = r.createCell((short)0); c.setCellFormula("" + Float.MAX_VALUE + operator + Float.MAX_VALUE); } wb.write(out); out.close(); assertTrue("file exists",file.exists()); out=null;wb=null; //otherwise we get out of memory error! floatVerify(operator,file); } private void floatVerify(String operator, File file) throws Exception { short rownum = 0; FileInputStream in = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(in); HSSFSheet s = wb.getSheetAt(0); HSSFRow r = null; HSSFCell c = null; // dont know how to check correct result .. for the moment, we just verify that the file can be read. for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.getRow((short) x); for (short y = 1; y < 256 && y > 0; y=(short)(y+2)) { c = r.getCell((short) y); assertTrue("got a formula",c.getCellFormula()!=null); assertTrue("loop Formula is as expected "+x+"."+y+operator+y+"."+x+"!="+c.getCellFormula(),( (""+x+"."+y+operator+y+"."+x).equals(c.getCellFormula()) )); } } in.close(); assertTrue("file exists",file.exists()); } public void testAreaSum() throws Exception { areaFunctionTest("SUM"); } public void testAreaAverage() throws Exception { areaFunctionTest("AVERAGE"); } public void testRefArraySum() throws Exception { refArrayFunctionTest("SUM"); } public void testAreaArraySum() throws Exception { refAreaArrayFunctionTest("SUM"); } private void operationRefTest(String operator) throws Exception { File file = File.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; //get our minimum values r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula("A2" + operator + "A3"); for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.createRow((short) x); for (short y = 1; y < 256 && y > 0; y++) { String ref=null; String ref2=null; short refx1=0; short refy1=0; short refx2=0; short refy2=0; if (x +50 < Short.MAX_VALUE) { refx1=(short)(x+50); refx2=(short)(x+46); } else { refx1=(short)(x-4); refx2=(short)(x-3); } if (y+50 < 255) { refy1=(short)(y+50); refy2=(short)(y+49); } else { refy1=(short)(y-4); refy2=(short)(y-3); } ref = ReferenceUtil.getReferenceFromXY(refx1,refy1); ref2 = ReferenceUtil.getReferenceFromXY(refx2,refy2); c = r.createCell((short) y); c.setCellFormula("" + ref + operator + ref2); } } //make sure we do the maximum value of the Int operator if (s.getLastRowNum() < Short.MAX_VALUE) { r = s.createRow((short)0); c = r.createCell((short)0); c.setCellFormula("" + "B1" + operator + "IV255"); } wb.write(out); out.close(); assertTrue("file exists",file.exists()); operationalRefVerify(operator,file); } /** * Opens the sheet we wrote out by binomialOperator and makes sure the formulas * all match what we expect (x operator y) */ private void operationalRefVerify(String operator, File file) throws Exception { short rownum = 0; FileInputStream in = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(in); HSSFSheet s = wb.getSheetAt(0); HSSFRow r = null; HSSFCell c = null; //get our minimum values r = s.getRow((short)0); c = r.getCell((short)1); //get our minimum values assertTrue("minval Formula is as expected A2"+operator+"A3 != "+c.getCellFormula(), ( ("A2"+operator+"A3").equals(c.getCellFormula()) )); for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.getRow((short) x); for (short y = 1; y < 256 && y > 0; y++) { String ref=null; String ref2=null; short refx1=0; short refy1=0; short refx2=0; short refy2=0; if (x +50 < Short.MAX_VALUE) { refx1=(short)(x+50); refx2=(short)(x+46); } else { refx1=(short)(x-4); refx2=(short)(x-3); } if (y+50 < 255) { refy1=(short)(y+50); refy2=(short)(y+49); } else { refy1=(short)(y-4); refy2=(short)(y-3); } c = r.getCell((short) y); ref = ReferenceUtil.getReferenceFromXY(refx1,refy1); ref2 = ReferenceUtil.getReferenceFromXY(refx2,refy2); assertTrue("loop Formula is as expected "+ref+operator+ref2+"!="+c.getCellFormula(),( (""+ref+operator+ref2).equals(c.getCellFormula()) ) ); } } //test our maximum values r = s.getRow((short)0); c = r.getCell((short)0); assertTrue("maxval Formula is as expected",( ("B1"+operator+"IV255").equals(c.getCellFormula()) ) ); in.close(); assertTrue("file exists",file.exists()); } /** * tests order wrting out == order writing in for a given formula */ private void orderTest(String formula) throws Exception { File file = File.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; //get our minimum values r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula(formula); wb.write(out); out.close(); assertTrue("file exists",file.exists()); FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); //get our minimum values r = s.getRow((short)0); c = r.getCell((short)1); assertTrue("minval Formula is as expected", formula.equals(c.getCellFormula()) ); in.close(); } /** * All multi-binomial operator tests use this to create a worksheet with a * huge set of x operator y formulas. Next we call binomialVerify and verify * that they are all how we expect. */ private void binomialOperator(String operator) throws Exception { short rownum = 0; File file = File.createTempFile("testFormula",".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; //get our minimum values r = s.createRow((short)0); c = r.createCell((short)1); c.setCellFormula(1 + operator + 1); for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.createRow((short) x); for (short y = 1; y < 256 && y > 0; y++) { c = r.createCell((short) y); c.setCellFormula("" + x + operator + y); } } //make sure we do the maximum value of the Int operator if (s.getLastRowNum() < Short.MAX_VALUE) { r = s.createRow((short)0); c = r.createCell((short)0); c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE); } wb.write(out); out.close(); assertTrue("file exists",file.exists()); binomialVerify(operator,file); } /** * Opens the sheet we wrote out by binomialOperator and makes sure the formulas * all match what we expect (x operator y) */ private void binomialVerify(String operator, File file) throws Exception { short rownum = 0; FileInputStream in = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(in); HSSFSheet s = wb.getSheetAt(0); HSSFRow r = null; HSSFCell c = null; //get our minimum values r = s.getRow((short)0); c = r.getCell((short)1); assertTrue("minval Formula is as expected 1"+operator+"1 != "+c.getCellFormula(), ( ("1"+operator+"1").equals(c.getCellFormula()) )); for (short x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { r = s.getRow((short) x); for (short y = 1; y < 256 && y > 0; y++) { c = r.getCell((short) y); assertTrue("loop Formula is as expected "+x+operator+y+"!="+c.getCellFormula(),( (""+x+operator+y).equals(c.getCellFormula()) ) ); } } //test our maximum values r = s.getRow((short)0); c = r.getCell((short)0); assertTrue("maxval Formula is as expected",( (""+Short.MAX_VALUE+operator+Short.MAX_VALUE).equals(c.getCellFormula()) ) ); in.close(); assertTrue("file exists",file.exists()); } /** * Writes a function then tests to see if its correct * */ public void areaFunctionTest(String function) throws Exception { short rownum = 0; File file = File.createTempFile("testFormulaAreaFunction"+function,".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; r = s.createRow((short) 0); c = r.createCell((short) 0); c.setCellFormula(function+"(A2:A3)"); wb.write(out); out.close(); assertTrue("file exists",file.exists()); FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); assertTrue("function ="+function+"(A2:A3)", ( (function+"(A2:A3)").equals((function+"(A2:A3)")) ) ); in.close(); } /** * Writes a function then tests to see if its correct * */ public void refArrayFunctionTest(String function) throws Exception { short rownum = 0; File file = File.createTempFile("testFormulaArrayFunction"+function,".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; r = s.createRow((short) 0); c = r.createCell((short) 0); c.setCellFormula(function+"(A2,A3)"); wb.write(out); out.close(); assertTrue("file exists",file.exists()); FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); assertTrue("function ="+function+"(A2,A3)", - ( (function+"(A2,A3)").equals((function+"(A2,A3)")) ) + ( (function+"(A2,A3)").equals(c.getCellFormula()) ) ); in.close(); } /** * Writes a function then tests to see if its correct * */ public void refAreaArrayFunctionTest(String function) throws Exception { short rownum = 0; File file = File.createTempFile("testFormulaAreaArrayFunction"+function,".xls"); FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); HSSFRow r = null; HSSFCell c = null; r = s.createRow((short) 0); c = r.createCell((short) 0); c.setCellFormula(function+"(A2:A4,B2:B4)"); wb.write(out); out.close(); assertTrue("file exists",file.exists()); FileInputStream in = new FileInputStream(file); wb = new HSSFWorkbook(in); s = wb.getSheetAt(0); r = s.getRow(0); c = r.getCell((short)0); assertTrue("function ="+function+"(A2:A4,B2:B4)", - ( (function+"(A2:A4,B2:B4)").equals((function+"(A2:A4,B2:B4)")) ) + ( (function+"(A2:A4,B2:B4)").equals(c.getCellFormula()) ) ); in.close(); } public static void main(String [] args) { System.out .println("Testing org.apache.poi.hssf.usermodel.TestFormulas"); junit.textui.TestRunner.run(TestFormulas.class); } }
false
false
null
null
diff --git a/src/realms/welcome-admin/src/java/org/wyona/yanel/servlet/menu/impl/WelcomeRealmMenu.java b/src/realms/welcome-admin/src/java/org/wyona/yanel/servlet/menu/impl/WelcomeRealmMenu.java index 609450a29..634420337 100644 --- a/src/realms/welcome-admin/src/java/org/wyona/yanel/servlet/menu/impl/WelcomeRealmMenu.java +++ b/src/realms/welcome-admin/src/java/org/wyona/yanel/servlet/menu/impl/WelcomeRealmMenu.java @@ -1,40 +1,40 @@ package org.wyona.yanel.servlet.menu.impl; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; +import org.wyona.yanel.servlet.IdentityMap; import org.wyona.yanel.servlet.YanelServlet; import org.wyona.yanel.servlet.menu.Menu; import org.wyona.security.core.api.Identity; -import org.wyona.security.core.api.IdentityMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; /** * */ public class WelcomeRealmMenu extends Menu { /** * Get toolbar menus */ public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuffer sb= new StringBuffer(); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>"); sb.append("<ul>"); sb.append("<li class=\"haschild\">New Realm&#160;&#160;&#160;<ul><li><a href=\"" + backToRealm + "add-realm-from-scratch.html\">From Scratch</a></li><li><a href=\"" + backToRealm + "add-realm-from-existing-website.html\">From Existing Website</a></li></ul></li>"); sb.append("</ul>"); sb.append("</li></ul>"); return sb.toString(); } } diff --git a/src/realms/yanel-website/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java b/src/realms/yanel-website/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java index 8bcd5517d..9bed34f66 100644 --- a/src/realms/yanel-website/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java +++ b/src/realms/yanel-website/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java @@ -1,81 +1,81 @@ package org.wyona.yanel.servlet.menu.impl; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.TranslatableV1; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.core.util.ResourceAttributeHelper; +import org.wyona.yanel.servlet.IdentityMap; import org.wyona.yanel.servlet.YanelServlet; import org.wyona.yanel.servlet.menu.Menu; import org.wyona.security.core.api.Identity; -import org.wyona.security.core.api.IdentityMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * */ public class YanelWebsiteMenu extends Menu { /** * Get toolbar menus */ public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuffer sb= new StringBuffer(); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>"); sb.append("<ul>"); sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New&#160;&#160;&#160;</a><ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Afile\">File</a></li></ul></li>"); sb.append("<li class=\"haschild\">New language&#160;&#160;&#160;<ul>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Translatable", "1")) { TranslatableV1 translatable = (TranslatableV1)resource; List existingLanguages = Arrays.asList(translatable.getLanguages()); String[] realmLanguages = resource.getRealm().getLanguages(); for (int i = 0; i < realmLanguages.length; i++) { if (!existingLanguages.contains(realmLanguages[i])) { sb.append("<li>"); sb.append(realmLanguages[i]); sb.append("</li>"); } } } //sb.append("<li>German</li><li>Mandarin</li>"); sb.append("</ul></li>"); sb.append("<li>Publish</li>"); sb.append("</ul>"); sb.append("</li></ul>"); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">Edit</div><ul>"); sb.append("<li class=\"haschild\">Open with&#160;&#160;&#160;<ul><li>Source editor</li><li>WYSIWYG editor</li></ul></li>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { RevisionInformation[] revisions = ((VersionableV2) resource).getRevisions(); if (revisions != null && revisions.length > 0) { sb.append("<li class=\"haschild\">Revisions&#160;&#160;&#160;<ul>"); for (int i = 0; i < revisions.length; i++) { sb.append("<li class=\"haschild\">"+revisions[i].getName()+"&#160;&#160;&#160;<ul><li><a href=\"?yanel.resource.revision=" + revisions[i].getName() + "\">View</a></li><li>Show diff</li><li>Revert to</li></ul></li>"); } sb.append("</ul></li>"); } } sb.append("</ul>"); sb.append("</li></ul>"); return sb.toString(); } }
false
false
null
null
diff --git a/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java b/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java index 07c111a8..85d315f7 100644 --- a/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java +++ b/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java @@ -1,336 +1,342 @@ /* © 2010 Stephan Reichholf <stephan at reichholf dot net> * * Licensed under the Create-Commons Attribution-Noncommercial-Share Alike 3.0 Unported * http://creativecommons.org/licenses/by-nc-sa/3.0/ */ package net.reichholf.dreamdroid.activities; import net.reichholf.dreamdroid.DreamDroid; import net.reichholf.dreamdroid.R; import net.reichholf.dreamdroid.abstivities.MultiPaneHandler; import net.reichholf.dreamdroid.fragment.ActivityCallbackHandler; import net.reichholf.dreamdroid.fragment.NavigationFragment; import net.reichholf.dreamdroid.helpers.ExtendedHashMap; import net.reichholf.dreamdroid.helpers.enigma2.CheckProfile; import android.app.Dialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.Window; import android.widget.TextView; /** * @author sre * */ public class FragmentMainActivity extends FragmentActivity implements MultiPaneHandler { private boolean mMultiPane; private Fragment mCurrentDetailFragment; private FragmentManager mFragmentManager; private NavigationFragment mNavigationFragment; private ActivityCallbackHandler mCallBackHandler; private TextView mActiveProfile; private TextView mConnectionState; private CheckProfileTask mCheckProfileTask; private boolean isNavigationDialog = false; private class CheckProfileTask extends AsyncTask<Void, String, ExtendedHashMap> { /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected ExtendedHashMap doInBackground(Void... params) { publishProgress(getText(R.string.checking).toString()); return CheckProfile.checkProfile(DreamDroid.PROFILE); } /* * (non-Javadoc) * * @see android.os.AsyncTask#onProgressUpdate(Progress[]) */ @Override protected void onProgressUpdate(String... progress) { setConnectionState(progress[0]); } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(ExtendedHashMap result) { Log.i(DreamDroid.LOG_TAG, result.toString()); if ((Boolean) result.get(CheckProfile.KEY_HAS_ERROR)) { String error = getText((Integer) result.get(CheckProfile.KEY_ERROR_TEXT)).toString(); setConnectionState(error); } else { setConnectionState(getText(R.string.ok).toString()); } } } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); mFragmentManager = getSupportFragmentManager(); if(savedInstanceState != null){ mNavigationFragment = (NavigationFragment) mFragmentManager.getFragment(savedInstanceState, "navigation"); } if(mNavigationFragment == null){ mNavigationFragment = new NavigationFragment(); } if(savedInstanceState != null){ mCurrentDetailFragment = mFragmentManager.getFragment(savedInstanceState, "current"); } initViews(); mNavigationFragment.setHighlightCurrent(mMultiPane); } private void initViews(){ setContentView(R.layout.dualpane); if(findViewById(R.id.detail_view) != null){ mMultiPane = true; } else { mMultiPane = false; } //Force Multipane Layout if User selected the option for it if(!mMultiPane && DreamDroid.SP.getBoolean("force_multipane", false)){ setContentView(R.layout.forced_dualpane); mMultiPane = true; } FragmentTransaction ft = mFragmentManager.beginTransaction(); showFragment(ft, R.id.navigation_view, mNavigationFragment); if(mCurrentDetailFragment != null){ showFragment(ft, R.id.detail_view, mCurrentDetailFragment); mCallBackHandler = (ActivityCallbackHandler) mCurrentDetailFragment; } else { } ft.commit(); mActiveProfile = (TextView) findViewById(R.id.TextViewProfile); + if(mActiveProfile == null){ + mActiveProfile = new TextView(this); + } mConnectionState = (TextView) findViewById(R.id.TextViewConnectionState); + if(mConnectionState == null){ + mConnectionState = new TextView(this); + } checkActiveProfile(); } private void showFragment(FragmentTransaction ft, int viewId, Fragment fragment){ if( fragment.isAdded() ){ Log.i(DreamDroid.LOG_TAG, "Fragment already added, showing"); ft.show(fragment); } else { Log.i(DreamDroid.LOG_TAG, "Fragment not added, adding"); ft.replace(viewId, fragment, fragment.getClass().getSimpleName()); } } /* * (non-Javadoc) * * @see net.reichholf.dreamdroid.abstivities.AbstractHttpListActivity# * onSaveInstanceState(android.os.Bundle) */ @Override public void onSaveInstanceState(Bundle outState) { mFragmentManager.putFragment(outState, "navigation", mNavigationFragment); if(mCurrentDetailFragment != null){ mFragmentManager.putFragment(outState, "current", mCurrentDetailFragment); } super.onSaveInstanceState(outState); } @Override public void onResume(){ super.onResume(); } /** * */ public void checkActiveProfile() { setProfileName(); if (mCheckProfileTask != null) { mCheckProfileTask.cancel(true); } mCheckProfileTask = new CheckProfileTask(); mCheckProfileTask.execute(); } /** * */ public void setProfileName() { mActiveProfile.setText(DreamDroid.PROFILE.getName()); } /** * @param state */ private void setConnectionState(String state) { mConnectionState.setText(state); setProgressBarIndeterminateVisibility(false); // TODO setAvailableFeatures(); } /** * @param fragmentClass */ @SuppressWarnings("rawtypes") public void showDetails(Class fragmentClass){ if(mMultiPane){ try { Fragment fragment = (Fragment) fragmentClass.newInstance(); showDetails(fragment); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Intent intent = new Intent(this, SimpleFragmentActivity.class); intent.putExtra("fragmentClass", fragmentClass); startActivity(intent); } } @Override public void showDetails(Fragment fragment){ showDetails(fragment, false); } public void back(){ mFragmentManager.popBackStackImmediate(); } /** * @param fragment * @throws IllegalAccessException * @throws InstantiationException */ @Override public void showDetails(Fragment fragment, boolean addToBackStack){ mCallBackHandler = (ActivityCallbackHandler) fragment; if(mMultiPane){ FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if(mCurrentDetailFragment != null){ if(mCurrentDetailFragment.isVisible()){ //TODO fix this hack (remove current fragment just to readd it in showFragment, do we really have to do that?) ft.remove(mCurrentDetailFragment); } } mCurrentDetailFragment = fragment; showFragment(ft, R.id.detail_view, fragment); if(addToBackStack){ ft.addToBackStack(null); } ft.commit(); } else { //TODO Error Handling Intent intent = new Intent(this, SimpleFragmentActivity.class); intent.putExtra("fragmentClass", fragment.getClass()); intent.putExtras(fragment.getArguments()); startActivity(intent); } } @Override public void setTitle(CharSequence title){ if(mMultiPane){ TextView t = (TextView) findViewById(R.id.detail_title); t.bringToFront(); String replaceMe = getText(R.string.app_name) + "::"; t.setText(title.toString().replace(replaceMe, "")); return; } super.setTitle(title); } public void setIsNavgationDialog(boolean is){ isNavigationDialog = is; } @Override protected Dialog onCreateDialog(int id){ Dialog dialog = null; if(isNavigationDialog){ dialog = mNavigationFragment.onCreateDialog(id); isNavigationDialog = false; } else { dialog = mCallBackHandler.onCreateDialog(id); } if(dialog == null){ dialog = super.onCreateDialog(id); } return dialog; } @Override public boolean onKeyDown(int keyCode, KeyEvent event){ if(mCallBackHandler != null){ if(mCallBackHandler.onKeyDown(keyCode, event)){ return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event){ if(mCallBackHandler != null){ if(mCallBackHandler.onKeyUp(keyCode, event)){ return true; } } return super.onKeyUp(keyCode, event); } public void onProfileChanged(){ checkActiveProfile(); } public boolean isMultiPane(){ return mMultiPane; } public void finish(boolean finishFragment){ if(mMultiPane && finishFragment){ //TODO finish() for Fragment // mFragmentManager.popBackStackImmediate(); } else { super.finish(); } } }
false
true
private void initViews(){ setContentView(R.layout.dualpane); if(findViewById(R.id.detail_view) != null){ mMultiPane = true; } else { mMultiPane = false; } //Force Multipane Layout if User selected the option for it if(!mMultiPane && DreamDroid.SP.getBoolean("force_multipane", false)){ setContentView(R.layout.forced_dualpane); mMultiPane = true; } FragmentTransaction ft = mFragmentManager.beginTransaction(); showFragment(ft, R.id.navigation_view, mNavigationFragment); if(mCurrentDetailFragment != null){ showFragment(ft, R.id.detail_view, mCurrentDetailFragment); mCallBackHandler = (ActivityCallbackHandler) mCurrentDetailFragment; } else { } ft.commit(); mActiveProfile = (TextView) findViewById(R.id.TextViewProfile); mConnectionState = (TextView) findViewById(R.id.TextViewConnectionState); checkActiveProfile(); }
private void initViews(){ setContentView(R.layout.dualpane); if(findViewById(R.id.detail_view) != null){ mMultiPane = true; } else { mMultiPane = false; } //Force Multipane Layout if User selected the option for it if(!mMultiPane && DreamDroid.SP.getBoolean("force_multipane", false)){ setContentView(R.layout.forced_dualpane); mMultiPane = true; } FragmentTransaction ft = mFragmentManager.beginTransaction(); showFragment(ft, R.id.navigation_view, mNavigationFragment); if(mCurrentDetailFragment != null){ showFragment(ft, R.id.detail_view, mCurrentDetailFragment); mCallBackHandler = (ActivityCallbackHandler) mCurrentDetailFragment; } else { } ft.commit(); mActiveProfile = (TextView) findViewById(R.id.TextViewProfile); if(mActiveProfile == null){ mActiveProfile = new TextView(this); } mConnectionState = (TextView) findViewById(R.id.TextViewConnectionState); if(mConnectionState == null){ mConnectionState = new TextView(this); } checkActiveProfile(); }
diff --git a/lib/src/main/java/fi/smaa/jsmaa/model/electre/ElectreTri.java b/lib/src/main/java/fi/smaa/jsmaa/model/electre/ElectreTri.java index 28c4629..865eda4 100644 --- a/lib/src/main/java/fi/smaa/jsmaa/model/electre/ElectreTri.java +++ b/lib/src/main/java/fi/smaa/jsmaa/model/electre/ElectreTri.java @@ -1,140 +1,141 @@ /* This file is part of JSMAA. JSMAA is distributed from http://smaa.fi/. (c) Tommi Tervonen, 2009-2010. (c) Tommi Tervonen, Gert van Valkenhoef 2011. (c) Tommi Tervonen, Gert van Valkenhoef, Joel Kuiper, Daan Reid 2012. (c) Tommi Tervonen, Gert van Valkenhoef, Joel Kuiper, Daan Reid, Raymond Vermaas 2013. JSMAA 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. JSMAA 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 JSMAA. If not, see <http://www.gnu.org/licenses/>. */ package fi.smaa.jsmaa.model.electre; import java.util.HashMap; import java.util.List; import java.util.Map; import fi.smaa.jsmaa.model.Alternative; import fi.smaa.jsmaa.model.Category; import fi.smaa.jsmaa.model.OutrankingCriterion; public class ElectreTri { private List<Alternative> alts; private List<OutrankingCriterion> crit; private Map<Alternative, Map<OutrankingCriterion, Double>> measurements; private Map<Alternative, Map<OutrankingCriterion, Double>> categoryUpperBounds; private boolean optimistic; private double lambda; private double[] weights; private List<Category> categories; public ElectreTri(List<Alternative> alts, List<OutrankingCriterion> crit, List<Category> categories, Map<Alternative, Map<OutrankingCriterion, Double>> measurements, Map<Alternative, Map<OutrankingCriterion, Double>> categoryUpperBounds, double[] weights, double lambda, boolean optimistic) { assert(weights.length == crit.size()); this.measurements = measurements; this.categoryUpperBounds = categoryUpperBounds; this.lambda = lambda; this.optimistic = optimistic; this.weights = weights; this.categories = categories; this.alts = alts; this.crit = crit; } /** * map is : alternative -> category * @return */ public Map<Alternative, Alternative> compute() { Map<Alternative, Alternative> resMap = new HashMap<Alternative, Alternative>(); if (categories.size() == 1) { for (Alternative a : alts) { resMap.put(a, categories.get(0)); } return resMap; } for (Alternative a : alts) { if (optimistic) { // from the top upper bound for (int i=categories.size()-2;i>=0;i--) { Alternative cat = categories.get(i); if (!preferred(categoryUpperBounds.get(cat), measurements.get(a))) { resMap.put(a, categories.get(i+1)); break; } if (i ==0) { resMap.put(a, cat); } } } else { // from the lowest upper bound for (int i=0;i<categories.size()-1;i++) { Alternative cat = categories.get(i); if (!outranks(measurements.get(a), categoryUpperBounds.get(cat))) { resMap.put(a, categories.get(i)); break; } if (i == categories.size()-2) { + cat = categories.get((i+1)); resMap.put(a, cat); } } } } return resMap; } public boolean outranks(Map<OutrankingCriterion, Double> alt, Map<OutrankingCriterion, Double> toAlt) { assert(alt.entrySet().size() == toAlt.entrySet().size()); assert(alt.entrySet().size() == weights.length); double concordance = concordance(alt, toAlt); return concordance >= lambda; } public double concordance(Map<OutrankingCriterion, Double> alt, Map<OutrankingCriterion, Double> toAlt) { double concordance = 0.0; for (int i=0;i<crit.size();i++) { OutrankingCriterion c = crit.get(i); Double altVal = alt.get(c); Double toAltVal = toAlt.get(c); concordance += OutrankingFunction.concordance(c, altVal, toAltVal) * weights[i]; } return concordance; } public boolean preferred(Map<OutrankingCriterion, Double> alt, Map<OutrankingCriterion, Double> toAlt) { assert(alt.entrySet().size() == toAlt.entrySet().size()); assert(alt.entrySet().size() == weights.length); return (outranks(alt, toAlt) && !outranks(toAlt, alt)); } public void setRule(boolean optimistic) { this.optimistic = optimistic; } } diff --git a/lib/src/test/java/fi/smaa/jsmaa/simulator/SMAATRISimulationTest.java b/lib/src/test/java/fi/smaa/jsmaa/simulator/SMAATRISimulationTest.java index d882690..26c8420 100644 --- a/lib/src/test/java/fi/smaa/jsmaa/simulator/SMAATRISimulationTest.java +++ b/lib/src/test/java/fi/smaa/jsmaa/simulator/SMAATRISimulationTest.java @@ -1,204 +1,204 @@ /* This file is part of JSMAA. JSMAA is distributed from http://smaa.fi/. (c) Tommi Tervonen, 2009-2010. (c) Tommi Tervonen, Gert van Valkenhoef 2011. (c) Tommi Tervonen, Gert van Valkenhoef, Joel Kuiper, Daan Reid 2012. (c) Tommi Tervonen, Gert van Valkenhoef, Joel Kuiper, Daan Reid, Raymond Vermaas 2013. JSMAA 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. JSMAA 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 JSMAA. If not, see <http://www.gnu.org/licenses/>. */ package fi.smaa.jsmaa.simulator; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.drugis.common.JUnitUtil; import org.drugis.common.threading.ThreadHandler; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import fi.smaa.common.RandomUtil; import fi.smaa.jsmaa.model.Alternative; import fi.smaa.jsmaa.model.Category; import fi.smaa.jsmaa.model.Criterion; import fi.smaa.jsmaa.model.ExactMeasurement; import fi.smaa.jsmaa.model.IndependentMeasurements; import fi.smaa.jsmaa.model.Interval; import fi.smaa.jsmaa.model.OutrankingCriterion; import fi.smaa.jsmaa.model.SMAATRIModel; public class SMAATRISimulationTest { private SMAATRIModel model; private Alternative alt1 = new Alternative("alt1"); private Alternative alt2 = new Alternative("alt2"); private OutrankingCriterion c1 = new OutrankingCriterion("c1", true, new Interval(0.0, 0.0), new Interval(1.0, 1.0)); private OutrankingCriterion c2 = new OutrankingCriterion("c2", true, new Interval(0.0, 0.0), new Interval(1.0, 1.0)); private Category cat1 = new Category("cat1"); private Category cat2 = new Category("cat2"); private Set<Alternative> alts; private Set<Criterion> crit; private List<Category> cats; @Before public void setUp() { alts = new HashSet<Alternative>(); crit = new HashSet<Criterion>(); cats = new ArrayList<Category>(); alts.add(alt1); alts.add(alt2); crit.add(c1); crit.add(c2); cats.add(cat1); cats.add(cat2); model = new SMAATRIModel("model"); model.addAlternative(alt1); model.addAlternative(alt2); model.addCriterion(c1); model.addCriterion(c2); model.addCategory(cat1); model.addCategory(cat2); ((IndependentMeasurements) model.getMeasurements()).setMeasurement(c1, alt1, new ExactMeasurement(2.0)); ((IndependentMeasurements) model.getMeasurements()).setMeasurement(c2, alt1, new ExactMeasurement(2.0)); ((IndependentMeasurements) model.getMeasurements()).setMeasurement(c1, alt2, new ExactMeasurement(0.0)); ((IndependentMeasurements) model.getMeasurements()).setMeasurement(c2, alt2, new ExactMeasurement(0.0)); model.setCategoryUpperBound(c1, cat1, new ExactMeasurement(1.0)); model.setCategoryUpperBound(c2, cat1, new ExactMeasurement(1.0)); model.setRule(true); } @Test public void testOneCategory() throws InterruptedException { model.deleteCategory(cat1); SMAATRIResults res = runModel(model); Map<Alternative, List<Double>> accs = res.getCategoryAcceptabilities(); assertEquals(1.0, accs.get(alt1).get(0), 0.00001); assertEquals(1.0, accs.get(alt2).get(0), 0.00001); } private SMAATRIResults runModel(SMAATRIModel model) throws InterruptedException { SMAATRISimulation simulation = new SMAATRISimulation(model, RandomUtil.createWithFixedSeed(), 10000); ThreadHandler hand = ThreadHandler.getInstance(); hand.scheduleTask(simulation.getTask()); do { Thread.sleep(1); } while (!simulation.getTask().isFinished()); return (SMAATRIResults) simulation.getResults(); } @Test public void testCorrectResults() throws InterruptedException { SMAATRIResults res = runModel(model); Map<Alternative, List<Double>> accs = res.getCategoryAcceptabilities(); assertEquals(0.0, accs.get(alt1).get(0), 0.00001); assertEquals(1.0, accs.get(alt1).get(1), 0.00001); assertEquals(1.0, accs.get(alt2).get(0), 0.00001); assertEquals(0.0, accs.get(alt2).get(1), 0.00001); } @Test public void testCorrectResultsPessimistic() throws InterruptedException { model.setRule(false); SMAATRIResults res = runModel(model); Map<Alternative, List<Double>> accs = res.getCategoryAcceptabilities(); - assertEquals(1.0, accs.get(alt1).get(0), 0.00001); - assertEquals(0.0, accs.get(alt1).get(1), 0.00001); + assertEquals(0.0, accs.get(alt1).get(0), 0.00001); + assertEquals(1.0, accs.get(alt1).get(1), 0.00001); assertEquals(1.0, accs.get(alt2).get(0), 0.00001); assertEquals(0.0, accs.get(alt2).get(1), 0.00001); } // ignore because mock doesnt match the event @Test @Ignore public void testInvalidUpperBoundsFire() throws InterruptedException { Category cat3 = new Category("cat3"); model.addCategory(cat3); model.setCategoryUpperBound(c1, cat1, new ExactMeasurement(1.0)); model.setCategoryUpperBound(c1, cat2, new ExactMeasurement(0.0)); SMAAResultsListener mock = createMock(SMAAResultsListener.class); SMAATRISimulation simulation = new SMAATRISimulation(model, RandomUtil.createWithFixedSeed(), 10000); ThreadHandler hand = ThreadHandler.getInstance(); mock.resultsChanged((ResultsEvent) JUnitUtil.eqEventObject(new ResultsEvent(simulation.getResults(), new IterationException("")))); replay(mock); simulation.getResults().addResultsListener(mock); hand.scheduleTask(simulation.getTask()); do { Thread.sleep(1); } while (hand.getQueuedTasks() > 0); verify(mock); } // ignore because mock doesnt match the event @Test @Ignore public void testInvalidThresholdsFire() throws InterruptedException { c1.setIndifMeasurement(new ExactMeasurement(3.0)); c1.setPrefMeasurement(new ExactMeasurement(2.0)); SMAATRISimulation simulation = new SMAATRISimulation(model, RandomUtil.createWithFixedSeed(), 10000); ThreadHandler hand = ThreadHandler.getInstance(); hand.scheduleTask(simulation.getTask()); do { Thread.sleep(1); } while (hand.getQueuedTasks() > 0); SMAAResultsListener mock = createMock(SMAAResultsListener.class); mock.resultsChanged((ResultsEvent) JUnitUtil.eqEventObject(new ResultsEvent(simulation.getResults(), new IterationException("")))); replay(mock); simulation.getResults().addResultsListener(mock); hand.scheduleTask(simulation.getTask()); do { Thread.sleep(1); } while (hand.getQueuedTasks() > 0); verify(mock); } @Test public void testOneCriterionZeroBoundUpperBound() throws InterruptedException { model.setCategoryUpperBound(c1, cat1, new ExactMeasurement(0.0)); model.setCategoryUpperBound(c2, cat1, new ExactMeasurement(0.0)); SMAATRIResults results = runModel(model); Thread.sleep(10); assertEquals(new Double(0.0), results.getCategoryAcceptabilities().get(alt1).get(0)); } }
false
false
null
null
diff --git a/public/java/src/org/broadinstitute/sting/gatk/walkers/phasing/PhaseByTransmission.java b/public/java/src/org/broadinstitute/sting/gatk/walkers/phasing/PhaseByTransmission.java index d3ed46ce8..cf4afbb6d 100755 --- a/public/java/src/org/broadinstitute/sting/gatk/walkers/phasing/PhaseByTransmission.java +++ b/public/java/src/org/broadinstitute/sting/gatk/walkers/phasing/PhaseByTransmission.java @@ -1,341 +1,343 @@ package org.broadinstitute.sting.gatk.walkers.phasing; import org.broadinstitute.sting.commandline.Argument; import org.broadinstitute.sting.commandline.Output; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.SampleUtils; import org.broadinstitute.sting.utils.codecs.vcf.*; import org.broadinstitute.sting.utils.text.XReadLines; import org.broadinstitute.sting.utils.variantcontext.Allele; import org.broadinstitute.sting.utils.variantcontext.Genotype; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import org.broadinstitute.sting.utils.variantcontext.VariantContextUtils; import java.io.File; import java.io.FileNotFoundException; import java.util.*; /** * Phases a trio VCF (child phased by transmission, implied phase carried over to parents). Given genotypes for a trio, * this walker modifies the genotypes (if necessary) to reflect the most likely configuration given the genotype * likelihoods and inheritance constraints, phases child by transmission and carries over implied phase to the parents * (their alleles in their genotypes are ordered as transmitted|untransmitted). Computes probability that the * determined phase is correct given that the genotype configuration is correct (useful if you want to use this to * compare phasing accuracy, but want to break that comparison down by phasing confidence in the truth set). Optionally * filters out sites where the phasing is indeterminate (site has no-calls), ambiguous (everyone is heterozygous), or * the genotypes exhibit a Mendelian violation. This walker assumes there are only three samples in the VCF file to * begin. */ public class PhaseByTransmission extends RodWalker<Integer, Integer> { @Argument(shortName="f", fullName="familySpec", required=true, doc="Patterns for the family structure (usage: mom+dad=child). Specify several trios by supplying this argument many times and/or a file containing many patterns.") public ArrayList<String> familySpecs = null; @Output protected VCFWriter vcfWriter = null; private final String ROD_NAME = "variant"; private final String TRANSMISSION_PROBABILITY_TAG_NAME = "TP"; private final String SOURCE_NAME = "PhaseByTransmission"; private final Double MENDELIAN_VIOLATION_PRIOR = 1e-8; private class Trio { private String mother; private String father; private String child; public Trio(String mother, String father, String child) { this.mother = mother; this.father = father; this.child = child; } public Trio(String familySpec) { String[] pieces = familySpec.split("[\\+\\=]"); this.mother = pieces[0]; this.father = pieces[1]; this.child = pieces[2]; } public String getMother() { return mother; } public String getFather() { return father; } public String getChild() { return child; } } private ArrayList<Trio> trios = new ArrayList<Trio>(); public ArrayList<Trio> getFamilySpecsFromCommandLineInput(ArrayList<String> familySpecs) { if (familySpecs != null) { // Let's first go through the list and see if we were given any files. We'll add every entry in the file to our // spec list set, and treat the entries as if they had been specified on the command line. ArrayList<Trio> specs = new ArrayList<Trio>(); for (String familySpec : familySpecs) { File specFile = new File(familySpec); try { XReadLines reader = new XReadLines(specFile); List<String> lines = reader.readLines(); for (String line : lines) { specs.add(new Trio(line)); } } catch (FileNotFoundException e) { specs.add(new Trio(familySpec)); // not a file, so must be a family spec } } return specs; } return new ArrayList<Trio>(); } /** * Parse the familial relationship specification, and initialize VCF writer */ public void initialize() { trios = getFamilySpecsFromCommandLineInput(familySpecs); ArrayList<String> rodNames = new ArrayList<String>(); rodNames.add(ROD_NAME); Map<String, VCFHeader> vcfRods = VCFUtils.getVCFHeadersFromRods(getToolkit(), rodNames); Set<String> vcfSamples = SampleUtils.getSampleList(vcfRods, VariantContextUtils.GenotypeMergeType.REQUIRE_UNIQUE); Set<VCFHeaderLine> headerLines = new HashSet<VCFHeaderLine>(); headerLines.addAll(VCFUtils.getHeaderFields(this.getToolkit())); headerLines.add(new VCFFormatHeaderLine(TRANSMISSION_PROBABILITY_TAG_NAME, 1, VCFHeaderLineType.Float, "Probability that the phase is correct given that the genotypes are correct")); headerLines.add(new VCFHeaderLine("source", SOURCE_NAME)); vcfWriter.writeHeader(new VCFHeader(headerLines, vcfSamples)); } private double computeTransmissionLikelihoodOfGenotypeConfiguration(Genotype mom, Genotype dad, Genotype child) { double[] momLikelihoods = MathUtils.normalizeFromLog10(mom.getLikelihoods().getAsVector()); double[] dadLikelihoods = MathUtils.normalizeFromLog10(dad.getLikelihoods().getAsVector()); double[] childLikelihoods = MathUtils.normalizeFromLog10(child.getLikelihoods().getAsVector()); int momIndex = mom.getType().ordinal() - 1; int dadIndex = dad.getType().ordinal() - 1; int childIndex = child.getType().ordinal() - 1; return momLikelihoods[momIndex]*dadLikelihoods[dadIndex]*childLikelihoods[childIndex]; } private ArrayList<Genotype> createAllThreeGenotypes(Allele refAllele, Allele altAllele, Genotype g) { List<Allele> homRefAlleles = new ArrayList<Allele>(); homRefAlleles.add(refAllele); homRefAlleles.add(refAllele); Genotype homRef = new Genotype(g.getSampleName(), homRefAlleles, g.getNegLog10PError(), null, g.getAttributes(), false); List<Allele> hetAlleles = new ArrayList<Allele>(); hetAlleles.add(refAllele); hetAlleles.add(altAllele); Genotype het = new Genotype(g.getSampleName(), hetAlleles, g.getNegLog10PError(), null, g.getAttributes(), false); List<Allele> homVarAlleles = new ArrayList<Allele>(); homVarAlleles.add(altAllele); homVarAlleles.add(altAllele); Genotype homVar = new Genotype(g.getSampleName(), homVarAlleles, g.getNegLog10PError(), null, g.getAttributes(), false); ArrayList<Genotype> genotypes = new ArrayList<Genotype>(); genotypes.add(homRef); genotypes.add(het); genotypes.add(homVar); return genotypes; } private int getNumberOfMatchingAlleles(Allele alleleToMatch, Genotype g) { List<Allele> alleles = g.getAlleles(); int matchingAlleles = 0; for (Allele a : alleles) { if (!alleleToMatch.equals(a)) { matchingAlleles++; } } return matchingAlleles; } private boolean isMendelianViolation(Allele refAllele, Allele altAllele, Genotype mom, Genotype dad, Genotype child) { int numMomRefAlleles = getNumberOfMatchingAlleles(refAllele, mom) > 0 ? 1 : 0; int numMomAltAlleles = getNumberOfMatchingAlleles(altAllele, mom) > 0 ? 1 : 0; int numDadRefAlleles = getNumberOfMatchingAlleles(refAllele, dad) > 0 ? 1 : 0; int numDadAltAlleles = getNumberOfMatchingAlleles(altAllele, dad) > 0 ? 1 : 0; int numChildRefAlleles = getNumberOfMatchingAlleles(refAllele, child); int numChildAltAlleles = getNumberOfMatchingAlleles(altAllele, child); return (numMomRefAlleles + numDadRefAlleles < numChildRefAlleles || numMomAltAlleles + numDadAltAlleles < numChildAltAlleles); } private ArrayList<Genotype> getPhasedGenotypes(Genotype mom, Genotype dad, Genotype child) { Set<Genotype> possiblePhasedChildGenotypes = new HashSet<Genotype>(); for (Allele momAllele : mom.getAlleles()) { for (Allele dadAllele : dad.getAlleles()) { ArrayList<Allele> possiblePhasedChildAlleles = new ArrayList<Allele>(); possiblePhasedChildAlleles.add(momAllele); possiblePhasedChildAlleles.add(dadAllele); Genotype possiblePhasedChildGenotype = new Genotype(child.getSampleName(), possiblePhasedChildAlleles, child.getNegLog10PError(), child.getFilters(), child.getAttributes(), true); possiblePhasedChildGenotypes.add(possiblePhasedChildGenotype); } } ArrayList<Genotype> finalGenotypes = new ArrayList<Genotype>(); for (Genotype phasedChildGenotype : possiblePhasedChildGenotypes) { if (child.sameGenotype(phasedChildGenotype, true)) { Allele momTransmittedAllele = phasedChildGenotype.getAllele(0); Allele momUntransmittedAllele = mom.getAllele(0) != momTransmittedAllele ? mom.getAllele(0) : mom.getAllele(1); ArrayList<Allele> phasedMomAlleles = new ArrayList<Allele>(); phasedMomAlleles.add(momTransmittedAllele); phasedMomAlleles.add(momUntransmittedAllele); Genotype phasedMomGenotype = new Genotype(mom.getSampleName(), phasedMomAlleles, mom.getNegLog10PError(), mom.getFilters(), mom.getAttributes(), true); Allele dadTransmittedAllele = phasedChildGenotype.getAllele(1); Allele dadUntransmittedAllele = dad.getAllele(0) != dadTransmittedAllele ? dad.getAllele(0) : dad.getAllele(1); ArrayList<Allele> phasedDadAlleles = new ArrayList<Allele>(); phasedDadAlleles.add(dadTransmittedAllele); phasedDadAlleles.add(dadUntransmittedAllele); Genotype phasedDadGenotype = new Genotype(dad.getSampleName(), phasedDadAlleles, dad.getNegLog10PError(), dad.getFilters(), dad.getAttributes(), true); finalGenotypes.add(phasedMomGenotype); finalGenotypes.add(phasedDadGenotype); finalGenotypes.add(phasedChildGenotype); return finalGenotypes; } } finalGenotypes.add(mom); finalGenotypes.add(dad); finalGenotypes.add(child); return finalGenotypes; } private ArrayList<Genotype> phaseTrioGenotypes(Allele ref, Allele alt, Genotype mother, Genotype father, Genotype child) { ArrayList<Genotype> finalGenotypes = new ArrayList<Genotype>(); finalGenotypes.add(mother); finalGenotypes.add(father); finalGenotypes.add(child); - if (mother.isCalled() && father.isCalled() && child.isCalled() && !(mother.isHet() && father.isHet() && child.isHet())) { + if (mother.isCalled() && father.isCalled() && child.isCalled()) { ArrayList<Genotype> possibleMotherGenotypes = createAllThreeGenotypes(ref, alt, mother); ArrayList<Genotype> possibleFatherGenotypes = createAllThreeGenotypes(ref, alt, father); ArrayList<Genotype> possibleChildGenotypes = createAllThreeGenotypes(ref, alt, child); double bestConfigurationLikelihood = 0.0; double bestPrior = 0.0; Genotype bestMotherGenotype = mother; Genotype bestFatherGenotype = father; Genotype bestChildGenotype = child; double norm = 0.0; for (Genotype motherGenotype : possibleMotherGenotypes) { for (Genotype fatherGenotype : possibleFatherGenotypes) { for (Genotype childGenotype : possibleChildGenotypes) { double prior = isMendelianViolation(ref, alt, motherGenotype, fatherGenotype, childGenotype) ? MENDELIAN_VIOLATION_PRIOR : 1.0 - 12*MENDELIAN_VIOLATION_PRIOR; double configurationLikelihood = computeTransmissionLikelihoodOfGenotypeConfiguration(motherGenotype, fatherGenotype, childGenotype); norm += prior*configurationLikelihood; if (prior*configurationLikelihood > bestPrior*bestConfigurationLikelihood) { bestConfigurationLikelihood = configurationLikelihood; bestPrior = prior; bestMotherGenotype = motherGenotype; bestFatherGenotype = fatherGenotype; bestChildGenotype = childGenotype; } } } } - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.putAll(bestChildGenotype.getAttributes()); - attributes.put(TRANSMISSION_PROBABILITY_TAG_NAME, bestPrior*bestConfigurationLikelihood / norm); - bestChildGenotype = Genotype.modifyAttributes(bestChildGenotype, attributes); + if (!(bestMotherGenotype.isHet() && bestFatherGenotype.isHet() && bestChildGenotype.isHet())) { + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.putAll(bestChildGenotype.getAttributes()); + attributes.put(TRANSMISSION_PROBABILITY_TAG_NAME, bestPrior*bestConfigurationLikelihood / norm); + bestChildGenotype = Genotype.modifyAttributes(bestChildGenotype, attributes); - finalGenotypes = getPhasedGenotypes(bestMotherGenotype, bestFatherGenotype, bestChildGenotype); + finalGenotypes = getPhasedGenotypes(bestMotherGenotype, bestFatherGenotype, bestChildGenotype); + } } return finalGenotypes; } /** * For each variant in the file, determine the phasing for the child and replace the child's genotype with the trio's genotype * * @param tracker the reference meta-data tracker * @param ref the reference context * @param context the alignment context * @return null */ @Override public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { if (tracker != null) { Collection<VariantContext> vcs = tracker.getVariantContexts(ref, ROD_NAME, null, context.getLocation(), true, true); for (VariantContext vc : vcs) { Map<String, Genotype> genotypeMap = vc.getGenotypes(); for (Trio trio : trios) { Genotype mother = vc.getGenotype(trio.getMother()); Genotype father = vc.getGenotype(trio.getFather()); Genotype child = vc.getGenotype(trio.getChild()); ArrayList<Genotype> trioGenotypes = phaseTrioGenotypes(vc.getReference(), vc.getAltAlleleWithHighestAlleleCount(), mother, father, child); Genotype phasedMother = trioGenotypes.get(0); Genotype phasedFather = trioGenotypes.get(1); Genotype phasedChild = trioGenotypes.get(2); genotypeMap.put(phasedMother.getSampleName(), phasedMother); genotypeMap.put(phasedFather.getSampleName(), phasedFather); genotypeMap.put(phasedChild.getSampleName(), phasedChild); } VariantContext newvc = VariantContext.modifyGenotypes(vc, genotypeMap); vcfWriter.add(newvc, ref.getBase()); } } return null; } /** * Provide an initial value for reduce computations. * * @return Initial value of reduce. */ @Override public Integer reduceInit() { return null; } /** * Reduces a single map with the accumulator provided as the ReduceType. * * @param value result of the map. * @param sum accumulator for the reduce. * @return accumulator with result of the map taken into account. */ @Override public Integer reduce(Integer value, Integer sum) { return null; } }
false
false
null
null
diff --git a/mcu/src/cah/melonar/mcu/MainForm.java b/mcu/src/cah/melonar/mcu/MainForm.java index 61333da..2bd95ac 100644 --- a/mcu/src/cah/melonar/mcu/MainForm.java +++ b/mcu/src/cah/melonar/mcu/MainForm.java @@ -1,407 +1,408 @@ package cah.melonar.mcu; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.SwingConstants; import java.awt.Component; import javax.swing.Box; import java.awt.Font; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JCheckBox; import javax.swing.BoxLayout; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JTextPane; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Iterator; import java.util.List; import javax.swing.JRadioButtonMenuItem; import org.w3c.dom.Document; import org.w3c.dom.Element; import cah.melonar.mcu.MCUApp; import cah.melonar.mcu.util.MCUpdater; import cah.melonar.mcu.util.Module; import cah.melonar.mcu.util.ServerList; import javax.swing.JProgressBar; import java.util.ResourceBundle; //import org.lobobrowser.gui.FramePanel; //import org.lobobrowser.main.PlatformInit; public class MainForm extends MCUApp { private static final ResourceBundle Customization = ResourceBundle.getBundle("customization"); //$NON-NLS-1$ private static MainForm window; private JFrame frmMain; final MCUpdater mcu = new MCUpdater(); private JMenu mnList = new JMenu("List"); private final JTextPane browser = new JTextPane(); private ServerList selected; /* private URL packURL; private URLConnection con; private InputStream is; private DOMSource parser; private Document doc; private DOMAnalyzer da; private BrowserCanvas browser; */ private final JPanel pnlModList = new JPanel(); private JLabel lblStatus; private JProgressBar progressBar; /** * Create the application. */ public MainForm() { initialize(); window = this; window.frmMain.setVisible(true); mcu.setParent(window); } /** * Initialize the contents of the frame. */ void initialize() { /* try { PlatformInit.getInstance().initLogging(false); PlatformInit.getInstance().init(false,false); } catch (Exception e1) { e1.printStackTrace(); } */ frmMain = new JFrame(); frmMain.setTitle("[No Server Selected] - Minecraft Updater"); frmMain.setResizable(false); frmMain.setBounds(100, 100, 834, 592); frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pnlFooter = new JPanel(); frmMain.getContentPane().add(pnlFooter, BorderLayout.SOUTH); pnlFooter.setLayout(new BorderLayout(0, 0)); JPanel pnlButtons = new JPanel(); pnlFooter.add(pnlButtons, BorderLayout.EAST); JButton btnUpdate = new JButton("Update"); btnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Thread() { public void run() { int saveConfig = JOptionPane.showConfirmDialog(null, "Do you want to save a backup of your existing configuration?", "MCUpdater", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(saveConfig == JOptionPane.YES_OPTION){ setLblStatus("Creating backup"); setProgressBar(10); Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String backDesc = (String) JOptionPane.showInputDialog(null,"Enter description for backup:", "MCUpdater", JOptionPane.QUESTION_MESSAGE, null, null, ("Automatic backup: " + sdf.format(cal.getTime()))); mcu.saveConfig(backDesc); } else if(saveConfig == JOptionPane.CANCEL_OPTION){ return; } List<Module> toInstall = new ArrayList<Module>(); List<Component> selects = new ArrayList<Component>(Arrays.asList(pnlModList.getComponents())); Iterator<Component> it = selects.iterator(); setLblStatus("Preparing module list"); setProgressBar(20); while(it.hasNext()) { Component baseEntry = it.next(); - if(baseEntry.getClass().toString().equals("class cah.melonar.JModuleCheckBox")) { + System.out.println(baseEntry.getClass().toString()); + if(baseEntry.getClass().toString().equals("class cah.melonar.mcu.JModuleCheckBox")) { JModuleCheckBox entry = (JModuleCheckBox) baseEntry; if(entry.isSelected()){ toInstall.add(entry.getModule()); } } } try { setLblStatus("Installing mods"); setProgressBar(25); mcu.installMods(selected, toInstall); setLblStatus("Writing servers.dat"); setProgressBar(90); mcu.writeMCServerFile(selected.getName(), selected.getAddress()); setLblStatus("Finished"); setProgressBar(100); } catch (FileNotFoundException fnf) { JOptionPane.showMessageDialog(null, fnf.getMessage(), "MCUpdater", JOptionPane.ERROR_MESSAGE); } } }.start(); } }); pnlButtons.add(btnUpdate); JButton btnLaunchMinecraft = new JButton("Launch Minecraft"); btnLaunchMinecraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File launcher = new File(mcu.getMCFolder() + MCUpdater.sep + "minecraft.jar"); if(!launcher.exists()) { try { URL launcherURL = new URL("http://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar"); ReadableByteChannel rbc = Channels.newChannel(launcherURL.openStream()); FileOutputStream fos = new FileOutputStream(launcher); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } ProcessBuilder pb = new ProcessBuilder("java","-jar",launcher.getPath()); pb.redirectErrorStream(true); try { pb.start(); } catch (IOException ioe) { ioe.printStackTrace(); } } }); pnlButtons.add(btnLaunchMinecraft); JPanel pnlStatus = new JPanel(); pnlFooter.add(pnlStatus, BorderLayout.CENTER); pnlStatus.setLayout(new BorderLayout(0, 0)); lblStatus = new JLabel("Idle"); lblStatus.setHorizontalAlignment(SwingConstants.LEFT); pnlStatus.add(lblStatus); JPanel panel = new JPanel(); pnlStatus.add(panel, BorderLayout.EAST); panel.setLayout(new BorderLayout(0, 0)); progressBar = new JProgressBar(); panel.add(progressBar); progressBar.setStringPainted(true); Component TopStrut = Box.createVerticalStrut(5); panel.add(TopStrut, BorderLayout.NORTH); Component BottomStrut = Box.createVerticalStrut(5); panel.add(BottomStrut, BorderLayout.SOUTH); Component horizontalStrut = Box.createHorizontalStrut(5); pnlFooter.add(horizontalStrut, BorderLayout.WEST); JPanel pnlRight = new JPanel(); frmMain.getContentPane().add(pnlRight, BorderLayout.EAST); pnlRight.setLayout(new BorderLayout(0, 0)); JLabel lblChanges = new JLabel("Changes"); lblChanges.setHorizontalAlignment(SwingConstants.CENTER); lblChanges.setFont(new Font("Dialog", Font.BOLD, 14)); pnlRight.add(lblChanges, BorderLayout.NORTH); JScrollPane modScroller = new JScrollPane(pnlModList); pnlRight.add(modScroller, BorderLayout.CENTER); pnlModList.setLayout(new BoxLayout(pnlModList, BoxLayout.Y_AXIS)); browser.setEditable(false); browser.setContentType("text/html"); //final FramePanel browser = new FramePanel(); browser.setText("<HTML><BODY>There are no servers currently defined.</BODY></HTML>"); JScrollPane scrollPane = new JScrollPane(browser); scrollPane.setViewportBorder(null); browser.setBorder(null); frmMain.getContentPane().add(scrollPane, BorderLayout.CENTER); JMenuBar menuBar = new JMenuBar(); frmMain.setJMenuBar(menuBar); JMenu mnServers = new JMenu("Servers"); menuBar.add(mnServers); JMenuItem mntmManage = new JMenuItem("Manage"); mntmManage.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ServerManager sm = new ServerManager(window); sm.setVisible(true); } }); mnServers.add(mntmManage); mnServers.add(mnList); // Sample entry // JRadioButtonMenuItem mnuServerEntry = new JRadioButtonMenuItem("New radio item"); // mnList.add(mnuServerEntry); // File serverList = new File(mcu.getArchiveFolder() + MCUpdater.sep + "mcuServers.dat"); while(!serverList.exists()){ String packUrl = (String) JOptionPane.showInputDialog(null, "No servers defined.\nPlease enter URL to ServerPack.xml: ", "MCUpdater", JOptionPane.INFORMATION_MESSAGE, null, null, Customization.getString("InitialServer.text")); if(packUrl.isEmpty()) { System.exit(0); } try { Document serverHeader = MCUpdater.readXmlFromUrl(packUrl); Element docEle = serverHeader.getDocumentElement(); ServerList sl = new ServerList(docEle.getAttribute("name"), packUrl, docEle.getAttribute("newsUrl"), docEle.getAttribute("version"), docEle.getAttribute("serverAddress")); List<ServerList> servers = new ArrayList<ServerList>(); servers.add(sl); mcu.writeServerList(servers); } catch (Exception x) { x.printStackTrace(); } } updateServerList(); JMenu mnBackups = new JMenu("Backups"); menuBar.add(mnBackups); JMenuItem mntmManageBackups = new JMenuItem("Manage"); mntmManageBackups.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { BackupManager bm = new BackupManager(window); bm.setVisible(true); } }); mnBackups.add(mntmManageBackups); JMenu mnInfo = new JMenu("Info"); menuBar.add(mnInfo); JMenuItem mntmMinecraftjarVersion = new JMenuItem("minecraft.jar version: " + mcu.getMCVersion()); mnInfo.add(mntmMinecraftjarVersion); } public void updateServerList() { mnList.removeAll(); List<ServerList> servers = mcu.loadServerList(); if(servers != null) { Iterator<ServerList> it = servers.iterator(); boolean flag = false; while(it.hasNext()) { ServerList entry = it.next(); final JServerMenuItem mnuServerEntry = new JServerMenuItem(entry.getName()); mnuServerEntry.setServerEntry(entry); mnList.add(mnuServerEntry); mnuServerEntry.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { //browser.navigate(mnuServerEntry.getServerEntry().getNewsUrl()); selected = mnuServerEntry.getServerEntry(); browser.setPage(mnuServerEntry.getServerEntry().getNewsUrl()); frmMain.setTitle(mnuServerEntry.getServerEntry().getName() + " - Minecraft Updater"); List<Module> modules = mcu.loadFromURL(mnuServerEntry.getServerEntry().getPackUrl()); Iterator<Module> itMods = modules.iterator(); pnlModList.setVisible(false); pnlModList.removeAll(); while(itMods.hasNext()) { Module modEntry = itMods.next(); JModuleCheckBox chkModule = new JModuleCheckBox(modEntry.getName()); if(modEntry.getInJar()) { chkModule.setFont(chkModule.getFont().deriveFont(Font.BOLD)); } chkModule.setModule(modEntry); if(modEntry.getRequired()) { chkModule.setSelected(true); chkModule.setEnabled(false); } pnlModList.add(chkModule); } pnlModList.setVisible(true); } catch (IOException ioe) { ioe.printStackTrace(); } } }); if(flag==false) { mnuServerEntry.doClick(); flag=true; } } } } @Override public void setLblStatus(String text) { lblStatus.setText(text); } @Override public void setProgressBar(int value) { progressBar.setValue(value); } } class JModuleCheckBox extends JCheckBox { /** * */ private static final long serialVersionUID = 8124564072878896685L; private Module entry; public JModuleCheckBox(String name) { super(name); } public void setModule(Module entry) { this.entry=entry; } public Module getModule() { return entry; } } class JServerMenuItem extends JRadioButtonMenuItem { private ServerList entry; /** * */ private static final long serialVersionUID = -6374548651338922992L; public JServerMenuItem(String name) { super(name); } public void setServerEntry(ServerList entry) { this.entry = entry; } public ServerList getServerEntry() { return entry; } } \ No newline at end of file
true
false
null
null
diff --git a/src/org/apache/xerces/parsers/AbstractDOMParser.java b/src/org/apache/xerces/parsers/AbstractDOMParser.java index bb8e5c53f..2d613cb67 100644 --- a/src/org/apache/xerces/parsers/AbstractDOMParser.java +++ b/src/org/apache/xerces/parsers/AbstractDOMParser.java @@ -1,2624 +1,2629 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.parsers; import java.util.Locale; import java.util.Stack; import org.apache.xerces.dom.AttrImpl; import org.apache.xerces.dom.CoreDocumentImpl; import org.apache.xerces.dom.DOMErrorImpl; import org.apache.xerces.dom.DOMMessageFormatter; import org.apache.xerces.dom.DeferredDocumentImpl; import org.apache.xerces.dom.DocumentImpl; import org.apache.xerces.dom.DocumentTypeImpl; import org.apache.xerces.dom.ElementDefinitionImpl; import org.apache.xerces.dom.ElementImpl; import org.apache.xerces.dom.ElementNSImpl; import org.apache.xerces.dom.EntityImpl; import org.apache.xerces.dom.EntityReferenceImpl; import org.apache.xerces.dom.NodeImpl; import org.apache.xerces.dom.NotationImpl; import org.apache.xerces.dom.PSVIAttrNSImpl; import org.apache.xerces.dom.PSVIDocumentImpl; import org.apache.xerces.dom.PSVIElementNSImpl; import org.apache.xerces.dom.TextImpl; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.util.DOMErrorHandlerWrapper; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLParserConfiguration; import org.apache.xerces.xs.AttributePSVI; import org.apache.xerces.xs.ElementPSVI; import org.apache.xerces.xs.XSTypeDefinition; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMError; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.w3c.dom.ls.LSParserFilter; import org.w3c.dom.traversal.NodeFilter; import org.xml.sax.SAXException; /** * This is the base class of all DOM parsers. It implements the XNI * callback methods to create the DOM tree. After a successful parse of * an XML document, the DOM Document object can be queried using the * <code>getDocument</code> method. The actual pipeline is defined in * parser configuration. * * @author Arnaud Le Hors, IBM * @author Andy Clark, IBM * @author Elena Litani, IBM * * @version $Id$ */ public class AbstractDOMParser extends AbstractXMLDocumentParser { // // Constants // // feature ids /** Feature id: namespace. */ protected static final String NAMESPACES = Constants.SAX_FEATURE_PREFIX+Constants.NAMESPACES_FEATURE; /** Feature id: create entity ref nodes. */ protected static final String CREATE_ENTITY_REF_NODES = Constants.XERCES_FEATURE_PREFIX + Constants.CREATE_ENTITY_REF_NODES_FEATURE; /** Feature id: include comments. */ protected static final String INCLUDE_COMMENTS_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.INCLUDE_COMMENTS_FEATURE; /** Feature id: create cdata nodes. */ protected static final String CREATE_CDATA_NODES_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.CREATE_CDATA_NODES_FEATURE; /** Feature id: include ignorable whitespace. */ protected static final String INCLUDE_IGNORABLE_WHITESPACE = Constants.XERCES_FEATURE_PREFIX + Constants.INCLUDE_IGNORABLE_WHITESPACE; /** Feature id: defer node expansion. */ protected static final String DEFER_NODE_EXPANSION = Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE; /** Recognized features. */ private static final String[] RECOGNIZED_FEATURES = { NAMESPACES, CREATE_ENTITY_REF_NODES, INCLUDE_COMMENTS_FEATURE, CREATE_CDATA_NODES_FEATURE, INCLUDE_IGNORABLE_WHITESPACE, DEFER_NODE_EXPANSION }; // property ids /** Property id: document class name. */ protected static final String DOCUMENT_CLASS_NAME = Constants.XERCES_PROPERTY_PREFIX + Constants.DOCUMENT_CLASS_NAME_PROPERTY; protected static final String CURRENT_ELEMENT_NODE= Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY; // protected static final String GRAMMAR_POOL = // Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; /** Recognized properties. */ private static final String[] RECOGNIZED_PROPERTIES = { DOCUMENT_CLASS_NAME, CURRENT_ELEMENT_NODE, }; // other /** Default document class name. */ protected static final String DEFAULT_DOCUMENT_CLASS_NAME = "org.apache.xerces.dom.DocumentImpl"; protected static final String CORE_DOCUMENT_CLASS_NAME = "org.apache.xerces.dom.CoreDocumentImpl"; protected static final String PSVI_DOCUMENT_CLASS_NAME = "org.apache.xerces.dom.PSVIDocumentImpl"; /** * If the user stops the process, this exception will be thrown. */ protected static final RuntimeException ABORT = new RuntimeException() { private static final long serialVersionUID = 1687848994976808490L; public Throwable fillInStackTrace() { return this; } }; // debugging private static final boolean DEBUG_EVENTS = false; private static final boolean DEBUG_BASEURI = false; // // Data // /** DOM L3 error handler */ protected DOMErrorHandlerWrapper fErrorHandler = null; /** True if inside DTD. */ protected boolean fInDTD; // features /** Create entity reference nodes. */ protected boolean fCreateEntityRefNodes; /** Include ignorable whitespace. */ protected boolean fIncludeIgnorableWhitespace; /** Include Comments. */ protected boolean fIncludeComments; /** Create cdata nodes. */ protected boolean fCreateCDATANodes; // dom information /** The document. */ protected Document fDocument; /** The default Xerces document implementation, if used. */ protected CoreDocumentImpl fDocumentImpl; /** Whether to store PSVI information in DOM tree. */ protected boolean fStorePSVI; /** The document class name to use. */ protected String fDocumentClassName; /** The document type node. */ protected DocumentType fDocumentType; /** Current node. */ protected Node fCurrentNode; protected CDATASection fCurrentCDATASection; protected EntityImpl fCurrentEntityDecl; protected int fDeferredEntityDecl; /** Character buffer */ protected final StringBuffer fStringBuffer = new StringBuffer (50); // internal subset /** Internal subset buffer. */ protected StringBuffer fInternalSubset; // deferred expansion data protected boolean fDeferNodeExpansion; protected boolean fNamespaceAware; protected DeferredDocumentImpl fDeferredDocumentImpl; protected int fDocumentIndex; protected int fDocumentTypeIndex; protected int fCurrentNodeIndex; protected int fCurrentCDATASectionIndex; // state /** True if inside DTD external subset. */ protected boolean fInDTDExternalSubset; /** Root element node. */ protected Node fRoot; /** True if inside CDATA section. */ protected boolean fInCDATASection; /** True if saw the first chunk of characters*/ protected boolean fFirstChunk = false; /** LSParserFilter: specifies that element with given QNAME and all its children * must be rejected */ protected boolean fFilterReject = false; // data /** Base uri stack*/ protected final Stack fBaseURIStack = new Stack (); - /** LSParserFilter: the QNAME of rejected element*/ - protected final QName fRejectedElement = new QName (); + /** LSParserFilter: tracks the element depth within a rejected subtree. */ + protected int fRejectedElementDepth = 0; - /** LSParserFilter: store qnames of skipped elements*/ + /** LSParserFilter: store depth of skipped elements */ protected Stack fSkippedElemStack = null; /** LSParserFilter: true if inside entity reference */ protected boolean fInEntityRef = false; /** Attribute QName. */ private final QName fAttrQName = new QName(); /** Document locator. */ private XMLLocator fLocator; // handlers protected LSParserFilter fDOMFilter = null; // // Constructors // /** Default constructor. */ protected AbstractDOMParser (XMLParserConfiguration config) { super (config); // add recognized features fConfiguration.addRecognizedFeatures (RECOGNIZED_FEATURES); // set default values fConfiguration.setFeature (CREATE_ENTITY_REF_NODES, true); fConfiguration.setFeature (INCLUDE_IGNORABLE_WHITESPACE, true); fConfiguration.setFeature (DEFER_NODE_EXPANSION, true); fConfiguration.setFeature (INCLUDE_COMMENTS_FEATURE, true); fConfiguration.setFeature (CREATE_CDATA_NODES_FEATURE, true); // add recognized properties fConfiguration.addRecognizedProperties (RECOGNIZED_PROPERTIES); // set default values fConfiguration.setProperty (DOCUMENT_CLASS_NAME, DEFAULT_DOCUMENT_CLASS_NAME); } // <init>(XMLParserConfiguration) /** * This method retreives the name of current document class. */ protected String getDocumentClassName () { return fDocumentClassName; } /** * This method allows the programmer to decide which document * factory to use when constructing the DOM tree. However, doing * so will lose the functionality of the default factory. Also, * a document class other than the default will lose the ability * to defer node expansion on the DOM tree produced. * * @param documentClassName The fully qualified class name of the * document factory to use when constructing * the DOM tree. * * @see #getDocumentClassName * @see #DEFAULT_DOCUMENT_CLASS_NAME */ protected void setDocumentClassName (String documentClassName) { // normalize class name if (documentClassName == null) { documentClassName = DEFAULT_DOCUMENT_CLASS_NAME; } if (!documentClassName.equals(DEFAULT_DOCUMENT_CLASS_NAME) && !documentClassName.equals(PSVI_DOCUMENT_CLASS_NAME)) { // verify that this class exists and is of the right type try { Class _class = ObjectFactory.findProviderClass (documentClassName, ObjectFactory.findClassLoader (), true); //if (!_class.isAssignableFrom(Document.class)) { if (!Document.class.isAssignableFrom (_class)) { throw new IllegalArgumentException ( DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "InvalidDocumentClassName", new Object [] {documentClassName})); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException ( DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "MissingDocumentClassName", new Object [] {documentClassName})); } } // set document class name fDocumentClassName = documentClassName; if (!documentClassName.equals (DEFAULT_DOCUMENT_CLASS_NAME)) { fDeferNodeExpansion = false; } } // setDocumentClassName(String) // // Public methods // /** Returns the DOM document object. */ public Document getDocument () { return fDocument; } // getDocument():Document /** * Drops all references to the last DOM which was built by this parser. */ public final void dropDocumentReferences() { fDocument = null; fDocumentImpl = null; fDeferredDocumentImpl = null; fDocumentType = null; fCurrentNode = null; fCurrentCDATASection = null; fCurrentEntityDecl = null; fRoot = null; } // dropDocumentReferences() // // XMLDocumentParser methods // /** * Resets the parser state. * * @throws SAXException Thrown on initialization error. */ public void reset () throws XNIException { super.reset (); // get feature state fCreateEntityRefNodes = fConfiguration.getFeature (CREATE_ENTITY_REF_NODES); fIncludeIgnorableWhitespace = fConfiguration.getFeature (INCLUDE_IGNORABLE_WHITESPACE); fDeferNodeExpansion = fConfiguration.getFeature (DEFER_NODE_EXPANSION); fNamespaceAware = fConfiguration.getFeature (NAMESPACES); fIncludeComments = fConfiguration.getFeature (INCLUDE_COMMENTS_FEATURE); fCreateCDATANodes = fConfiguration.getFeature (CREATE_CDATA_NODES_FEATURE); // get property setDocumentClassName ((String) fConfiguration.getProperty (DOCUMENT_CLASS_NAME)); // reset dom information fDocument = null; fDocumentImpl = null; fStorePSVI = false; fDocumentType = null; fDocumentTypeIndex = -1; fDeferredDocumentImpl = null; fCurrentNode = null; // reset string buffer fStringBuffer.setLength (0); // reset state information fRoot = null; fInDTD = false; fInDTDExternalSubset = false; fInCDATASection = false; fFirstChunk = false; fCurrentCDATASection = null; fCurrentCDATASectionIndex = -1; fBaseURIStack.removeAllElements (); } // reset() /** * Set the locale to use for messages. * * @param locale The locale object to use for localization of messages. * */ public void setLocale (Locale locale) { fConfiguration.setLocale (locale); } // setLocale(Locale) // // XMLDocumentHandler methods // /** * This method notifies the start of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the general entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @exception XNIException Thrown by handler to signal an error. */ public void startGeneralEntity (String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>startGeneralEntity ("+name+")"); if (DEBUG_BASEURI) { System.out.println (" expandedSystemId( **baseURI): "+identifier.getExpandedSystemId ()); System.out.println (" baseURI:"+ identifier.getBaseSystemId ()); } } // Always create entity reference nodes to be able to recreate // entity as a part of doctype if (!fDeferNodeExpansion) { if (fFilterReject) { return; } setCharacterData (true); EntityReference er = fDocument.createEntityReference (name); if (fDocumentImpl != null) { // REVISIT: baseURI/actualEncoding // remove dependency on our implementation when DOM L3 is REC // EntityReferenceImpl erImpl =(EntityReferenceImpl)er; // set base uri erImpl.setBaseURI (identifier.getExpandedSystemId ()); if (fDocumentType != null) { // set actual encoding NamedNodeMap entities = fDocumentType.getEntities (); fCurrentEntityDecl = (EntityImpl) entities.getNamedItem (name); if (fCurrentEntityDecl != null) { fCurrentEntityDecl.setInputEncoding (encoding); } } // we don't need synchronization now, because entity ref will be // expanded anyway. Synch only needed when user creates entityRef node erImpl.needsSyncChildren (false); } fInEntityRef = true; fCurrentNode.appendChild (er); fCurrentNode = er; } else { int er = fDeferredDocumentImpl.createDeferredEntityReference (name, identifier.getExpandedSystemId ()); if (fDocumentTypeIndex != -1) { // find corresponding Entity decl int node = fDeferredDocumentImpl.getLastChild (fDocumentTypeIndex, false); while (node != -1) { short nodeType = fDeferredDocumentImpl.getNodeType (node, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName (node, false); if (nodeName.equals (name)) { fDeferredEntityDecl = node; fDeferredDocumentImpl.setInputEncoding (node, encoding); break; } } node = fDeferredDocumentImpl.getRealPrevSibling (node, false); } } fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, er); fCurrentNodeIndex = er; } } // startGeneralEntity(String,XMLResourceIdentifier, Augmentations) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl (String version, String encoding, Augmentations augs) throws XNIException { if (fInDTD){ return; } if (!fDeferNodeExpansion) { if (fCurrentEntityDecl != null && !fFilterReject) { fCurrentEntityDecl.setXmlEncoding (encoding); if (version != null) fCurrentEntityDecl.setXmlVersion (version); } } else { if (fDeferredEntityDecl !=-1) { fDeferredDocumentImpl.setEntityInfo (fDeferredEntityDecl, version, encoding); } } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by application to signal an error. */ public void comment (XMLString text, Augmentations augs) throws XNIException { if (fInDTD) { if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<!--"); if (text.length > 0) { fInternalSubset.append (text.ch, text.offset, text.length); } fInternalSubset.append ("-->"); } return; } if (!fIncludeComments || fFilterReject) { return; } if (!fDeferNodeExpansion) { Comment comment = fDocument.createComment (text.toString ()); setCharacterData (false); fCurrentNode.appendChild (comment); if (fDOMFilter !=null && !fInEntityRef && (fDOMFilter.getWhatToShow () & NodeFilter.SHOW_COMMENT)!= 0) { short code = fDOMFilter.acceptNode (comment); switch (code) { case LSParserFilter.FILTER_INTERRUPT:{ throw ABORT; } case LSParserFilter.FILTER_REJECT:{ // REVISIT: the constant FILTER_REJECT should be changed when new // DOM LS specs gets published // fall through to SKIP since comment has no children. } case LSParserFilter.FILTER_SKIP: { // REVISIT: the constant FILTER_SKIP should be changed when new // DOM LS specs gets published fCurrentNode.removeChild (comment); // make sure we don't loose chars if next event is characters() fFirstChunk = true; return; } default: { // accept node } } } } else { int comment = fDeferredDocumentImpl.createDeferredComment (text.toString ()); fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, comment); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction (String target, XMLString data, Augmentations augs) throws XNIException { if (fInDTD) { if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<?"); fInternalSubset.append (target); if (data.length > 0) { fInternalSubset.append (' ').append (data.ch, data.offset, data.length); } fInternalSubset.append ("?>"); } return; } if (DEBUG_EVENTS) { System.out.println ("==>processingInstruction ("+target+")"); } if (!fDeferNodeExpansion) { if (fFilterReject) { return; } ProcessingInstruction pi = fDocument.createProcessingInstruction (target, data.toString ()); setCharacterData (false); fCurrentNode.appendChild (pi); if (fDOMFilter !=null && !fInEntityRef && (fDOMFilter.getWhatToShow () & NodeFilter.SHOW_PROCESSING_INSTRUCTION)!= 0) { short code = fDOMFilter.acceptNode (pi); switch (code) { case LSParserFilter.FILTER_INTERRUPT:{ throw ABORT; } case LSParserFilter.FILTER_REJECT:{ // fall through to SKIP since PI has no children. } case LSParserFilter.FILTER_SKIP: { fCurrentNode.removeChild (pi); // fFirstChunk must be set to true so that data // won't be lost in the case where the child before PI is // a text node and the next event is characters. fFirstChunk = true; return; } default: { } } } } else { int pi = fDeferredDocumentImpl. createDeferredProcessingInstruction (target, data.toString ()); fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, pi); } } // processingInstruction(String,XMLString) /** * The start of the document. * * @param locator The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param namespaceContext * The namespace context in effect at the * start of this document. * This object represents the current context. * Implementors of this class are responsible * for copying the namespace bindings from the * the current context (and its parent contexts) * if that information is important. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument (XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { fLocator = locator; if (!fDeferNodeExpansion) { if (fDocumentClassName.equals (DEFAULT_DOCUMENT_CLASS_NAME)) { fDocument = new DocumentImpl (); fDocumentImpl = (CoreDocumentImpl)fDocument; // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class // set DOM error checking off fDocumentImpl.setStrictErrorChecking (false); // set actual encoding fDocumentImpl.setInputEncoding (encoding); // set documentURI fDocumentImpl.setDocumentURI (locator.getExpandedSystemId ()); } else if (fDocumentClassName.equals (PSVI_DOCUMENT_CLASS_NAME)) { fDocument = new PSVIDocumentImpl(); fDocumentImpl = (CoreDocumentImpl)fDocument; fStorePSVI = true; // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class // set DOM error checking off fDocumentImpl.setStrictErrorChecking (false); // set actual encoding fDocumentImpl.setInputEncoding (encoding); // set documentURI fDocumentImpl.setDocumentURI (locator.getExpandedSystemId ()); } else { // use specified document class try { ClassLoader cl = ObjectFactory.findClassLoader(); Class documentClass = ObjectFactory.findProviderClass (fDocumentClassName, cl, true); fDocument = (Document)documentClass.newInstance (); // if subclass of our own class that's cool too Class defaultDocClass = ObjectFactory.findProviderClass (CORE_DOCUMENT_CLASS_NAME, cl, true); if (defaultDocClass.isAssignableFrom (documentClass)) { fDocumentImpl = (CoreDocumentImpl)fDocument; Class psviDocClass = ObjectFactory.findProviderClass (PSVI_DOCUMENT_CLASS_NAME, cl, true); if (psviDocClass.isAssignableFrom (documentClass)) { fStorePSVI = true; } // REVISIT: when DOM Level 3 is REC rely on // Document.support instead of specific class // set DOM error checking off fDocumentImpl.setStrictErrorChecking (false); // set actual encoding fDocumentImpl.setInputEncoding (encoding); // set documentURI if (locator != null) { fDocumentImpl.setDocumentURI (locator.getExpandedSystemId ()); } } } catch (ClassNotFoundException e) { // won't happen we already checked that earlier } catch (Exception e) { throw new RuntimeException ( DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "CannotCreateDocumentClass", new Object [] {fDocumentClassName})); } } fCurrentNode = fDocument; } else { fDeferredDocumentImpl = new DeferredDocumentImpl (fNamespaceAware); fDocument = fDeferredDocumentImpl; fDocumentIndex = fDeferredDocumentImpl.createDeferredDocument (); // REVISIT: strict error checking is not implemented in deferred dom. // Document.support instead of specific class // set actual encoding fDeferredDocumentImpl.setInputEncoding (encoding); // set documentURI fDeferredDocumentImpl.setDocumentURI (locator.getExpandedSystemId ()); fCurrentNodeIndex = fDocumentIndex; } } // startDocument(String,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl (String version, String encoding, String standalone, Augmentations augs) throws XNIException { if (!fDeferNodeExpansion) { // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class if (fDocumentImpl != null) { if (version != null) fDocumentImpl.setXmlVersion (version); fDocumentImpl.setXmlEncoding (encoding); fDocumentImpl.setXmlStandalone ("yes".equals (standalone)); } } else { if (version != null) fDeferredDocumentImpl.setXmlVersion (version); fDeferredDocumentImpl.setXmlEncoding (encoding); fDeferredDocumentImpl.setXmlStandalone ("yes".equals (standalone)); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl (String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { if (!fDeferNodeExpansion) { if (fDocumentImpl != null) { fDocumentType = fDocumentImpl.createDocumentType ( rootElement, publicId, systemId); fCurrentNode.appendChild (fDocumentType); } } else { fDocumentTypeIndex = fDeferredDocumentImpl. createDeferredDocumentType (rootElement, publicId, systemId); fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, fDocumentTypeIndex); } } // doctypeDecl(String,String,String) /** * The start of an element. If the document specifies the start element * by using an empty tag, then the startElement method will immediately * be followed by the endElement method, with no intervening methods. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement (QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>startElement ("+element.rawname+")"); } if (!fDeferNodeExpansion) { if (fFilterReject) { + ++fRejectedElementDepth; return; } Element el = createElementNode (element); int attrCount = attributes.getLength (); boolean seenSchemaDefault = false; for (int i = 0; i < attrCount; i++) { attributes.getName (i, fAttrQName); Attr attr = createAttrNode (fAttrQName); String attrValue = attributes.getValue (i); AttributePSVI attrPSVI =(AttributePSVI) attributes.getAugmentations (i).getItem (Constants.ATTRIBUTE_PSVI); if (fStorePSVI && attrPSVI != null){ ((PSVIAttrNSImpl) attr).setPSVI (attrPSVI); } attr.setValue (attrValue); boolean specified = attributes.isSpecified(i); // Take special care of schema defaulted attributes. Calling the // non-namespace aware setAttributeNode() method could overwrite // another attribute with the same local name. if (!specified && (seenSchemaDefault || (fAttrQName.uri != null && fAttrQName.prefix == null))) { el.setAttributeNodeNS(attr); seenSchemaDefault = true; } else { el.setAttributeNode(attr); } // NOTE: The specified value MUST be set after you set // the node value because that turns the "specified" // flag to "true" which may overwrite a "false" // value from the attribute list. -Ac if (fDocumentImpl != null) { AttrImpl attrImpl = (AttrImpl) attr; Object type = null; boolean id = false; // REVISIT: currently it is possible that someone turns off // namespaces and turns on xml schema validation // To avoid classcast exception in AttrImpl check for namespaces // however the correct solution should probably disallow setting // namespaces to false when schema processing is turned on. if (attrPSVI != null && fNamespaceAware) { // XML Schema type = attrPSVI.getMemberTypeDefinition (); if (type == null) { type = attrPSVI.getTypeDefinition (); if (type != null) { id = ((XSSimpleType) type).isIDType (); attrImpl.setType (type); } } else { id = ((XSSimpleType) type).isIDType (); attrImpl.setType (type); } } else { // DTD boolean isDeclared = Boolean.TRUE.equals (attributes.getAugmentations (i).getItem (Constants.ATTRIBUTE_DECLARED)); // For DOM Level 3 TypeInfo, the type name must // be null if this attribute has not been declared // in the DTD. if (isDeclared) { type = attributes.getType (i); id = "ID".equals (type); } attrImpl.setType (type); } if (id) { ((ElementImpl) el).setIdAttributeNode (attr, true); } attrImpl.setSpecified (specified); // REVISIT: Handle entities in attribute value. } } setCharacterData (false); if (augs != null) { ElementPSVI elementPSVI = (ElementPSVI)augs.getItem (Constants.ELEMENT_PSVI); if (elementPSVI != null && fNamespaceAware) { XSTypeDefinition type = elementPSVI.getMemberTypeDefinition (); if (type == null) { type = elementPSVI.getTypeDefinition (); } ((ElementNSImpl)el).setType (type); } } // filter nodes if (fDOMFilter != null && !fInEntityRef) { if (fRoot == null) { // fill value of the root element fRoot = el; } else { short code = fDOMFilter.startElement(el); switch (code) { case LSParserFilter.FILTER_INTERRUPT : { throw ABORT; } case LSParserFilter.FILTER_REJECT : { fFilterReject = true; - fRejectedElement.setValues(element); + fRejectedElementDepth = 0; return; } case LSParserFilter.FILTER_SKIP : { - fSkippedElemStack.push(element.clone()); + fSkippedElemStack.push(Boolean.TRUE); return; } - default : {} + default : + { + if (!fSkippedElemStack.isEmpty()) { + fSkippedElemStack.push(Boolean.FALSE); + } + } } } } fCurrentNode.appendChild (el); fCurrentNode = el; } else { int el = fDeferredDocumentImpl.createDeferredElement (fNamespaceAware ? element.uri : null, element.rawname); Object type = null; int attrCount = attributes.getLength (); // Need to loop in reverse order so that the attributes // are processed in document order when the DOM is expanded. for (int i = attrCount - 1; i >= 0; --i) { // set type information AttributePSVI attrPSVI = (AttributePSVI)attributes.getAugmentations (i).getItem (Constants.ATTRIBUTE_PSVI); boolean id = false; // REVISIT: currently it is possible that someone turns off // namespaces and turns on xml schema validation // To avoid classcast exception in AttrImpl check for namespaces // however the correct solution should probably disallow setting // namespaces to false when schema processing is turned on. if (attrPSVI != null && fNamespaceAware) { // XML Schema type = attrPSVI.getMemberTypeDefinition (); if (type == null) { type = attrPSVI.getTypeDefinition (); if (type != null){ id = ((XSSimpleType) type).isIDType (); } } else { id = ((XSSimpleType) type).isIDType (); } } else { // DTD boolean isDeclared = Boolean.TRUE.equals (attributes.getAugmentations (i).getItem (Constants.ATTRIBUTE_DECLARED)); // For DOM Level 3 TypeInfo, the type name must // be null if this attribute has not been declared // in the DTD. if (isDeclared) { type = attributes.getType (i); id = "ID".equals (type); } } // create attribute fDeferredDocumentImpl.setDeferredAttribute ( el, attributes.getQName (i), attributes.getURI (i), attributes.getValue (i), attributes.isSpecified (i), id, type); } fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, el); fCurrentNodeIndex = el; } } // startElement(QName,XMLAttributes) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement (QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { startElement (element, attributes, augs); endElement (element, augs); } // emptyElement(QName,XMLAttributes) /** * Character content. * * @param text The content. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void characters (XMLString text, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>characters(): "+text.toString ()); } if (!fDeferNodeExpansion) { if (fFilterReject) { return; } if (fInCDATASection && fCreateCDATANodes) { if (fCurrentCDATASection == null) { fCurrentCDATASection = fDocument.createCDATASection (text.toString ()); fCurrentNode.appendChild (fCurrentCDATASection); fCurrentNode = fCurrentCDATASection; } else { fCurrentCDATASection.appendData (text.toString ()); } } else if (!fInDTD) { // if type is union (XML Schema) it is possible that we receive // character call with empty data if (text.length == 0) { return; } Node child = fCurrentNode.getLastChild (); if (child != null && child.getNodeType () == Node.TEXT_NODE) { // collect all the data into the string buffer. if (fFirstChunk) { if (fDocumentImpl != null) { fStringBuffer.append (((TextImpl)child).removeData ()); } else { fStringBuffer.append (((Text)child).getData ()); ((Text)child).setNodeValue (null); } fFirstChunk = false; } if (text.length > 0) { fStringBuffer.append (text.ch, text.offset, text.length); } } else { fFirstChunk = true; Text textNode = fDocument.createTextNode (text.toString()); fCurrentNode.appendChild (textNode); } } } else { // The Text and CDATASection normalization is taken care of within // the DOM in the deferred case. if (fInCDATASection && fCreateCDATANodes) { if (fCurrentCDATASectionIndex == -1) { int cs = fDeferredDocumentImpl. createDeferredCDATASection (text.toString ()); fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, cs); fCurrentCDATASectionIndex = cs; fCurrentNodeIndex = cs; } else { int txt = fDeferredDocumentImpl. createDeferredTextNode (text.toString (), false); fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, txt); } } else if (!fInDTD) { // if type is union (XML Schema) it is possible that we receive // character call with empty data if (text.length == 0) { return; } String value = text.toString (); int txt = fDeferredDocumentImpl. createDeferredTextNode (value, false); fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, txt); } } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace (XMLString text, Augmentations augs) throws XNIException { if (!fIncludeIgnorableWhitespace || fFilterReject) { return; } if (!fDeferNodeExpansion) { Node child = fCurrentNode.getLastChild (); if (child != null && child.getNodeType () == Node.TEXT_NODE) { Text textNode = (Text)child; textNode.appendData (text.toString ()); } else { Text textNode = fDocument.createTextNode (text.toString ()); if (fDocumentImpl != null) { TextImpl textNodeImpl = (TextImpl)textNode; textNodeImpl.setIgnorableWhitespace (true); } fCurrentNode.appendChild (textNode); } } else { // The Text normalization is taken care of within the DOM in the // deferred case. int txt = fDeferredDocumentImpl. createDeferredTextNode (text.toString (), true); fDeferredDocumentImpl.appendChild (fCurrentNodeIndex, txt); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endElement (QName element, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>endElement ("+element.rawname+")"); } if (!fDeferNodeExpansion) { // REVISIT: Should this happen after we call the filter? if (augs != null && fDocumentImpl != null && (fNamespaceAware || fStorePSVI)) { ElementPSVI elementPSVI = (ElementPSVI) augs.getItem(Constants.ELEMENT_PSVI); if (elementPSVI != null) { // Updating TypeInfo. If the declared type is a union the // [member type definition] will only be available at the // end of an element. if (fNamespaceAware) { XSTypeDefinition type = elementPSVI.getMemberTypeDefinition(); if (type == null) { type = elementPSVI.getTypeDefinition(); } ((ElementNSImpl)fCurrentNode).setType(type); } if (fStorePSVI) { ((PSVIElementNSImpl)fCurrentNode).setPSVI (elementPSVI); } } } if (fDOMFilter != null) { if (fFilterReject) { - if (element.equals (fRejectedElement)) { + if (fRejectedElementDepth-- == 0) { fFilterReject = false; } return; } - if (!fSkippedElemStack.isEmpty ()) { - if (fSkippedElemStack.peek ().equals (element)) { - fSkippedElemStack.pop (); + if (!fSkippedElemStack.isEmpty()) { + if (fSkippedElemStack.pop() == Boolean.TRUE) { return; } } setCharacterData (false); if ((fCurrentNode != fRoot) && !fInEntityRef && (fDOMFilter.getWhatToShow () & NodeFilter.SHOW_ELEMENT)!=0) { short code = fDOMFilter.acceptNode (fCurrentNode); switch (code) { case LSParserFilter.FILTER_INTERRUPT:{ throw ABORT; } case LSParserFilter.FILTER_REJECT:{ Node parent = fCurrentNode.getParentNode (); parent.removeChild (fCurrentNode); fCurrentNode = parent; return; } case LSParserFilter.FILTER_SKIP: { // make sure that if any char data is available // the fFirstChunk is true, so that if the next event // is characters(), and the last node is text, we will copy // the value already in the text node to fStringBuffer // (not to loose it). fFirstChunk = true; // replace children Node parent = fCurrentNode.getParentNode (); NodeList ls = fCurrentNode.getChildNodes (); int length = ls.getLength (); for (int i=0;i<length;i++) { parent.appendChild (ls.item (0)); } parent.removeChild (fCurrentNode); fCurrentNode = parent; return; } default: { } } } fCurrentNode = fCurrentNode.getParentNode (); } // end-if DOMFilter else { setCharacterData (false); fCurrentNode = fCurrentNode.getParentNode (); } } else { if (augs != null) { ElementPSVI elementPSVI = (ElementPSVI) augs.getItem(Constants.ELEMENT_PSVI); if (elementPSVI != null) { // Setting TypeInfo. If the declared type is a union the // [member type definition] will only be available at the // end of an element. XSTypeDefinition type = elementPSVI.getMemberTypeDefinition(); if (type == null) { type = elementPSVI.getTypeDefinition(); } fDeferredDocumentImpl.setTypeInfo(fCurrentNodeIndex, type); } } fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode (fCurrentNodeIndex, false); } } // endElement(QName) /** * The start of a CDATA section. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA (Augmentations augs) throws XNIException { fInCDATASection = true; if (!fDeferNodeExpansion) { if (fFilterReject) { return; } if (fCreateCDATANodes) { setCharacterData (false); } } } // startCDATA() /** * The end of a CDATA section. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA (Augmentations augs) throws XNIException { fInCDATASection = false; if (!fDeferNodeExpansion) { if (fFilterReject) { return; } if (fCurrentCDATASection !=null) { if (fDOMFilter !=null && !fInEntityRef && (fDOMFilter.getWhatToShow () & NodeFilter.SHOW_CDATA_SECTION)!= 0) { short code = fDOMFilter.acceptNode (fCurrentCDATASection); switch (code) { case LSParserFilter.FILTER_INTERRUPT:{ throw ABORT; } case LSParserFilter.FILTER_REJECT:{ // fall through to SKIP since CDATA section has no children. } case LSParserFilter.FILTER_SKIP: { Node parent = fCurrentNode.getParentNode (); parent.removeChild (fCurrentCDATASection); fCurrentNode = parent; return; } default: { // accept node } } } fCurrentNode = fCurrentNode.getParentNode (); fCurrentCDATASection = null; } } else { if (fCurrentCDATASectionIndex !=-1) { fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode (fCurrentNodeIndex, false); fCurrentCDATASectionIndex = -1; } } } // endCDATA() /** * The end of the document. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument (Augmentations augs) throws XNIException { if (!fDeferNodeExpansion) { // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class // set the actual encoding and set DOM error checking back on if (fDocumentImpl != null) { if (fLocator != null) { fDocumentImpl.setInputEncoding (fLocator.getEncoding()); } fDocumentImpl.setStrictErrorChecking (true); } fCurrentNode = null; } else { // set the actual encoding if (fLocator != null) { fDeferredDocumentImpl.setInputEncoding (fLocator.getEncoding()); } fCurrentNodeIndex = -1; } } // endDocument() /** * This method notifies the end of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param augs Additional information that may include infoset augmentations * * @exception XNIException * Thrown by handler to signal an error. */ public void endGeneralEntity (String name, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>endGeneralEntity: ("+name+")"); } if (!fDeferNodeExpansion) { if (fFilterReject) { return; } setCharacterData (true); if (fDocumentType != null) { // get current entity declaration NamedNodeMap entities = fDocumentType.getEntities (); fCurrentEntityDecl = (EntityImpl) entities.getNamedItem (name); if (fCurrentEntityDecl != null) { if (fCurrentEntityDecl != null && fCurrentEntityDecl.getFirstChild () == null) { fCurrentEntityDecl.setReadOnly (false, true); Node child = fCurrentNode.getFirstChild (); while (child != null) { Node copy = child.cloneNode (true); fCurrentEntityDecl.appendChild (copy); child = child.getNextSibling (); } fCurrentEntityDecl.setReadOnly (true, true); //entities.setNamedItem(fCurrentEntityDecl); } fCurrentEntityDecl = null; } } fInEntityRef = false; boolean removeEntityRef = false; if (fCreateEntityRefNodes) { if (fDocumentImpl != null) { // Make entity ref node read only ((NodeImpl)fCurrentNode).setReadOnly (true, true); } if (fDOMFilter !=null && (fDOMFilter.getWhatToShow () & NodeFilter.SHOW_ENTITY_REFERENCE)!= 0) { short code = fDOMFilter.acceptNode (fCurrentNode); switch (code) { case LSParserFilter.FILTER_INTERRUPT:{ throw ABORT; } case LSParserFilter.FILTER_REJECT:{ Node parent = fCurrentNode.getParentNode (); parent.removeChild (fCurrentNode); fCurrentNode = parent; return; } case LSParserFilter.FILTER_SKIP: { // make sure we don't loose chars if next event is characters() fFirstChunk = true; removeEntityRef = true; break; } default: { fCurrentNode = fCurrentNode.getParentNode (); } } } else { fCurrentNode = fCurrentNode.getParentNode (); } } if (!fCreateEntityRefNodes || removeEntityRef) { // move entity reference children to the list of // siblings of its parent and remove entity reference NodeList children = fCurrentNode.getChildNodes (); Node parent = fCurrentNode.getParentNode (); int length = children.getLength (); if (length > 0) { // get previous sibling of the entity reference Node node = fCurrentNode.getPreviousSibling (); // normalize text nodes Node child = children.item (0); if (node != null && node.getNodeType () == Node.TEXT_NODE && child.getNodeType () == Node.TEXT_NODE) { ((Text)node).appendData (child.getNodeValue ()); fCurrentNode.removeChild (child); } else { node = parent.insertBefore (child, fCurrentNode); handleBaseURI (node); } for (int i=1;i <length;i++) { node = parent.insertBefore (children.item (0), fCurrentNode); handleBaseURI (node); } } // length > 0 parent.removeChild (fCurrentNode); fCurrentNode = parent; } } else { if (fDocumentTypeIndex != -1) { // find corresponding Entity decl int node = fDeferredDocumentImpl.getLastChild (fDocumentTypeIndex, false); while (node != -1) { short nodeType = fDeferredDocumentImpl.getNodeType (node, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName (node, false); if (nodeName.equals (name)) { fDeferredEntityDecl = node; break; } } node = fDeferredDocumentImpl.getRealPrevSibling (node, false); } } if (fDeferredEntityDecl != -1 && fDeferredDocumentImpl.getLastChild (fDeferredEntityDecl, false) == -1) { // entity definition exists and it does not have any children int prevIndex = -1; int childIndex = fDeferredDocumentImpl.getLastChild (fCurrentNodeIndex, false); while (childIndex != -1) { int cloneIndex = fDeferredDocumentImpl.cloneNode (childIndex, true); fDeferredDocumentImpl.insertBefore (fDeferredEntityDecl, cloneIndex, prevIndex); prevIndex = cloneIndex; childIndex = fDeferredDocumentImpl.getRealPrevSibling (childIndex, false); } } if (fCreateEntityRefNodes) { fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode (fCurrentNodeIndex, false); } else { //!fCreateEntityRefNodes // move children of entity ref before the entity ref. // remove entity ref. // holds a child of entity ref int childIndex = fDeferredDocumentImpl.getLastChild (fCurrentNodeIndex, false); int parentIndex = fDeferredDocumentImpl.getParentNode (fCurrentNodeIndex, false); int prevIndex = fCurrentNodeIndex; int lastChild = childIndex; int sibling = -1; while (childIndex != -1) { handleBaseURI (childIndex); sibling = fDeferredDocumentImpl.getRealPrevSibling (childIndex, false); fDeferredDocumentImpl.insertBefore (parentIndex, childIndex, prevIndex); prevIndex = childIndex; childIndex = sibling; } if(lastChild != -1) fDeferredDocumentImpl.setAsLastChild (parentIndex, lastChild); else{ sibling = fDeferredDocumentImpl.getRealPrevSibling (prevIndex, false); fDeferredDocumentImpl.setAsLastChild (parentIndex, sibling); } fCurrentNodeIndex = parentIndex; } fDeferredEntityDecl = -1; } } // endGeneralEntity(String, Augmentations) /** * Record baseURI information for the Element (by adding xml:base attribute) * or for the ProcessingInstruction (by setting a baseURI field) * Non deferred DOM. * * @param node */ protected final void handleBaseURI (Node node){ if (fDocumentImpl != null) { // REVISIT: remove dependency on our implementation when // DOM L3 becomes REC String baseURI = null; short nodeType = node.getNodeType (); if (nodeType == Node.ELEMENT_NODE) { // if an element already has xml:base attribute // do nothing if (fNamespaceAware) { if (((Element)node).getAttributeNodeNS ("http://www.w3.org/XML/1998/namespace","base")!=null) { return; } } else if (((Element)node).getAttributeNode ("xml:base") != null) { return; } // retrive the baseURI from the entity reference baseURI = ((EntityReferenceImpl)fCurrentNode).getBaseURI (); if (baseURI !=null && !baseURI.equals (fDocumentImpl.getDocumentURI ())) { if (fNamespaceAware) { ((Element)node).setAttributeNS ("http://www.w3.org/XML/1998/namespace","base", baseURI); } else { ((Element)node).setAttribute ("xml:base", baseURI); } } } else if (nodeType == Node.PROCESSING_INSTRUCTION_NODE) { baseURI = ((EntityReferenceImpl)fCurrentNode).getBaseURI (); if (baseURI !=null && fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl (); error.fType = "pi-base-uri-not-preserved"; error.fRelatedData = baseURI; error.fSeverity = DOMError.SEVERITY_WARNING; fErrorHandler.getErrorHandler ().handleError (error); } } } } /** * * Record baseURI information for the Element (by adding xml:base attribute) * or for the ProcessingInstruction (by setting a baseURI field) * Deferred DOM. * * @param node */ protected final void handleBaseURI (int node){ short nodeType = fDeferredDocumentImpl.getNodeType (node, false); if (nodeType == Node.ELEMENT_NODE) { String baseURI = fDeferredDocumentImpl.getNodeValueString (fCurrentNodeIndex, false); if (baseURI == null) { baseURI = fDeferredDocumentImpl.getDeferredEntityBaseURI (fDeferredEntityDecl); } if (baseURI !=null && !baseURI.equals (fDeferredDocumentImpl.getDocumentURI ())) { fDeferredDocumentImpl.setDeferredAttribute (node, "xml:base", "http://www.w3.org/XML/1998/namespace", baseURI, true); } } else if (nodeType == Node.PROCESSING_INSTRUCTION_NODE) { // retrieve baseURI from the entity reference String baseURI = fDeferredDocumentImpl.getNodeValueString (fCurrentNodeIndex, false); if (baseURI == null) { // try baseURI of the entity declaration baseURI = fDeferredDocumentImpl.getDeferredEntityBaseURI (fDeferredEntityDecl); } if (baseURI != null && fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl (); error.fType = "pi-base-uri-not-preserved"; error.fRelatedData = baseURI; error.fSeverity = DOMError.SEVERITY_WARNING; fErrorHandler.getErrorHandler ().handleError (error); } } } // // XMLDTDHandler methods // /** * The start of the DTD. * * @param locator The document locator, or null if the document * location cannot be reported during the parsing of * the document DTD. However, it is <em>strongly</em> * recommended that a locator be supplied that can * at least report the base system identifier of the * DTD. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void startDTD (XMLLocator locator, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>startDTD"); if (DEBUG_BASEURI) { System.out.println (" expandedSystemId: "+locator.getExpandedSystemId ()); System.out.println (" baseURI:"+ locator.getBaseSystemId ()); } } fInDTD = true; if (locator != null) { fBaseURIStack.push (locator.getBaseSystemId ()); } if (fDeferNodeExpansion || fDocumentImpl != null) { fInternalSubset = new StringBuffer (1024); } } // startDTD(XMLLocator) /** * The end of the DTD. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void endDTD (Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>endDTD()"); } fInDTD = false; if (!fBaseURIStack.isEmpty ()) { fBaseURIStack.pop (); } String internalSubset = fInternalSubset != null && fInternalSubset.length () > 0 ? fInternalSubset.toString () : null; if (fDeferNodeExpansion) { if (internalSubset != null) { fDeferredDocumentImpl.setInternalSubset (fDocumentTypeIndex, internalSubset); } } else if (fDocumentImpl != null) { if (internalSubset != null) { ((DocumentTypeImpl)fDocumentType).setInternalSubset (internalSubset); } } } // endDTD() /** * The start of a conditional section. * * @param type The type of the conditional section. This value will * either be CONDITIONAL_INCLUDE or CONDITIONAL_IGNORE. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. * * @see #CONDITIONAL_INCLUDE * @see #CONDITIONAL_IGNORE */ public void startConditional (short type, Augmentations augs) throws XNIException { } // startConditional(short) /** * The end of a conditional section. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void endConditional (Augmentations augs) throws XNIException { } // endConditional() /** * The start of the DTD external subset. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void startExternalSubset (XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>startExternalSubset"); if (DEBUG_BASEURI) { System.out.println (" expandedSystemId: "+identifier.getExpandedSystemId ()); System.out.println (" baseURI:"+ identifier.getBaseSystemId ()); } } fBaseURIStack.push (identifier.getBaseSystemId ()); fInDTDExternalSubset = true; } // startExternalSubset(Augmentations) /** * The end of the DTD external subset. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void endExternalSubset (Augmentations augs) throws XNIException { fInDTDExternalSubset = false; fBaseURIStack.pop (); } // endExternalSubset(Augmentations) /** * An internal entity declaration. * * @param name The name of the entity. Parameter entity names start with * '%', whereas the name of a general entity is just the * entity name. * @param text The value of the entity. * @param nonNormalizedText The non-normalized value of the entity. This * value contains the same sequence of characters that was in * the internal entity declaration, without any entity * references expanded. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void internalEntityDecl (String name, XMLString text, XMLString nonNormalizedText, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>internalEntityDecl: "+name); if (DEBUG_BASEURI) { System.out.println (" baseURI:"+ (String)fBaseURIStack.peek ()); } } // internal subset string if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<!ENTITY "); if (name.startsWith ("%")) { fInternalSubset.append ("% "); fInternalSubset.append (name.substring (1)); } else { fInternalSubset.append (name); } fInternalSubset.append (' '); String value = nonNormalizedText.toString (); boolean singleQuote = value.indexOf ('\'') == -1; fInternalSubset.append (singleQuote ? '\'' : '"'); fInternalSubset.append (value); fInternalSubset.append (singleQuote ? '\'' : '"'); fInternalSubset.append (">\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node // don't add parameter entities! if(name.startsWith ("%")) return; if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities (); EntityImpl entity = (EntityImpl)entities.getNamedItem (name); if (entity == null) { entity = (EntityImpl)fDocumentImpl.createEntity (name); entity.setBaseURI ((String)fBaseURIStack.peek ()); entities.setNamedItem (entity); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int node = fDeferredDocumentImpl.getLastChild (fDocumentTypeIndex, false); while (node != -1) { short nodeType = fDeferredDocumentImpl.getNodeType (node, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName (node, false); if (nodeName.equals (name)) { found = true; break; } } node = fDeferredDocumentImpl.getRealPrevSibling (node, false); } if (!found) { int entityIndex = fDeferredDocumentImpl.createDeferredEntity (name, null, null, null, (String)fBaseURIStack.peek ()); fDeferredDocumentImpl.appendChild (fDocumentTypeIndex, entityIndex); } } } // internalEntityDecl(String,XMLString,XMLString) /** * An external entity declaration. * * @param name The name of the entity. Parameter entity names start * with '%', whereas the name of a general entity is just * the entity name. * @param identifier An object containing all location information * pertinent to this notation. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void externalEntityDecl (String name, XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>externalEntityDecl: "+name); if (DEBUG_BASEURI) { System.out.println (" expandedSystemId:"+ identifier.getExpandedSystemId ()); System.out.println (" baseURI:"+ identifier.getBaseSystemId ()); } } // internal subset string String publicId = identifier.getPublicId (); String literalSystemId = identifier.getLiteralSystemId (); if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<!ENTITY "); if (name.startsWith ("%")) { fInternalSubset.append ("% "); fInternalSubset.append (name.substring (1)); } else { fInternalSubset.append (name); } fInternalSubset.append (' '); if (publicId != null) { fInternalSubset.append ("PUBLIC '"); fInternalSubset.append (publicId); fInternalSubset.append ("' '"); } else { fInternalSubset.append ("SYSTEM '"); } fInternalSubset.append (literalSystemId); fInternalSubset.append ("'>\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node // don't add parameter entities! if(name.startsWith ("%")) return; if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities (); EntityImpl entity = (EntityImpl)entities.getNamedItem (name); if (entity == null) { entity = (EntityImpl)fDocumentImpl.createEntity (name); entity.setPublicId (publicId); entity.setSystemId (literalSystemId); entity.setBaseURI (identifier.getBaseSystemId ()); entities.setNamedItem (entity); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int nodeIndex = fDeferredDocumentImpl.getLastChild (fDocumentTypeIndex, false); while (nodeIndex != -1) { short nodeType = fDeferredDocumentImpl.getNodeType (nodeIndex, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName (nodeIndex, false); if (nodeName.equals (name)) { found = true; break; } } nodeIndex = fDeferredDocumentImpl.getRealPrevSibling (nodeIndex, false); } if (!found) { int entityIndex = fDeferredDocumentImpl.createDeferredEntity ( name, publicId, literalSystemId, null, identifier.getBaseSystemId ()); fDeferredDocumentImpl.appendChild (fDocumentTypeIndex, entityIndex); } } } // externalEntityDecl(String,XMLResourceIdentifier, Augmentations) /** * This method notifies of the start of a parameter entity. The parameter * entity name start with a '%' character. * * @param name The name of the parameter entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal parameter entities). * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void startParameterEntity (String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>startParameterEntity: "+name); if (DEBUG_BASEURI) { System.out.println (" expandedSystemId: "+identifier.getExpandedSystemId ()); System.out.println (" baseURI:"+ identifier.getBaseSystemId ()); } } if (augs != null && fInternalSubset != null && !fInDTDExternalSubset && Boolean.TRUE.equals(augs.getItem(Constants.ENTITY_SKIPPED))) { fInternalSubset.append(name).append(";\n"); } fBaseURIStack.push (identifier.getExpandedSystemId ()); } /** * This method notifies the end of a parameter entity. Parameter entity * names begin with a '%' character. * * @param name The name of the parameter entity. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void endParameterEntity (String name, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>endParameterEntity: "+name); } fBaseURIStack.pop (); } /** * An unparsed entity declaration. * * @param name The name of the entity. * @param identifier An object containing all location information * pertinent to this entity. * @param notation The name of the notation. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void unparsedEntityDecl (String name, XMLResourceIdentifier identifier, String notation, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println ("==>unparsedEntityDecl: "+name); if (DEBUG_BASEURI) { System.out.println (" expandedSystemId:"+ identifier.getExpandedSystemId ()); System.out.println (" baseURI:"+ identifier.getBaseSystemId ()); } } // internal subset string String publicId = identifier.getPublicId (); String literalSystemId = identifier.getLiteralSystemId (); if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<!ENTITY "); fInternalSubset.append (name); fInternalSubset.append (' '); if (publicId != null) { fInternalSubset.append ("PUBLIC '"); fInternalSubset.append (publicId); if (literalSystemId != null) { fInternalSubset.append ("' '"); fInternalSubset.append (literalSystemId); } } else { fInternalSubset.append ("SYSTEM '"); fInternalSubset.append (literalSystemId); } fInternalSubset.append ("' NDATA "); fInternalSubset.append (notation); fInternalSubset.append (">\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities (); EntityImpl entity = (EntityImpl)entities.getNamedItem (name); if (entity == null) { entity = (EntityImpl)fDocumentImpl.createEntity (name); entity.setPublicId (publicId); entity.setSystemId (literalSystemId); entity.setNotationName (notation); entity.setBaseURI (identifier.getBaseSystemId ()); entities.setNamedItem (entity); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int nodeIndex = fDeferredDocumentImpl.getLastChild (fDocumentTypeIndex, false); while (nodeIndex != -1) { short nodeType = fDeferredDocumentImpl.getNodeType (nodeIndex, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName (nodeIndex, false); if (nodeName.equals (name)) { found = true; break; } } nodeIndex = fDeferredDocumentImpl.getRealPrevSibling (nodeIndex, false); } if (!found) { int entityIndex = fDeferredDocumentImpl.createDeferredEntity ( name, publicId, literalSystemId, notation, identifier.getBaseSystemId ()); fDeferredDocumentImpl.appendChild (fDocumentTypeIndex, entityIndex); } } } // unparsedEntityDecl(String,XMLResourceIdentifier, String, Augmentations) /** * A notation declaration * * @param name The name of the notation. * @param identifier An object containing all location information * pertinent to this notation. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void notationDecl (String name, XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { // internal subset string String publicId = identifier.getPublicId (); String literalSystemId = identifier.getLiteralSystemId (); if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<!NOTATION "); fInternalSubset.append (name); if (publicId != null) { fInternalSubset.append (" PUBLIC '"); fInternalSubset.append (publicId); if (literalSystemId != null) { fInternalSubset.append ("' '"); fInternalSubset.append (literalSystemId); } } else { fInternalSubset.append (" SYSTEM '"); fInternalSubset.append (literalSystemId); } fInternalSubset.append ("'>\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node if (fDocumentImpl !=null && fDocumentType != null) { NamedNodeMap notations = fDocumentType.getNotations (); if (notations.getNamedItem (name) == null) { NotationImpl notation = (NotationImpl)fDocumentImpl.createNotation (name); notation.setPublicId (publicId); notation.setSystemId (literalSystemId); notation.setBaseURI (identifier.getBaseSystemId ()); notations.setNamedItem (notation); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int nodeIndex = fDeferredDocumentImpl.getLastChild (fDocumentTypeIndex, false); while (nodeIndex != -1) { short nodeType = fDeferredDocumentImpl.getNodeType (nodeIndex, false); if (nodeType == Node.NOTATION_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName (nodeIndex, false); if (nodeName.equals (name)) { found = true; break; } } nodeIndex = fDeferredDocumentImpl.getPrevSibling (nodeIndex, false); } if (!found) { int notationIndex = fDeferredDocumentImpl.createDeferredNotation ( name, publicId, literalSystemId, identifier.getBaseSystemId ()); fDeferredDocumentImpl.appendChild (fDocumentTypeIndex, notationIndex); } } } // notationDecl(String,XMLResourceIdentifier, Augmentations) /** * Characters within an IGNORE conditional section. * * @param text The ignored text. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void ignoredCharacters (XMLString text, Augmentations augs) throws XNIException { } // ignoredCharacters(XMLString, Augmentations) /** * An element declaration. * * @param name The name of the element. * @param contentModel The element content model. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void elementDecl (String name, String contentModel, Augmentations augs) throws XNIException { // internal subset string if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<!ELEMENT "); fInternalSubset.append (name); fInternalSubset.append (' '); fInternalSubset.append (contentModel); fInternalSubset.append (">\n"); } } // elementDecl(String,String) /** * An attribute declaration. * * @param elementName The name of the element that this attribute * is associated with. * @param attributeName The name of the attribute. * @param type The attribute type. This value will be one of * the following: "CDATA", "ENTITY", "ENTITIES", * "ENUMERATION", "ID", "IDREF", "IDREFS", * "NMTOKEN", "NMTOKENS", or "NOTATION". * @param enumeration If the type has the value "ENUMERATION" or * "NOTATION", this array holds the allowed attribute * values; otherwise, this array is null. * @param defaultType The attribute default type. This value will be * one of the following: "#FIXED", "#IMPLIED", * "#REQUIRED", or null. * @param defaultValue The attribute default value, or null if no * default value is specified. * @param nonNormalizedDefaultValue The attribute default value with no normalization * performed, or null if no default value is specified. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void attributeDecl (String elementName, String attributeName, String type, String[] enumeration, String defaultType, XMLString defaultValue, XMLString nonNormalizedDefaultValue, Augmentations augs) throws XNIException { // internal subset string if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append ("<!ATTLIST "); fInternalSubset.append (elementName); fInternalSubset.append (' '); fInternalSubset.append (attributeName); fInternalSubset.append (' '); if (type.equals ("ENUMERATION")) { fInternalSubset.append ('('); for (int i = 0; i < enumeration.length; i++) { if (i > 0) { fInternalSubset.append ('|'); } fInternalSubset.append (enumeration[i]); } fInternalSubset.append (')'); } else { fInternalSubset.append (type); } if (defaultType != null) { fInternalSubset.append (' '); fInternalSubset.append (defaultType); } if (defaultValue != null) { fInternalSubset.append (" '"); for (int i = 0; i < defaultValue.length; i++) { char c = defaultValue.ch[defaultValue.offset + i]; if (c == '\'') { fInternalSubset.append ("&apos;"); } else { fInternalSubset.append (c); } } fInternalSubset.append ('\''); } fInternalSubset.append (">\n"); } // REVISIT: This code applies to the support of domx/grammar-access // feature in Xerces 1 // deferred expansion if (fDeferredDocumentImpl != null) { // get the default value if (defaultValue != null) { // get element definition int elementDefIndex = fDeferredDocumentImpl.lookupElementDefinition (elementName); // create element definition if not already there if (elementDefIndex == -1) { elementDefIndex = fDeferredDocumentImpl.createDeferredElementDefinition (elementName); fDeferredDocumentImpl.appendChild (fDocumentTypeIndex, elementDefIndex); } // add default attribute int attrIndex = fDeferredDocumentImpl.createDeferredAttribute ( attributeName, defaultValue.toString (), false); if ("ID".equals (type)) { fDeferredDocumentImpl.setIdAttribute (attrIndex); } // REVISIT: set ID type correctly fDeferredDocumentImpl.appendChild (elementDefIndex, attrIndex); } } // if deferred // full expansion else if (fDocumentImpl != null) { // get the default value if (defaultValue != null) { // get element definition node NamedNodeMap elements = ((DocumentTypeImpl)fDocumentType).getElements (); ElementDefinitionImpl elementDef = (ElementDefinitionImpl)elements.getNamedItem (elementName); if (elementDef == null) { elementDef = fDocumentImpl.createElementDefinition (elementName); ((DocumentTypeImpl)fDocumentType).getElements ().setNamedItem (elementDef); } // REVISIT: Check for uniqueness of element name? -Ac // create attribute and set properties boolean nsEnabled = fNamespaceAware; AttrImpl attr; if (nsEnabled) { String namespaceURI = null; // DOM Level 2 wants all namespace declaration attributes // to be bound to "http://www.w3.org/2000/xmlns/" // So as long as the XML parser doesn't do it, it needs to // done here. if (attributeName.startsWith ("xmlns:") || attributeName.equals ("xmlns")) { namespaceURI = NamespaceContext.XMLNS_URI; } attr = (AttrImpl)fDocumentImpl.createAttributeNS (namespaceURI, attributeName); } else { attr = (AttrImpl)fDocumentImpl.createAttribute (attributeName); } attr.setValue (defaultValue.toString ()); attr.setSpecified (false); attr.setIdAttribute ("ID".equals (type)); // add default attribute to element definition if (nsEnabled){ elementDef.getAttributes ().setNamedItemNS (attr); } else { elementDef.getAttributes ().setNamedItem (attr); } } } // if NOT defer-node-expansion } // attributeDecl(String,String,String,String[],String,XMLString, XMLString, Augmentations) /** * The start of an attribute list. * * @param elementName The name of the element that this attribute * list is associated with. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void startAttlist (String elementName, Augmentations augs) throws XNIException { } // startAttlist(String) /** * The end of an attribute list. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void endAttlist (Augmentations augs) throws XNIException { } // endAttlist() // method to create an element node. // subclasses can override this method to create element nodes in other ways. protected Element createElementNode (QName element) { Element el = null; if (fNamespaceAware) { // if we are using xerces DOM implementation, call our // own constructor to reuse the strings we have here. if (fDocumentImpl != null) { el = fDocumentImpl.createElementNS (element.uri, element.rawname, element.localpart); } else { el = fDocument.createElementNS (element.uri, element.rawname); } } else { el = fDocument.createElement (element.rawname); } return el; } // method to create an attribute node. // subclasses can override this method to create attribute nodes in other ways. protected Attr createAttrNode (QName attrQName) { Attr attr = null; if (fNamespaceAware) { if (fDocumentImpl != null) { // if we are using xerces DOM implementation, call our // own constructor to reuse the strings we have here. attr = fDocumentImpl.createAttributeNS (attrQName.uri, attrQName.rawname, attrQName.localpart); } else { attr = fDocument.createAttributeNS (attrQName.uri, attrQName.rawname); } } else { attr = fDocument.createAttribute (attrQName.rawname); } return attr; } /* * When the first characters() call is received, the data is stored in * a new Text node. If right after the first characters() we receive another chunk of data, * the data from the Text node, following the new characters are appended * to the fStringBuffer and the text node data is set to empty. * * This function is called when the state is changed and the * data must be appended to the current node. * * Note: if DOMFilter is set, you must make sure that if Node is skipped, * or removed fFistChunk must be set to true, otherwise some data can be lost. * */ protected void setCharacterData (boolean sawChars){ // handle character data fFirstChunk = sawChars; // if we have data in the buffer we must have created // a text node already. Node child = fCurrentNode.getLastChild (); if (child != null) { if (fStringBuffer.length () > 0) { // REVISIT: should this check be performed? if (child.getNodeType () == Node.TEXT_NODE) { if (fDocumentImpl != null) { ((TextImpl)child).replaceData (fStringBuffer.toString ()); } else { ((Text)child).setData (fStringBuffer.toString ()); } } // reset string buffer fStringBuffer.setLength (0); } if (fDOMFilter !=null && !fInEntityRef) { if ( (child.getNodeType () == Node.TEXT_NODE ) && ((fDOMFilter.getWhatToShow () & NodeFilter.SHOW_TEXT)!= 0) ) { short code = fDOMFilter.acceptNode (child); switch (code) { case LSParserFilter.FILTER_INTERRUPT:{ throw ABORT; } case LSParserFilter.FILTER_REJECT:{ // fall through to SKIP since Comment has no children. } case LSParserFilter.FILTER_SKIP: { fCurrentNode.removeChild (child); return; } default: { // accept node -- do nothing } } } } // end-if fDOMFilter !=null } // end-if child !=null } /** * @see org.w3c.dom.ls.LSParser#abort() */ public void abort () { throw ABORT; } } // class AbstractDOMParser diff --git a/src/org/apache/xerces/parsers/DOMParserImpl.java b/src/org/apache/xerces/parsers/DOMParserImpl.java index c4c8900da..84a9d2893 100644 --- a/src/org/apache/xerces/parsers/DOMParserImpl.java +++ b/src/org/apache/xerces/parsers/DOMParserImpl.java @@ -1,1356 +1,1356 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.parsers; import java.io.StringReader; import java.util.ArrayList; import java.util.Locale; import java.util.Stack; import java.util.StringTokenizer; import org.apache.xerces.dom.DOMErrorImpl; import org.apache.xerces.dom.DOMMessageFormatter; import org.apache.xerces.dom.DOMStringListImpl; import org.apache.xerces.impl.Constants; import org.apache.xerces.util.DOMEntityResolverWrapper; import org.apache.xerces.util.DOMErrorHandlerWrapper; import org.apache.xerces.util.DOMUtil; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDTDContentModelHandler; import org.apache.xerces.xni.XMLDTDHandler; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDTDContentModelSource; import org.apache.xerces.xni.parser.XMLDTDSource; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.parser.XMLParseException; import org.apache.xerces.xni.parser.XMLParserConfiguration; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMError; import org.w3c.dom.DOMErrorHandler; import org.w3c.dom.DOMException; import org.w3c.dom.DOMStringList; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.ls.LSException; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSParser; import org.w3c.dom.ls.LSParserFilter; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.SAXException; /** * This is Xerces DOM Builder class. It uses the abstract DOM * parser with a document scanner, a dtd scanner, and a validator, as * well as a grammar pool. * * @author Pavani Mukthipudi, Sun Microsystems Inc. * @author Elena Litani, IBM * @author Rahul Srivastava, Sun Microsystems Inc. * @version $Id$ */ public class DOMParserImpl extends AbstractDOMParser implements LSParser, DOMConfiguration { // SAX & Xerces feature ids /** Feature identifier: namespaces. */ protected static final String NAMESPACES = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE; /** Feature id: validation. */ protected static final String VALIDATION_FEATURE = Constants.SAX_FEATURE_PREFIX+Constants.VALIDATION_FEATURE; /** XML Schema validation */ protected static final String XMLSCHEMA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** XML Schema full checking */ protected static final String XMLSCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; /** Dynamic validation */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: disallow docType Decls. */ protected static final String DISALLOW_DOCTYPE_DECL_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.DISALLOW_DOCTYPE_DECL_FEATURE; /** Feature identifier: honour all schemaLocations */ protected static final String HONOUR_ALL_SCHEMALOCATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.HONOUR_ALL_SCHEMALOCATIONS_FEATURE; // internal properties protected static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; protected static final String PSVI_AUGMENT = Constants.XERCES_FEATURE_PREFIX +Constants.SCHEMA_AUGMENT_PSVI; // // Data // /** Include namespace declaration attributes in the document. **/ protected boolean fNamespaceDeclarations = true; // REVISIT: this value should be null by default and should be set during creation of // LSParser protected String fSchemaType = null; protected boolean fBusy = false; private boolean abortNow = false; private Thread currentThread; protected final static boolean DEBUG = false; private String fSchemaLocation = null; private DOMStringList fRecognizedParameters; private final AbortHandler abortHandler = new AbortHandler(); // // Constructors // /** * Constructs a DOM Builder using the standard parser configuration. */ public DOMParserImpl (String configuration, String schemaType) { this ( (XMLParserConfiguration) ObjectFactory.createObject ( "org.apache.xerces.xni.parser.XMLParserConfiguration", configuration)); if (schemaType != null) { if (schemaType.equals (Constants.NS_DTD)) { //Schema validation is false by default and hence there is no //need to set it to false here. Also, schema validation is //not a recognized feature for DTDConfiguration's and so //setting this feature here would result in a Configuration //Exception. fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, Constants.NS_DTD); fSchemaType = Constants.NS_DTD; } else if (schemaType.equals (Constants.NS_XMLSCHEMA)) { // XML Schem validation fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, Constants.NS_XMLSCHEMA); } } } /** * Constructs a DOM Builder using the specified parser configuration. */ public DOMParserImpl (XMLParserConfiguration config) { super (config); // add recognized features final String[] domRecognizedFeatures = { Constants.DOM_CANONICAL_FORM, Constants.DOM_CDATA_SECTIONS, Constants.DOM_CHARSET_OVERRIDES_XML_ENCODING, Constants.DOM_INFOSET, Constants.DOM_NAMESPACE_DECLARATIONS, Constants.DOM_SPLIT_CDATA, Constants.DOM_SUPPORTED_MEDIATYPES_ONLY, Constants.DOM_CERTIFIED, Constants.DOM_WELLFORMED, Constants.DOM_IGNORE_UNKNOWN_CHARACTER_DENORMALIZATIONS, }; fConfiguration.addRecognizedFeatures (domRecognizedFeatures); // turn off deferred DOM fConfiguration.setFeature (DEFER_NODE_EXPANSION, false); // Set values so that the value of the // infoset parameter is true (its default value). // // true: namespace-declarations, well-formed, // element-content-whitespace, comments, namespaces // // false: validate-if-schema, entities, // datatype-normalization, cdata-sections fConfiguration.setFeature(Constants.DOM_NAMESPACE_DECLARATIONS, true); fConfiguration.setFeature(Constants.DOM_WELLFORMED, true); fConfiguration.setFeature(INCLUDE_COMMENTS_FEATURE, true); fConfiguration.setFeature(INCLUDE_IGNORABLE_WHITESPACE, true); fConfiguration.setFeature(NAMESPACES, true); fConfiguration.setFeature(DYNAMIC_VALIDATION, false); fConfiguration.setFeature(CREATE_ENTITY_REF_NODES, false); fConfiguration.setFeature(CREATE_CDATA_NODES_FEATURE, false); // set other default values fConfiguration.setFeature (Constants.DOM_CANONICAL_FORM, false); fConfiguration.setFeature (Constants.DOM_CHARSET_OVERRIDES_XML_ENCODING, true); fConfiguration.setFeature (Constants.DOM_SPLIT_CDATA, true); fConfiguration.setFeature (Constants.DOM_SUPPORTED_MEDIATYPES_ONLY, false); fConfiguration.setFeature (Constants.DOM_IGNORE_UNKNOWN_CHARACTER_DENORMALIZATIONS, true); // REVISIT: by default Xerces assumes that input is certified. // default is different from the one specified in the DOM spec fConfiguration.setFeature (Constants.DOM_CERTIFIED, true); // Xerces datatype-normalization feature is on by default // This is a recognized feature only for XML Schemas. If the // configuration doesn't support this feature, ignore it. try { fConfiguration.setFeature ( NORMALIZE_DATA, false ); } catch (XMLConfigurationException exc) {} } // <init>(XMLParserConfiguration) /** * Constructs a DOM Builder using the specified symbol table. */ public DOMParserImpl (SymbolTable symbolTable) { this ( (XMLParserConfiguration) ObjectFactory.createObject ( "org.apache.xerces.xni.parser.XMLParserConfiguration", "org.apache.xerces.parsers.XIncludeAwareParserConfiguration")); fConfiguration.setProperty ( Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY, symbolTable); } // <init>(SymbolTable) /** * Constructs a DOM Builder using the specified symbol table and * grammar pool. */ public DOMParserImpl (SymbolTable symbolTable, XMLGrammarPool grammarPool) { this ( (XMLParserConfiguration) ObjectFactory.createObject ( "org.apache.xerces.xni.parser.XMLParserConfiguration", "org.apache.xerces.parsers.XIncludeAwareParserConfiguration")); fConfiguration.setProperty ( Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY, symbolTable); fConfiguration.setProperty ( Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY, grammarPool); } /** * Resets the parser state. * * @throws SAXException Thrown on initialization error. */ public void reset () { super.reset(); // get state of namespace-declarations parameter. fNamespaceDeclarations = fConfiguration.getFeature(Constants.DOM_NAMESPACE_DECLARATIONS); // DOM Filter if (fSkippedElemStack != null) { fSkippedElemStack.removeAllElements(); } - fRejectedElement.clear(); + fRejectedElementDepth = 0; fFilterReject = false; fSchemaType = null; } // reset() // // DOMParser methods // public DOMConfiguration getDomConfig (){ return this; } /** * When the application provides a filter, the parser will call out to * the filter at the completion of the construction of each * <code>Element</code> node. The filter implementation can choose to * remove the element from the document being constructed (unless the * element is the document element) or to terminate the parse early. If * the document is being validated when it's loaded the validation * happens before the filter is called. */ public LSParserFilter getFilter () { return fDOMFilter; } /** * When the application provides a filter, the parser will call out to * the filter at the completion of the construction of each * <code>Element</code> node. The filter implementation can choose to * remove the element from the document being constructed (unless the * element is the document element) or to terminate the parse early. If * the document is being validated when it's loaded the validation * happens before the filter is called. */ public void setFilter (LSParserFilter filter) { fDOMFilter = filter; if (fSkippedElemStack == null) { fSkippedElemStack = new Stack (); } } /** * Set parameters and properties */ public void setParameter (String name, Object value) throws DOMException { // set features if (value instanceof Boolean) { boolean state = ((Boolean)value).booleanValue(); try { if (name.equalsIgnoreCase (Constants.DOM_COMMENTS)) { fConfiguration.setFeature (INCLUDE_COMMENTS_FEATURE, state); } else if (name.equalsIgnoreCase (Constants.DOM_DATATYPE_NORMALIZATION)) { fConfiguration.setFeature (NORMALIZE_DATA, state); } else if (name.equalsIgnoreCase (Constants.DOM_ENTITIES)) { fConfiguration.setFeature (CREATE_ENTITY_REF_NODES, state); } else if (name.equalsIgnoreCase (Constants.DOM_DISALLOW_DOCTYPE)) { fConfiguration.setFeature (DISALLOW_DOCTYPE_DECL_FEATURE, state); } else if (name.equalsIgnoreCase (Constants.DOM_SUPPORTED_MEDIATYPES_ONLY) || name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS) || name.equalsIgnoreCase (Constants.DOM_CHECK_CHAR_NORMALIZATION) || name.equalsIgnoreCase (Constants.DOM_CANONICAL_FORM)) { if (state) { // true is not supported throw newFeatureNotSupportedError(name); } // setting those features to false is no-op } else if (name.equalsIgnoreCase (Constants.DOM_NAMESPACES)) { fConfiguration.setFeature (NAMESPACES, state); } else if (name.equalsIgnoreCase (Constants.DOM_INFOSET)) { // Setting false has no effect. if (state) { // true: namespaces, namespace-declarations, // comments, element-content-whitespace fConfiguration.setFeature(NAMESPACES, true); fConfiguration.setFeature(Constants.DOM_NAMESPACE_DECLARATIONS, true); fConfiguration.setFeature(INCLUDE_COMMENTS_FEATURE, true); fConfiguration.setFeature(INCLUDE_IGNORABLE_WHITESPACE, true); // false: validate-if-schema, entities, // datatype-normalization, cdata-sections fConfiguration.setFeature(DYNAMIC_VALIDATION, false); fConfiguration.setFeature(CREATE_ENTITY_REF_NODES, false); fConfiguration.setFeature(NORMALIZE_DATA, false); fConfiguration.setFeature(CREATE_CDATA_NODES_FEATURE, false); } } else if (name.equalsIgnoreCase(Constants.DOM_CDATA_SECTIONS)) { fConfiguration.setFeature(CREATE_CDATA_NODES_FEATURE, state); } else if (name.equalsIgnoreCase (Constants.DOM_NAMESPACE_DECLARATIONS)) { fConfiguration.setFeature(Constants.DOM_NAMESPACE_DECLARATIONS, state); } else if (name.equalsIgnoreCase (Constants.DOM_WELLFORMED) || name.equalsIgnoreCase (Constants.DOM_IGNORE_UNKNOWN_CHARACTER_DENORMALIZATIONS)) { if (!state) { // false is not supported throw newFeatureNotSupportedError(name); } // setting these features to true is no-op // REVISIT: implement "namespace-declaration" feature } else if (name.equalsIgnoreCase (Constants.DOM_VALIDATE)) { fConfiguration.setFeature (VALIDATION_FEATURE, state); if (fSchemaType != Constants.NS_DTD) { fConfiguration.setFeature (XMLSCHEMA, state); fConfiguration.setFeature (XMLSCHEMA_FULL_CHECKING, state); } if (state){ fConfiguration.setFeature (DYNAMIC_VALIDATION, false); } } else if (name.equalsIgnoreCase (Constants.DOM_VALIDATE_IF_SCHEMA)) { fConfiguration.setFeature (DYNAMIC_VALIDATION, state); // Note: validation and dynamic validation are mutually exclusive if (state){ fConfiguration.setFeature (VALIDATION_FEATURE, false); } } else if (name.equalsIgnoreCase (Constants.DOM_ELEMENT_CONTENT_WHITESPACE)) { fConfiguration.setFeature (INCLUDE_IGNORABLE_WHITESPACE, state); } else if (name.equalsIgnoreCase (Constants.DOM_PSVI)){ //XSModel - turn on PSVI augmentation fConfiguration.setFeature (PSVI_AUGMENT, true); fConfiguration.setProperty (DOCUMENT_CLASS_NAME, "org.apache.xerces.dom.PSVIDocumentImpl"); } else { // Constants.DOM_CHARSET_OVERRIDES_XML_ENCODING feature, // Constants.DOM_SPLIT_CDATA feature, // or any Xerces feature String normalizedName; // The honour-all-schemaLocations feature is // mixed case so requires special treatment. if (name.equalsIgnoreCase(HONOUR_ALL_SCHEMALOCATIONS)) { normalizedName = HONOUR_ALL_SCHEMALOCATIONS; } else { normalizedName = name.toLowerCase(Locale.ENGLISH); } fConfiguration.setFeature(normalizedName, state); } } catch (XMLConfigurationException e) { throw newFeatureNotFoundError(name); } } else { // set properties if (name.equalsIgnoreCase (Constants.DOM_ERROR_HANDLER)) { if (value instanceof DOMErrorHandler || value == null) { try { fErrorHandler = new DOMErrorHandlerWrapper ((DOMErrorHandler) value); fConfiguration.setProperty (ERROR_HANDLER, fErrorHandler); } catch (XMLConfigurationException e) {} } else { throw newTypeMismatchError(name); } } else if (name.equalsIgnoreCase (Constants.DOM_RESOURCE_RESOLVER)) { if (value instanceof LSResourceResolver || value == null) { try { fConfiguration.setProperty (ENTITY_RESOLVER, new DOMEntityResolverWrapper ((LSResourceResolver) value)); } catch (XMLConfigurationException e) {} } else { throw newTypeMismatchError(name); } } else if (name.equalsIgnoreCase (Constants.DOM_SCHEMA_LOCATION)) { if (value instanceof String || value == null) { try { if (value == null) { fSchemaLocation = null; fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE, null); } else { fSchemaLocation = (String)value; // map DOM schema-location to JAXP schemaSource property // tokenize location string StringTokenizer t = new StringTokenizer (fSchemaLocation, " \n\t\r"); if (t.hasMoreTokens()) { ArrayList locations = new ArrayList(); locations.add (t.nextToken()); while (t.hasMoreTokens()) { locations.add (t.nextToken()); } fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE, locations.toArray ()); } else { fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE, value); } } } catch (XMLConfigurationException e) {} } else { throw newTypeMismatchError(name); } } else if (name.equalsIgnoreCase (Constants.DOM_SCHEMA_TYPE)) { if (value instanceof String || value == null) { try { if (value == null) { // turn off schema features fConfiguration.setFeature (XMLSCHEMA, false); fConfiguration.setFeature (XMLSCHEMA_FULL_CHECKING, false); // map to JAXP schemaLanguage fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, null); fSchemaType = null; } else if (value.equals (Constants.NS_XMLSCHEMA)) { // turn on schema features fConfiguration.setFeature (XMLSCHEMA, true); fConfiguration.setFeature (XMLSCHEMA_FULL_CHECKING, true); // map to JAXP schemaLanguage fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, Constants.NS_XMLSCHEMA); fSchemaType = Constants.NS_XMLSCHEMA; } else if (value.equals (Constants.NS_DTD)) { // turn off schema features fConfiguration.setFeature (XMLSCHEMA, false); fConfiguration.setFeature (XMLSCHEMA_FULL_CHECKING, false); // map to JAXP schemaLanguage fConfiguration.setProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE, Constants.NS_DTD); fSchemaType = Constants.NS_DTD; } } catch (XMLConfigurationException e) {} } else { throw newTypeMismatchError(name); } } else if (name.equalsIgnoreCase (DOCUMENT_CLASS_NAME)) { fConfiguration.setProperty (DOCUMENT_CLASS_NAME, value); } else { // Try to set the property. String normalizedName = name.toLowerCase(Locale.ENGLISH); try { fConfiguration.setProperty(normalizedName, value); return; } catch (XMLConfigurationException e) {} // If this is a boolean parameter a type mismatch should be thrown. try { // The honour-all-schemaLocations feature is // mixed case so requires special treatment. if (name.equalsIgnoreCase(HONOUR_ALL_SCHEMALOCATIONS)) { normalizedName = HONOUR_ALL_SCHEMALOCATIONS; } fConfiguration.getFeature(normalizedName); throw newTypeMismatchError(name); } catch (XMLConfigurationException e) {} // Parameter is not recognized throw newFeatureNotFoundError(name); } } } /** * Look up the value of a feature or a property. */ public Object getParameter (String name) throws DOMException { if (name.equalsIgnoreCase (Constants.DOM_COMMENTS)) { return (fConfiguration.getFeature (INCLUDE_COMMENTS_FEATURE)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_DATATYPE_NORMALIZATION)) { return (fConfiguration.getFeature (NORMALIZE_DATA)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_ENTITIES)) { return (fConfiguration.getFeature (CREATE_ENTITY_REF_NODES)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_NAMESPACES)) { return (fConfiguration.getFeature (NAMESPACES)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_VALIDATE)) { return (fConfiguration.getFeature (VALIDATION_FEATURE)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_VALIDATE_IF_SCHEMA)) { return (fConfiguration.getFeature (DYNAMIC_VALIDATION)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_ELEMENT_CONTENT_WHITESPACE)) { return (fConfiguration.getFeature (INCLUDE_IGNORABLE_WHITESPACE)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_DISALLOW_DOCTYPE)) { return (fConfiguration.getFeature (DISALLOW_DOCTYPE_DECL_FEATURE)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_INFOSET)) { // REVISIT: This is somewhat expensive to compute // but it's possible that the user has a reference // to the configuration and is changing the values // of these features directly on it. boolean infoset = fConfiguration.getFeature(NAMESPACES) && fConfiguration.getFeature(Constants.DOM_NAMESPACE_DECLARATIONS) && fConfiguration.getFeature(INCLUDE_COMMENTS_FEATURE) && fConfiguration.getFeature(INCLUDE_IGNORABLE_WHITESPACE) && !fConfiguration.getFeature(DYNAMIC_VALIDATION) && !fConfiguration.getFeature(CREATE_ENTITY_REF_NODES) && !fConfiguration.getFeature(NORMALIZE_DATA) && !fConfiguration.getFeature(CREATE_CDATA_NODES_FEATURE); return (infoset) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase(Constants.DOM_CDATA_SECTIONS)) { return (fConfiguration.getFeature(CREATE_CDATA_NODES_FEATURE)) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase(Constants.DOM_CHECK_CHAR_NORMALIZATION ) || name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS)) { return Boolean.FALSE; } else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACE_DECLARATIONS) || name.equalsIgnoreCase (Constants.DOM_WELLFORMED) || name.equalsIgnoreCase (Constants.DOM_IGNORE_UNKNOWN_CHARACTER_DENORMALIZATIONS) || name.equalsIgnoreCase (Constants.DOM_CANONICAL_FORM) || name.equalsIgnoreCase (Constants.DOM_SUPPORTED_MEDIATYPES_ONLY) || name.equalsIgnoreCase (Constants.DOM_SPLIT_CDATA) || name.equalsIgnoreCase (Constants.DOM_CHARSET_OVERRIDES_XML_ENCODING)) { return (fConfiguration.getFeature (name.toLowerCase(Locale.ENGLISH))) ? Boolean.TRUE : Boolean.FALSE; } else if (name.equalsIgnoreCase (Constants.DOM_ERROR_HANDLER)) { if (fErrorHandler != null) { return fErrorHandler.getErrorHandler (); } return null; } else if (name.equalsIgnoreCase (Constants.DOM_RESOURCE_RESOLVER)) { try { XMLEntityResolver entityResolver = (XMLEntityResolver) fConfiguration.getProperty (ENTITY_RESOLVER); if (entityResolver != null && entityResolver instanceof DOMEntityResolverWrapper) { return ((DOMEntityResolverWrapper) entityResolver).getEntityResolver(); } } catch (XMLConfigurationException e) {} return null; } else if (name.equalsIgnoreCase (Constants.DOM_SCHEMA_TYPE)) { return fConfiguration.getProperty ( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE); } else if (name.equalsIgnoreCase (Constants.DOM_SCHEMA_LOCATION)) { return fSchemaLocation; } else if (name.equalsIgnoreCase (SYMBOL_TABLE)) { return fConfiguration.getProperty (SYMBOL_TABLE); } else if (name.equalsIgnoreCase (DOCUMENT_CLASS_NAME)) { return fConfiguration.getProperty (DOCUMENT_CLASS_NAME); } else { // This could be a recognized feature or property. String normalizedName; // The honour-all-schemaLocations feature is // mixed case so requires special treatment. if (name.equalsIgnoreCase(HONOUR_ALL_SCHEMALOCATIONS)) { normalizedName = HONOUR_ALL_SCHEMALOCATIONS; } else { normalizedName = name.toLowerCase(Locale.ENGLISH); } try { return fConfiguration.getFeature(normalizedName) ? Boolean.TRUE : Boolean.FALSE; } catch (XMLConfigurationException e) {} // This isn't a feature; perhaps it's a property try { return fConfiguration.getProperty(normalizedName); } catch (XMLConfigurationException e) {} throw newFeatureNotFoundError(name); } } public boolean canSetParameter (String name, Object value) { if (value == null) { return true; } if (value instanceof Boolean) { boolean state = ((Boolean)value).booleanValue(); if ( name.equalsIgnoreCase (Constants.DOM_SUPPORTED_MEDIATYPES_ONLY) || name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS) || name.equalsIgnoreCase(Constants.DOM_CHECK_CHAR_NORMALIZATION ) || name.equalsIgnoreCase (Constants.DOM_CANONICAL_FORM) ) { // true is not supported return (state) ? false : true; } else if (name.equalsIgnoreCase (Constants.DOM_WELLFORMED) || name.equalsIgnoreCase (Constants.DOM_IGNORE_UNKNOWN_CHARACTER_DENORMALIZATIONS)) { // false is not supported return (state) ? true : false; } else if (name.equalsIgnoreCase (Constants.DOM_CDATA_SECTIONS) || name.equalsIgnoreCase (Constants.DOM_CHARSET_OVERRIDES_XML_ENCODING) || name.equalsIgnoreCase (Constants.DOM_COMMENTS) || name.equalsIgnoreCase (Constants.DOM_DATATYPE_NORMALIZATION) || name.equalsIgnoreCase (Constants.DOM_DISALLOW_DOCTYPE) || name.equalsIgnoreCase (Constants.DOM_ENTITIES) || name.equalsIgnoreCase (Constants.DOM_INFOSET) || name.equalsIgnoreCase (Constants.DOM_NAMESPACES) || name.equalsIgnoreCase (Constants.DOM_NAMESPACE_DECLARATIONS) || name.equalsIgnoreCase (Constants.DOM_VALIDATE) || name.equalsIgnoreCase (Constants.DOM_VALIDATE_IF_SCHEMA) || name.equalsIgnoreCase (Constants.DOM_ELEMENT_CONTENT_WHITESPACE) || name.equalsIgnoreCase (Constants.DOM_XMLDECL)) { return true; } // Recognize Xerces features. try { String normalizedName; // The honour-all-schemaLocations feature is // mixed case so requires special treatment. if (name.equalsIgnoreCase(HONOUR_ALL_SCHEMALOCATIONS)) { normalizedName = HONOUR_ALL_SCHEMALOCATIONS; } else { normalizedName = name.toLowerCase(Locale.ENGLISH); } fConfiguration.getFeature(normalizedName); return true; } catch (XMLConfigurationException e) { return false; } } else { // check properties if (name.equalsIgnoreCase (Constants.DOM_ERROR_HANDLER)) { if (value instanceof DOMErrorHandler || value == null) { return true; } return false; } else if (name.equalsIgnoreCase (Constants.DOM_RESOURCE_RESOLVER)) { if (value instanceof LSResourceResolver || value == null) { return true; } return false; } else if (name.equalsIgnoreCase (Constants.DOM_SCHEMA_TYPE)) { if ((value instanceof String && (value.equals (Constants.NS_XMLSCHEMA) || value.equals (Constants.NS_DTD))) || value == null) { return true; } return false; } else if (name.equalsIgnoreCase (Constants.DOM_SCHEMA_LOCATION)) { if (value instanceof String || value == null) return true; return false; } else if (name.equalsIgnoreCase (DOCUMENT_CLASS_NAME)) { return true; } // Recognize Xerces properties. try { fConfiguration.getProperty(name.toLowerCase(Locale.ENGLISH)); return true; } catch (XMLConfigurationException e) { return false; } } } /** * DOM Level 3 CR - Experimental. * * The list of the parameters supported by this * <code>DOMConfiguration</code> object and for which at least one value * can be set by the application. Note that this list can also contain * parameter names defined outside this specification. */ public DOMStringList getParameterNames () { if (fRecognizedParameters == null){ ArrayList parameters = new ArrayList(); // REVISIT: add Xerces recognized properties/features parameters.add(Constants.DOM_NAMESPACES); parameters.add(Constants.DOM_CDATA_SECTIONS); parameters.add(Constants.DOM_CANONICAL_FORM); parameters.add(Constants.DOM_NAMESPACE_DECLARATIONS); parameters.add(Constants.DOM_SPLIT_CDATA); parameters.add(Constants.DOM_ENTITIES); parameters.add(Constants.DOM_VALIDATE_IF_SCHEMA); parameters.add(Constants.DOM_VALIDATE); parameters.add(Constants.DOM_DATATYPE_NORMALIZATION); parameters.add(Constants.DOM_CHARSET_OVERRIDES_XML_ENCODING); parameters.add(Constants.DOM_CHECK_CHAR_NORMALIZATION); parameters.add(Constants.DOM_SUPPORTED_MEDIATYPES_ONLY); parameters.add(Constants.DOM_IGNORE_UNKNOWN_CHARACTER_DENORMALIZATIONS); parameters.add(Constants.DOM_NORMALIZE_CHARACTERS); parameters.add(Constants.DOM_WELLFORMED); parameters.add(Constants.DOM_INFOSET); parameters.add(Constants.DOM_DISALLOW_DOCTYPE); parameters.add(Constants.DOM_ELEMENT_CONTENT_WHITESPACE); parameters.add(Constants.DOM_COMMENTS); parameters.add(Constants.DOM_ERROR_HANDLER); parameters.add(Constants.DOM_RESOURCE_RESOLVER); parameters.add(Constants.DOM_SCHEMA_LOCATION); parameters.add(Constants.DOM_SCHEMA_TYPE); fRecognizedParameters = new DOMStringListImpl(parameters); } return fRecognizedParameters; } /** * Parse an XML document from a location identified by an URI reference. * If the URI contains a fragment identifier (see section 4.1 in ), the * behavior is not defined by this specification. * */ public Document parseURI (String uri) throws LSException { //If DOMParser insstance is already busy parsing another document when this // method is called, then raise INVALID_STATE_ERR according to DOM L3 LS spec if ( fBusy ) { throw newInvalidStateError(); } XMLInputSource source = new XMLInputSource (null, uri, null); try { currentThread = Thread.currentThread(); fBusy = true; parse (source); fBusy = false; if (abortNow && currentThread.isInterrupted()) { //reset interrupt state abortNow = false; Thread.interrupted(); } } catch (Exception e){ fBusy = false; if (abortNow && currentThread.isInterrupted()) { Thread.interrupted(); } if (abortNow) { abortNow = false; restoreHandlers(); return null; } // Consume this exception if the user // issued an interrupt or an abort. if (e != ABORT) { if (!(e instanceof XMLParseException) && fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl (); error.fException = e; error.fMessage = e.getMessage (); error.fSeverity = DOMError.SEVERITY_FATAL_ERROR; fErrorHandler.getErrorHandler ().handleError (error); } if (DEBUG) { e.printStackTrace (); } throw (LSException) DOMUtil.createLSException(LSException.PARSE_ERR, e).fillInStackTrace(); } } Document doc = getDocument(); dropDocumentReferences(); return doc; } /** * Parse an XML document from a resource identified by an * <code>LSInput</code>. * */ public Document parse (LSInput is) throws LSException { // need to wrap the LSInput with an XMLInputSource XMLInputSource xmlInputSource = dom2xmlInputSource (is); if ( fBusy ) { throw newInvalidStateError(); } try { currentThread = Thread.currentThread(); fBusy = true; parse (xmlInputSource); fBusy = false; if (abortNow && currentThread.isInterrupted()) { //reset interrupt state abortNow = false; Thread.interrupted(); } } catch (Exception e) { fBusy = false; if (abortNow && currentThread.isInterrupted()) { Thread.interrupted(); } if (abortNow) { abortNow = false; restoreHandlers(); return null; } // Consume this exception if the user // issued an interrupt or an abort. if (e != ABORT) { if (!(e instanceof XMLParseException) && fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl (); error.fException = e; error.fMessage = e.getMessage (); error.fSeverity = DOMError.SEVERITY_FATAL_ERROR; fErrorHandler.getErrorHandler().handleError (error); } if (DEBUG) { e.printStackTrace (); } throw (LSException) DOMUtil.createLSException(LSException.PARSE_ERR, e).fillInStackTrace(); } } Document doc = getDocument(); dropDocumentReferences(); return doc; } private void restoreHandlers() { fConfiguration.setDocumentHandler(this); fConfiguration.setDTDHandler(this); fConfiguration.setDTDContentModelHandler(this); } /** * Parse an XML document or fragment from a resource identified by an * <code>LSInput</code> and insert the content into an existing * document at the position epcified with the <code>contextNode</code> * and <code>action</code> arguments. When parsing the input stream the * context node is used for resolving unbound namespace prefixes. * * @param is The <code>LSInput</code> from which the source * document is to be read. * @param cnode The <code>Node</code> that is used as the context for * the data that is being parsed. * @param action This parameter describes which action should be taken * between the new set of node being inserted and the existing * children of the context node. The set of possible actions is * defined above. * @exception DOMException * HIERARCHY_REQUEST_ERR: Thrown if this action results in an invalid * hierarchy (i.e. a Document with more than one document element). */ public Node parseWithContext (LSInput is, Node cnode, short action) throws DOMException, LSException { // REVISIT: need to implement. throw new DOMException (DOMException.NOT_SUPPORTED_ERR, "Not supported"); } /** * NON-DOM: convert LSInput to XNIInputSource * * @param is * @return */ XMLInputSource dom2xmlInputSource (LSInput is) { // need to wrap the LSInput with an XMLInputSource XMLInputSource xis = null; // check whether there is a Reader // according to DOM, we need to treat such reader as "UTF-16". if (is.getCharacterStream () != null) { xis = new XMLInputSource (is.getPublicId (), is.getSystemId (), is.getBaseURI (), is.getCharacterStream (), "UTF-16"); } // check whether there is an InputStream else if (is.getByteStream () != null) { xis = new XMLInputSource (is.getPublicId (), is.getSystemId (), is.getBaseURI (), is.getByteStream (), is.getEncoding ()); } // if there is a string data, use a StringReader // according to DOM, we need to treat such data as "UTF-16". else if (is.getStringData () != null && is.getStringData().length() > 0) { xis = new XMLInputSource (is.getPublicId (), is.getSystemId (), is.getBaseURI (), new StringReader (is.getStringData ()), "UTF-16"); } // otherwise, just use the public/system/base Ids else if ((is.getSystemId() != null && is.getSystemId().length() > 0) || (is.getPublicId() != null && is.getPublicId().length() > 0)) { xis = new XMLInputSource (is.getPublicId (), is.getSystemId (), is.getBaseURI ()); } else { // all inputs are null if (fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl(); error.fType = "no-input-specified"; error.fMessage = "no-input-specified"; error.fSeverity = DOMError.SEVERITY_FATAL_ERROR; fErrorHandler.getErrorHandler().handleError(error); } throw new LSException(LSException.PARSE_ERR, "no-input-specified"); } return xis; } /** * @see org.w3c.dom.ls.LSParser#getAsync() */ public boolean getAsync () { return false; } /** * @see org.w3c.dom.ls.LSParser#getBusy() */ public boolean getBusy () { return fBusy; } /** * @see org.w3c.dom.ls.LSParser#abort() */ public void abort () { // If parse operation is in progress then reset it if (fBusy) { fBusy = false; if (currentThread != null) { abortNow = true; fConfiguration.setDocumentHandler(abortHandler); fConfiguration.setDTDHandler(abortHandler); fConfiguration.setDTDContentModelHandler(abortHandler); if (currentThread == Thread.currentThread()) { throw ABORT; } currentThread.interrupt(); } } return; // If not busy then this is noop } /** * The start of an element. If the document specifies the start element * by using an empty tag, then the startElement method will immediately * be followed by the endElement method, with no intervening methods. * Overriding the parent to handle DOM_NAMESPACE_DECLARATIONS=false. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement (QName element, XMLAttributes attributes, Augmentations augs) { // namespace declarations parameter has no effect if namespaces is false. if (!fNamespaceDeclarations && fNamespaceAware) { int len = attributes.getLength(); for (int i = len - 1; i >= 0; --i) { if (XMLSymbols.PREFIX_XMLNS == attributes.getPrefix(i) || XMLSymbols.PREFIX_XMLNS == attributes.getQName(i)) { attributes.removeAttributeAt(i); } } } super.startElement(element, attributes, augs); } private static final class AbortHandler implements XMLDocumentHandler, XMLDTDHandler, XMLDTDContentModelHandler { private XMLDocumentSource documentSource; private XMLDTDContentModelSource dtdContentSource; private XMLDTDSource dtdSource; public void startDocument(XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { throw ABORT; } public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { throw ABORT; } public void doctypeDecl(String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { throw ABORT; } public void comment(XMLString text, Augmentations augs) throws XNIException { throw ABORT; } public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { throw ABORT; } public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { throw ABORT; } public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { throw ABORT; } public void startGeneralEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { throw ABORT; } public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { throw ABORT; } public void endGeneralEntity(String name, Augmentations augs) throws XNIException { throw ABORT; } public void characters(XMLString text, Augmentations augs) throws XNIException { throw ABORT; } public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { throw ABORT; } public void endElement(QName element, Augmentations augs) throws XNIException { throw ABORT; } public void startCDATA(Augmentations augs) throws XNIException { throw ABORT; } public void endCDATA(Augmentations augs) throws XNIException { throw ABORT; } public void endDocument(Augmentations augs) throws XNIException { throw ABORT; } public void setDocumentSource(XMLDocumentSource source) { documentSource = source; } public XMLDocumentSource getDocumentSource() { return documentSource; } public void startDTD(XMLLocator locator, Augmentations augmentations) throws XNIException { throw ABORT; } public void startParameterEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augmentations) throws XNIException { throw ABORT; } public void endParameterEntity(String name, Augmentations augmentations) throws XNIException { throw ABORT; } public void startExternalSubset(XMLResourceIdentifier identifier, Augmentations augmentations) throws XNIException { throw ABORT; } public void endExternalSubset(Augmentations augmentations) throws XNIException { throw ABORT; } public void elementDecl(String name, String contentModel, Augmentations augmentations) throws XNIException { throw ABORT; } public void startAttlist(String elementName, Augmentations augmentations) throws XNIException { throw ABORT; } public void attributeDecl(String elementName, String attributeName, String type, String[] enumeration, String defaultType, XMLString defaultValue, XMLString nonNormalizedDefaultValue, Augmentations augmentations) throws XNIException { throw ABORT; } public void endAttlist(Augmentations augmentations) throws XNIException { throw ABORT; } public void internalEntityDecl(String name, XMLString text, XMLString nonNormalizedText, Augmentations augmentations) throws XNIException { throw ABORT; } public void externalEntityDecl(String name, XMLResourceIdentifier identifier, Augmentations augmentations) throws XNIException { throw ABORT; } public void unparsedEntityDecl(String name, XMLResourceIdentifier identifier, String notation, Augmentations augmentations) throws XNIException { throw ABORT; } public void notationDecl(String name, XMLResourceIdentifier identifier, Augmentations augmentations) throws XNIException { throw ABORT; } public void startConditional(short type, Augmentations augmentations) throws XNIException { throw ABORT; } public void ignoredCharacters(XMLString text, Augmentations augmentations) throws XNIException { throw ABORT; } public void endConditional(Augmentations augmentations) throws XNIException { throw ABORT; } public void endDTD(Augmentations augmentations) throws XNIException { throw ABORT; } public void setDTDSource(XMLDTDSource source) { dtdSource = source; } public XMLDTDSource getDTDSource() { return dtdSource; } public void startContentModel(String elementName, Augmentations augmentations) throws XNIException { throw ABORT; } public void any(Augmentations augmentations) throws XNIException { throw ABORT; } public void empty(Augmentations augmentations) throws XNIException { throw ABORT; } public void startGroup(Augmentations augmentations) throws XNIException { throw ABORT; } public void pcdata(Augmentations augmentations) throws XNIException { throw ABORT; } public void element(String elementName, Augmentations augmentations) throws XNIException { throw ABORT; } public void separator(short separator, Augmentations augmentations) throws XNIException { throw ABORT; } public void occurrence(short occurrence, Augmentations augmentations) throws XNIException { throw ABORT; } public void endGroup(Augmentations augmentations) throws XNIException { throw ABORT; } public void endContentModel(Augmentations augmentations) throws XNIException { throw ABORT; } public void setDTDContentModelSource(XMLDTDContentModelSource source) { dtdContentSource = source; } public XMLDTDContentModelSource getDTDContentModelSource() { return dtdContentSource; } } private static DOMException newInvalidStateError() { String msg = DOMMessageFormatter.formatMessage ( DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null); throw new DOMException ( DOMException.INVALID_STATE_ERR, msg); } private static DOMException newFeatureNotSupportedError(String name) { String msg = DOMMessageFormatter.formatMessage ( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_SUPPORTED", new Object[] { name }); return new DOMException (DOMException.NOT_SUPPORTED_ERR, msg); } private static DOMException newFeatureNotFoundError(String name) { String msg = DOMMessageFormatter.formatMessage ( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_FOUND", new Object[] { name }); return new DOMException (DOMException.NOT_FOUND_ERR, msg); } private static DOMException newTypeMismatchError(String name) { String msg = DOMMessageFormatter.formatMessage ( DOMMessageFormatter.DOM_DOMAIN, "TYPE_MISMATCH_ERR", new Object[] { name }); return new DOMException (DOMException.TYPE_MISMATCH_ERR, msg); } } // class DOMParserImpl
false
false
null
null
diff --git a/lucene/core/src/java/org/apache/lucene/search/DocIdSet.java b/lucene/core/src/java/org/apache/lucene/search/DocIdSet.java index 6345e6aaf3..cccd1f4a9b 100644 --- a/lucene/core/src/java/org/apache/lucene/search/DocIdSet.java +++ b/lucene/core/src/java/org/apache/lucene/search/DocIdSet.java @@ -1,91 +1,91 @@ package org.apache.lucene.search; /* * 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. */ import java.io.IOException; import org.apache.lucene.util.Bits; /** * A DocIdSet contains a set of doc ids. Implementing classes must * only implement {@link #iterator} to provide access to the set. */ public abstract class DocIdSet { /** An empty {@code DocIdSet} instance for easy use, e.g. in Filters that hit no documents. */ public static final DocIdSet EMPTY_DOCIDSET = new DocIdSet() { private final DocIdSetIterator iterator = new DocIdSetIterator() { @Override public int advance(int target) { return NO_MORE_DOCS; } @Override public int docID() { return NO_MORE_DOCS; } @Override public int nextDoc() { return NO_MORE_DOCS; } }; @Override public DocIdSetIterator iterator() { return iterator; } @Override public boolean isCacheable() { return true; } // we explicitely provide no random access, as this filter is 100% sparse and iterator exits faster @Override public Bits bits() { return null; } }; /** Provides a {@link DocIdSetIterator} to access the set. * This implementation can return <code>null</code> or * <code>{@linkplain #EMPTY_DOCIDSET}.iterator()</code> if there * are no docs that match. */ public abstract DocIdSetIterator iterator() throws IOException; /** Optionally provides a {@link Bits} interface for random access * to matching documents. * @return {@code null}, if this {@code DocIdSet} does not support random access. * In contrast to {@link #iterator()}, a return value of {@code null} * <b>does not</b> imply that no documents match the filter! * The default implementation does not provide random access, so you * only need to implement this method if your DocIdSet can * guarantee random access to every docid in O(1) time without * external disk access (as {@link Bits} interface cannot throw * {@link IOException}). This is generally true for bit sets * like {@link org.apache.lucene.util.FixedBitSet}, which return - * itsself if they are used as {@code DocIdSet}. + * itself if they are used as {@code DocIdSet}. */ public Bits bits() throws IOException { return null; } /** * This method is a hint for {@link CachingWrapperFilter}, if this <code>DocIdSet</code> * should be cached without copying it into a BitSet. The default is to return * <code>false</code>. If you have an own <code>DocIdSet</code> implementation * that does its iteration very effective and fast without doing disk I/O, * override this method and return <code>true</here>. */ public boolean isCacheable() { return false; } } diff --git a/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java b/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java index 8dbb146507..5e351976ab 100644 --- a/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java +++ b/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java @@ -1,526 +1,526 @@ package org.apache.lucene.search; /* * 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. */ import java.io.IOException; import java.util.Comparator; import java.util.LinkedList; import org.apache.lucene.analysis.NumericTokenStream; // for javadocs import org.apache.lucene.document.DoubleField; // for javadocs import org.apache.lucene.document.FloatField; // for javadocs import org.apache.lucene.document.IntField; // for javadocs import org.apache.lucene.document.LongField; // for javadocs import org.apache.lucene.document.FieldType.NumericType; import org.apache.lucene.index.FilteredTermsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.AttributeSource; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.NumericUtils; import org.apache.lucene.util.ToStringUtils; import org.apache.lucene.index.Term; // for javadocs /** * <p>A {@link Query} that matches numeric values within a * specified range. To use this, you must first index the * numeric values using {@link IntField}, {@link * FloatField}, {@link LongField} or {@link DoubleField} (expert: {@link * NumericTokenStream}). If your terms are instead textual, * you should use {@link TermRangeQuery}. {@link * NumericRangeFilter} is the filter equivalent of this * query.</p> * * <p>You create a new NumericRangeQuery with the static * factory methods, eg: * * <pre> * Query q = NumericRangeQuery.newFloatRange("weight", 0.03f, 0.10f, true, true); * </pre> * * matches all documents whose float valued "weight" field * ranges from 0.03 to 0.10, inclusive. * * <p>The performance of NumericRangeQuery is much better * than the corresponding {@link TermRangeQuery} because the * number of terms that must be searched is usually far * fewer, thanks to trie indexing, described below.</p> * * <p>You can optionally specify a <a * href="#precisionStepDesc"><code>precisionStep</code></a> * when creating this query. This is necessary if you've * changed this configuration from its default (4) during * indexing. Lower values consume more disk space but speed * up searching. Suitable values are between <b>1</b> and * <b>8</b>. A good starting point to test is <b>4</b>, * which is the default value for all <code>Numeric*</code> * classes. See <a href="#precisionStepDesc">below</a> for * details. * * <p>This query defaults to {@linkplain * MultiTermQuery#CONSTANT_SCORE_AUTO_REWRITE_DEFAULT} for * 32 bit (int/float) ranges with precisionStep &le;8 and 64 * bit (long/double) ranges with precisionStep &le;6. * Otherwise it uses {@linkplain * MultiTermQuery#CONSTANT_SCORE_FILTER_REWRITE} as the * number of terms is likely to be high. With precision * steps of &le;4, this query can be run with one of the * BooleanQuery rewrite methods without changing * BooleanQuery's default max clause count. * * <br><h3>How it works</h3> * * <p>See the publication about <a target="_blank" href="http://www.panfmp.org">panFMP</a>, * where this algorithm was described (referred to as <code>TrieRangeQuery</code>): * * <blockquote><strong>Schindler, U, Diepenbroek, M</strong>, 2008. * <em>Generic XML-based Framework for Metadata Portals.</em> * Computers &amp; Geosciences 34 (12), 1947-1955. * <a href="http://dx.doi.org/10.1016/j.cageo.2008.02.023" * target="_blank">doi:10.1016/j.cageo.2008.02.023</a></blockquote> * * <p><em>A quote from this paper:</em> Because Apache Lucene is a full-text * search engine and not a conventional database, it cannot handle numerical ranges * (e.g., field value is inside user defined bounds, even dates are numerical values). * We have developed an extension to Apache Lucene that stores * the numerical values in a special string-encoded format with variable precision * (all numerical values like doubles, longs, floats, and ints are converted to * lexicographic sortable string representations and stored with different precisions * (for a more detailed description of how the values are stored, * see {@link NumericUtils}). A range is then divided recursively into multiple intervals for searching: * The center of the range is searched only with the lowest possible precision in the <em>trie</em>, * while the boundaries are matched more exactly. This reduces the number of terms dramatically.</p> * * <p>For the variant that stores long values in 8 different precisions (each reduced by 8 bits) that * uses a lowest precision of 1 byte, the index contains only a maximum of 256 distinct values in the * lowest precision. Overall, a range could consist of a theoretical maximum of * <code>7*255*2 + 255 = 3825</code> distinct terms (when there is a term for every distinct value of an * 8-byte-number in the index and the range covers almost all of them; a maximum of 255 distinct values is used * because it would always be possible to reduce the full 256 values to one term with degraded precision). * In practice, we have seen up to 300 terms in most cases (index with 500,000 metadata records * and a uniform value distribution).</p> * * <a name="precisionStepDesc"><h3>Precision Step</h3> * <p>You can choose any <code>precisionStep</code> when encoding values. * Lower step values mean more precisions and so more terms in index (and index gets larger). * On the other hand, the maximum number of terms to match reduces, which optimized query speed. * The formula to calculate the maximum term count is: * <pre> * n = [ (bitsPerValue/precisionStep - 1) * (2^precisionStep - 1 ) * 2 ] + (2^precisionStep - 1 ) * </pre> * <p><em>(this formula is only correct, when <code>bitsPerValue/precisionStep</code> is an integer; * in other cases, the value must be rounded up and the last summand must contain the modulo of the division as * precision step)</em>. * For longs stored using a precision step of 4, <code>n = 15*15*2 + 15 = 465</code>, and for a precision * step of 2, <code>n = 31*3*2 + 3 = 189</code>. But the faster search speed is reduced by more seeking * in the term enum of the index. Because of this, the ideal <code>precisionStep</code> value can only * be found out by testing. <b>Important:</b> You can index with a lower precision step value and test search speed * using a multiple of the original step value.</p> * * <p>Good values for <code>precisionStep</code> are depending on usage and data type: * <ul> * <li>The default for all data types is <b>4</b>, which is used, when no <code>precisionStep</code> is given. * <li>Ideal value in most cases for <em>64 bit</em> data types <em>(long, double)</em> is <b>6</b> or <b>8</b>. * <li>Ideal value in most cases for <em>32 bit</em> data types <em>(int, float)</em> is <b>4</b>. * <li>For low cardinality fields larger precision steps are good. If the cardinality is &lt; 100, it is * fair to use {@link Integer#MAX_VALUE} (see below). * <li>Steps <b>&ge;64</b> for <em>long/double</em> and <b>&ge;32</b> for <em>int/float</em> produces one token * per value in the index and querying is as slow as a conventional {@link TermRangeQuery}. But it can be used * to produce fields, that are solely used for sorting (in this case simply use {@link Integer#MAX_VALUE} as * <code>precisionStep</code>). Using {@link IntField}, * {@link LongField}, {@link FloatField} or {@link DoubleField} for sorting * is ideal, because building the field cache is much faster than with text-only numbers. * These fields have one term per value and therefore also work with term enumeration for building distinct lists * (e.g. facets / preselected values to search for). * Sorting is also possible with range query optimized fields using one of the above <code>precisionSteps</code>. * </ul> * * <p>Comparisons of the different types of RangeQueries on an index with about 500,000 docs showed * that {@link TermRangeQuery} in boolean rewrite mode (with raised {@link BooleanQuery} clause count) * took about 30-40 secs to complete, {@link TermRangeQuery} in constant score filter rewrite mode took 5 secs * and executing this class took &lt;100ms to complete (on an Opteron64 machine, Java 1.5, 8 bit * precision step). This query type was developed for a geographic portal, where the performance for * e.g. bounding boxes or exact date/time stamps is important.</p> * * @since 2.9 **/ public final class NumericRangeQuery<T extends Number> extends MultiTermQuery { private NumericRangeQuery(final String field, final int precisionStep, final NumericType dataType, T min, T max, final boolean minInclusive, final boolean maxInclusive ) { super(field); if (precisionStep < 1) throw new IllegalArgumentException("precisionStep must be >=1"); this.precisionStep = precisionStep; this.dataType = dataType; this.min = min; this.max = max; this.minInclusive = minInclusive; this.maxInclusive = maxInclusive; } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>long</code> * range using the given <a href="#precisionStepDesc"><code>precisionStep</code></a>. * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Long> newLongRange(final String field, final int precisionStep, Long min, Long max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Long>(field, precisionStep, NumericType.LONG, min, max, minInclusive, maxInclusive); } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>long</code> * range using the default <code>precisionStep</code> {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Long> newLongRange(final String field, Long min, Long max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Long>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.LONG, min, max, minInclusive, maxInclusive); } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>int</code> * range using the given <a href="#precisionStepDesc"><code>precisionStep</code></a>. * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Integer> newIntRange(final String field, final int precisionStep, Integer min, Integer max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Integer>(field, precisionStep, NumericType.INT, min, max, minInclusive, maxInclusive); } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>int</code> * range using the default <code>precisionStep</code> {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Integer> newIntRange(final String field, Integer min, Integer max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Integer>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.INT, min, max, minInclusive, maxInclusive); } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>double</code> * range using the given <a href="#precisionStepDesc"><code>precisionStep</code></a>. * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. * {@link Double#NaN} will never match a half-open range, to hit {@code NaN} use a query * with {@code min == max == Double.NaN}. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Double> newDoubleRange(final String field, final int precisionStep, Double min, Double max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Double>(field, precisionStep, NumericType.DOUBLE, min, max, minInclusive, maxInclusive); } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>double</code> * range using the default <code>precisionStep</code> {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. * {@link Double#NaN} will never match a half-open range, to hit {@code NaN} use a query * with {@code min == max == Double.NaN}. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Double> newDoubleRange(final String field, Double min, Double max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Double>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.DOUBLE, min, max, minInclusive, maxInclusive); } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>float</code> * range using the given <a href="#precisionStepDesc"><code>precisionStep</code></a>. * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. * {@link Float#NaN} will never match a half-open range, to hit {@code NaN} use a query * with {@code min == max == Float.NaN}. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Float> newFloatRange(final String field, final int precisionStep, Float min, Float max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Float>(field, precisionStep, NumericType.FLOAT, min, max, minInclusive, maxInclusive); } /** * Factory that creates a <code>NumericRangeQuery</code>, that queries a <code>float</code> * range using the default <code>precisionStep</code> {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). * You can have half-open ranges (which are in fact &lt;/&le; or &gt;/&ge; queries) * by setting the min or max value to <code>null</code>. * {@link Float#NaN} will never match a half-open range, to hit {@code NaN} use a query * with {@code min == max == Float.NaN}. By setting inclusive to false, it will * match all documents excluding the bounds, with inclusive on, the boundaries are hits, too. */ public static NumericRangeQuery<Float> newFloatRange(final String field, Float min, Float max, final boolean minInclusive, final boolean maxInclusive ) { return new NumericRangeQuery<Float>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.FLOAT, min, max, minInclusive, maxInclusive); } @Override @SuppressWarnings("unchecked") protected TermsEnum getTermsEnum(final Terms terms, AttributeSource atts) throws IOException { - // very strange: java.lang.Number itsself is not Comparable, but all subclasses used here are + // very strange: java.lang.Number itself is not Comparable, but all subclasses used here are if (min != null && max != null && ((Comparable<T>) min).compareTo(max) > 0) { return TermsEnum.EMPTY; } return new NumericRangeTermsEnum(terms.iterator(null)); } /** Returns <code>true</code> if the lower endpoint is inclusive */ public boolean includesMin() { return minInclusive; } /** Returns <code>true</code> if the upper endpoint is inclusive */ public boolean includesMax() { return maxInclusive; } /** Returns the lower value of this range query */ public T getMin() { return min; } /** Returns the upper value of this range query */ public T getMax() { return max; } /** Returns the precision step. */ public int getPrecisionStep() { return precisionStep; } @Override public String toString(final String field) { final StringBuilder sb = new StringBuilder(); if (!getField().equals(field)) sb.append(getField()).append(':'); return sb.append(minInclusive ? '[' : '{') .append((min == null) ? "*" : min.toString()) .append(" TO ") .append((max == null) ? "*" : max.toString()) .append(maxInclusive ? ']' : '}') .append(ToStringUtils.boost(getBoost())) .toString(); } @Override @SuppressWarnings({"unchecked","rawtypes"}) public final boolean equals(final Object o) { if (o==this) return true; if (!super.equals(o)) return false; if (o instanceof NumericRangeQuery) { final NumericRangeQuery q=(NumericRangeQuery)o; return ( (q.min == null ? min == null : q.min.equals(min)) && (q.max == null ? max == null : q.max.equals(max)) && minInclusive == q.minInclusive && maxInclusive == q.maxInclusive && precisionStep == q.precisionStep ); } return false; } @Override public final int hashCode() { int hash = super.hashCode(); hash += precisionStep^0x64365465; if (min != null) hash += min.hashCode()^0x14fa55fb; if (max != null) hash += max.hashCode()^0x733fa5fe; return hash + (Boolean.valueOf(minInclusive).hashCode()^0x14fa55fb)+ (Boolean.valueOf(maxInclusive).hashCode()^0x733fa5fe); } // members (package private, to be also fast accessible by NumericRangeTermEnum) final int precisionStep; final NumericType dataType; final T min, max; final boolean minInclusive,maxInclusive; // used to handle float/double infinity correcty static final long LONG_NEGATIVE_INFINITY = NumericUtils.doubleToSortableLong(Double.NEGATIVE_INFINITY); static final long LONG_POSITIVE_INFINITY = NumericUtils.doubleToSortableLong(Double.POSITIVE_INFINITY); static final int INT_NEGATIVE_INFINITY = NumericUtils.floatToSortableInt(Float.NEGATIVE_INFINITY); static final int INT_POSITIVE_INFINITY = NumericUtils.floatToSortableInt(Float.POSITIVE_INFINITY); /** * Subclass of FilteredTermsEnum for enumerating all terms that match the * sub-ranges for trie range queries, using flex API. * <p> * WARNING: This term enumeration is not guaranteed to be always ordered by * {@link Term#compareTo}. * The ordering depends on how {@link NumericUtils#splitLongRange} and * {@link NumericUtils#splitIntRange} generates the sub-ranges. For * {@link MultiTermQuery} ordering is not relevant. */ private final class NumericRangeTermsEnum extends FilteredTermsEnum { private BytesRef currentLowerBound, currentUpperBound; private final LinkedList<BytesRef> rangeBounds = new LinkedList<BytesRef>(); private final Comparator<BytesRef> termComp; NumericRangeTermsEnum(final TermsEnum tenum) { super(tenum); switch (dataType) { case LONG: case DOUBLE: { // lower long minBound; if (dataType == NumericType.LONG) { minBound = (min == null) ? Long.MIN_VALUE : min.longValue(); } else { assert dataType == NumericType.DOUBLE; minBound = (min == null) ? LONG_NEGATIVE_INFINITY : NumericUtils.doubleToSortableLong(min.doubleValue()); } if (!minInclusive && min != null) { if (minBound == Long.MAX_VALUE) break; minBound++; } // upper long maxBound; if (dataType == NumericType.LONG) { maxBound = (max == null) ? Long.MAX_VALUE : max.longValue(); } else { assert dataType == NumericType.DOUBLE; maxBound = (max == null) ? LONG_POSITIVE_INFINITY : NumericUtils.doubleToSortableLong(max.doubleValue()); } if (!maxInclusive && max != null) { if (maxBound == Long.MIN_VALUE) break; maxBound--; } NumericUtils.splitLongRange(new NumericUtils.LongRangeBuilder() { @Override public final void addRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded) { rangeBounds.add(minPrefixCoded); rangeBounds.add(maxPrefixCoded); } }, precisionStep, minBound, maxBound); break; } case INT: case FLOAT: { // lower int minBound; if (dataType == NumericType.INT) { minBound = (min == null) ? Integer.MIN_VALUE : min.intValue(); } else { assert dataType == NumericType.FLOAT; minBound = (min == null) ? INT_NEGATIVE_INFINITY : NumericUtils.floatToSortableInt(min.floatValue()); } if (!minInclusive && min != null) { if (minBound == Integer.MAX_VALUE) break; minBound++; } // upper int maxBound; if (dataType == NumericType.INT) { maxBound = (max == null) ? Integer.MAX_VALUE : max.intValue(); } else { assert dataType == NumericType.FLOAT; maxBound = (max == null) ? INT_POSITIVE_INFINITY : NumericUtils.floatToSortableInt(max.floatValue()); } if (!maxInclusive && max != null) { if (maxBound == Integer.MIN_VALUE) break; maxBound--; } NumericUtils.splitIntRange(new NumericUtils.IntRangeBuilder() { @Override public final void addRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded) { rangeBounds.add(minPrefixCoded); rangeBounds.add(maxPrefixCoded); } }, precisionStep, minBound, maxBound); break; } default: // should never happen throw new IllegalArgumentException("Invalid NumericType"); } termComp = getComparator(); } private void nextRange() { assert rangeBounds.size() % 2 == 0; currentLowerBound = rangeBounds.removeFirst(); assert currentUpperBound == null || termComp.compare(currentUpperBound, currentLowerBound) <= 0 : "The current upper bound must be <= the new lower bound"; currentUpperBound = rangeBounds.removeFirst(); } @Override protected final BytesRef nextSeekTerm(BytesRef term) { while (rangeBounds.size() >= 2) { nextRange(); // if the new upper bound is before the term parameter, the sub-range is never a hit if (term != null && termComp.compare(term, currentUpperBound) > 0) continue; // never seek backwards, so use current term if lower bound is smaller return (term != null && termComp.compare(term, currentLowerBound) > 0) ? term : currentLowerBound; } // no more sub-range enums available assert rangeBounds.isEmpty(); currentLowerBound = currentUpperBound = null; return null; } @Override protected final AcceptStatus accept(BytesRef term) { while (currentUpperBound == null || termComp.compare(term, currentUpperBound) > 0) { if (rangeBounds.isEmpty()) return AcceptStatus.END; // peek next sub-range, only seek if the current term is smaller than next lower bound if (termComp.compare(term, rangeBounds.getFirst()) < 0) return AcceptStatus.NO_AND_SEEK; // step forward to next range without seeking, as next lower range bound is less or equal current term nextRange(); } return AcceptStatus.YES; } } } diff --git a/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java b/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java index eda91b019d..9153a1b0db 100644 --- a/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java +++ b/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java @@ -1,568 +1,568 @@ package org.apache.lucene.util; /** * 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. */ import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Random; public class TestNumericUtils extends LuceneTestCase { public void testLongConversionAndOrdering() throws Exception { // generate a series of encoded longs, each numerical one bigger than the one before BytesRef last=null, act=new BytesRef(NumericUtils.BUF_SIZE_LONG); for (long l=-100000L; l<100000L; l++) { NumericUtils.longToPrefixCoded(l, 0, act); if (last!=null) { // test if smaller assertTrue("actual bigger than last (BytesRef)", last.compareTo(act) < 0 ); assertTrue("actual bigger than last (as String)", last.utf8ToString().compareTo(act.utf8ToString()) < 0 ); } // test is back and forward conversion works assertEquals("forward and back conversion should generate same long", l, NumericUtils.prefixCodedToLong(act)); // next step last = act; act = new BytesRef(NumericUtils.BUF_SIZE_LONG); } } public void testIntConversionAndOrdering() throws Exception { // generate a series of encoded ints, each numerical one bigger than the one before BytesRef last=null, act=new BytesRef(NumericUtils.BUF_SIZE_INT); for (int i=-100000; i<100000; i++) { NumericUtils.intToPrefixCoded(i, 0, act); if (last!=null) { // test if smaller assertTrue("actual bigger than last (BytesRef)", last.compareTo(act) < 0 ); assertTrue("actual bigger than last (as String)", last.utf8ToString().compareTo(act.utf8ToString()) < 0 ); } // test is back and forward conversion works assertEquals("forward and back conversion should generate same int", i, NumericUtils.prefixCodedToInt(act)); // next step last=act; act = new BytesRef(NumericUtils.BUF_SIZE_INT); } } public void testLongSpecialValues() throws Exception { long[] vals=new long[]{ Long.MIN_VALUE, Long.MIN_VALUE+1, Long.MIN_VALUE+2, -5003400000000L, -4000L, -3000L, -2000L, -1000L, -1L, 0L, 1L, 10L, 300L, 50006789999999999L, Long.MAX_VALUE-2, Long.MAX_VALUE-1, Long.MAX_VALUE }; BytesRef[] prefixVals=new BytesRef[vals.length]; for (int i=0; i<vals.length; i++) { prefixVals[i] = new BytesRef(NumericUtils.BUF_SIZE_LONG); NumericUtils.longToPrefixCoded(vals[i], 0, prefixVals[i]); // check forward and back conversion assertEquals( "forward and back conversion should generate same long", vals[i], NumericUtils.prefixCodedToLong(prefixVals[i]) ); // test if decoding values as int fails correctly try { NumericUtils.prefixCodedToInt(prefixVals[i]); fail("decoding a prefix coded long value as int should fail"); } catch (NumberFormatException e) { // worked } } // check sort order (prefixVals should be ascending) for (int i=1; i<prefixVals.length; i++) { assertTrue( "check sort order", prefixVals[i-1].compareTo(prefixVals[i]) < 0 ); } // check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits final BytesRef ref = new BytesRef(NumericUtils.BUF_SIZE_LONG); for (int i=0; i<vals.length; i++) { for (int j=0; j<64; j++) { NumericUtils.longToPrefixCoded(vals[i], j, ref); long prefixVal=NumericUtils.prefixCodedToLong(ref); long mask=(1L << j) - 1L; assertEquals( "difference between prefix val and original value for "+vals[i]+" with shift="+j, vals[i] & mask, vals[i]-prefixVal ); } } } public void testIntSpecialValues() throws Exception { int[] vals=new int[]{ Integer.MIN_VALUE, Integer.MIN_VALUE+1, Integer.MIN_VALUE+2, -64765767, -4000, -3000, -2000, -1000, -1, 0, 1, 10, 300, 765878989, Integer.MAX_VALUE-2, Integer.MAX_VALUE-1, Integer.MAX_VALUE }; BytesRef[] prefixVals=new BytesRef[vals.length]; for (int i=0; i<vals.length; i++) { prefixVals[i] = new BytesRef(NumericUtils.BUF_SIZE_INT); NumericUtils.intToPrefixCoded(vals[i], 0, prefixVals[i]); // check forward and back conversion assertEquals( "forward and back conversion should generate same int", vals[i], NumericUtils.prefixCodedToInt(prefixVals[i]) ); // test if decoding values as long fails correctly try { NumericUtils.prefixCodedToLong(prefixVals[i]); fail("decoding a prefix coded int value as long should fail"); } catch (NumberFormatException e) { // worked } } // check sort order (prefixVals should be ascending) for (int i=1; i<prefixVals.length; i++) { assertTrue( "check sort order", prefixVals[i-1].compareTo(prefixVals[i]) < 0 ); } // check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits final BytesRef ref = new BytesRef(NumericUtils.BUF_SIZE_LONG); for (int i=0; i<vals.length; i++) { for (int j=0; j<32; j++) { NumericUtils.intToPrefixCoded(vals[i], j, ref); int prefixVal=NumericUtils.prefixCodedToInt(ref); int mask=(1 << j) - 1; assertEquals( "difference between prefix val and original value for "+vals[i]+" with shift="+j, vals[i] & mask, vals[i]-prefixVal ); } } } public void testDoubles() throws Exception { double[] vals=new double[]{ Double.NEGATIVE_INFINITY, -2.3E25, -1.0E15, -1.0, -1.0E-1, -1.0E-2, -0.0, +0.0, 1.0E-2, 1.0E-1, 1.0, 1.0E15, 2.3E25, Double.POSITIVE_INFINITY, Double.NaN }; long[] longVals=new long[vals.length]; // check forward and back conversion for (int i=0; i<vals.length; i++) { longVals[i]=NumericUtils.doubleToSortableLong(vals[i]); assertTrue( "forward and back conversion should generate same double", Double.compare(vals[i], NumericUtils.sortableLongToDouble(longVals[i]))==0 ); } // check sort order (prefixVals should be ascending) for (int i=1; i<longVals.length; i++) { assertTrue( "check sort order", longVals[i-1] < longVals[i] ); } } public static final double[] DOUBLE_NANs = { Double.NaN, Double.longBitsToDouble(0x7ff0000000000001L), Double.longBitsToDouble(0x7fffffffffffffffL), Double.longBitsToDouble(0xfff0000000000001L), Double.longBitsToDouble(0xffffffffffffffffL) }; public void testSortableDoubleNaN() { final long plusInf = NumericUtils.doubleToSortableLong(Double.POSITIVE_INFINITY); for (double nan : DOUBLE_NANs) { assertTrue(Double.isNaN(nan)); final long sortable = NumericUtils.doubleToSortableLong(nan); assertTrue("Double not sorted correctly: " + nan + ", long repr: " + sortable + ", positive inf.: " + plusInf, sortable > plusInf); } } public void testFloats() throws Exception { float[] vals=new float[]{ Float.NEGATIVE_INFINITY, -2.3E25f, -1.0E15f, -1.0f, -1.0E-1f, -1.0E-2f, -0.0f, +0.0f, 1.0E-2f, 1.0E-1f, 1.0f, 1.0E15f, 2.3E25f, Float.POSITIVE_INFINITY, Float.NaN }; int[] intVals=new int[vals.length]; // check forward and back conversion for (int i=0; i<vals.length; i++) { intVals[i]=NumericUtils.floatToSortableInt(vals[i]); assertTrue( "forward and back conversion should generate same double", Float.compare(vals[i], NumericUtils.sortableIntToFloat(intVals[i]))==0 ); } // check sort order (prefixVals should be ascending) for (int i=1; i<intVals.length; i++) { assertTrue( "check sort order", intVals[i-1] < intVals[i] ); } } public static final float[] FLOAT_NANs = { Float.NaN, Float.intBitsToFloat(0x7f800001), Float.intBitsToFloat(0x7fffffff), Float.intBitsToFloat(0xff800001), Float.intBitsToFloat(0xffffffff) }; public void testSortableFloatNaN() { final int plusInf = NumericUtils.floatToSortableInt(Float.POSITIVE_INFINITY); for (float nan : FLOAT_NANs) { assertTrue(Float.isNaN(nan)); final int sortable = NumericUtils.floatToSortableInt(nan); assertTrue("Float not sorted correctly: " + nan + ", int repr: " + sortable + ", positive inf.: " + plusInf, sortable > plusInf); } } // INFO: Tests for trieCodeLong()/trieCodeInt() not needed because implicitely tested by range filter tests /** Note: The neededBounds Iterable must be unsigned (easier understanding what's happening) */ private void assertLongRangeSplit(final long lower, final long upper, int precisionStep, final boolean useBitSet, final Iterable<Long> expectedBounds, final Iterable<Integer> expectedShifts ) { // Cannot use FixedBitSet since the range could be long: final OpenBitSet bits=useBitSet ? new OpenBitSet(upper-lower+1) : null; final Iterator<Long> neededBounds = (expectedBounds == null) ? null : expectedBounds.iterator(); final Iterator<Integer> neededShifts = (expectedShifts == null) ? null : expectedShifts.iterator(); NumericUtils.splitLongRange(new NumericUtils.LongRangeBuilder() { @Override public void addRange(long min, long max, int shift) { assertTrue("min, max should be inside bounds", min>=lower && min<=upper && max>=lower && max<=upper); if (useBitSet) for (long l=min; l<=max; l++) { assertFalse("ranges should not overlap", bits.getAndSet(l-lower) ); // extra exit condition to prevent overflow on MAX_VALUE if (l == max) break; } if (neededBounds == null || neededShifts == null) return; // make unsigned longs for easier display and understanding min ^= 0x8000000000000000L; max ^= 0x8000000000000000L; //System.out.println("0x"+Long.toHexString(min>>>shift)+"L,0x"+Long.toHexString(max>>>shift)+"L)/*shift="+shift+"*/,"); assertEquals( "shift", neededShifts.next().intValue(), shift); assertEquals( "inner min bound", neededBounds.next().longValue(), min>>>shift); assertEquals( "inner max bound", neededBounds.next().longValue(), max>>>shift); } }, precisionStep, lower, upper); if (useBitSet) { // after flipping all bits in the range, the cardinality should be zero bits.flip(0,upper-lower+1); assertEquals("The sub-range concenated should match the whole range", 0, bits.cardinality()); } } /** LUCENE-2541: NumericRangeQuery errors with endpoints near long min and max values */ public void testLongExtremeValues() throws Exception { // upper end extremes assertLongRangeSplit(Long.MAX_VALUE, Long.MAX_VALUE, 1, true, Arrays.asList( 0xffffffffffffffffL,0xffffffffffffffffL ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MAX_VALUE, Long.MAX_VALUE, 2, true, Arrays.asList( 0xffffffffffffffffL,0xffffffffffffffffL ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MAX_VALUE, Long.MAX_VALUE, 4, true, Arrays.asList( 0xffffffffffffffffL,0xffffffffffffffffL ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MAX_VALUE, Long.MAX_VALUE, 6, true, Arrays.asList( 0xffffffffffffffffL,0xffffffffffffffffL ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MAX_VALUE, Long.MAX_VALUE, 8, true, Arrays.asList( 0xffffffffffffffffL,0xffffffffffffffffL ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MAX_VALUE, Long.MAX_VALUE, 64, true, Arrays.asList( 0xffffffffffffffffL,0xffffffffffffffffL ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MAX_VALUE-0xfL, Long.MAX_VALUE, 4, true, Arrays.asList( 0xfffffffffffffffL,0xfffffffffffffffL ), Arrays.asList( 4 )); assertLongRangeSplit(Long.MAX_VALUE-0x10L, Long.MAX_VALUE, 4, true, Arrays.asList( 0xffffffffffffffefL,0xffffffffffffffefL, 0xfffffffffffffffL,0xfffffffffffffffL ), Arrays.asList( 0, 4 )); // lower end extremes assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE, 1, true, Arrays.asList( 0x0000000000000000L,0x0000000000000000L ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE, 2, true, Arrays.asList( 0x0000000000000000L,0x0000000000000000L ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE, 4, true, Arrays.asList( 0x0000000000000000L,0x0000000000000000L ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE, 6, true, Arrays.asList( 0x0000000000000000L,0x0000000000000000L ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE, 8, true, Arrays.asList( 0x0000000000000000L,0x0000000000000000L ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE, 64, true, Arrays.asList( 0x0000000000000000L,0x0000000000000000L ), Arrays.asList( 0 )); assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE+0xfL, 4, true, Arrays.asList( 0x000000000000000L,0x000000000000000L ), Arrays.asList( 4 )); assertLongRangeSplit(Long.MIN_VALUE, Long.MIN_VALUE+0x10L, 4, true, Arrays.asList( 0x0000000000000010L,0x0000000000000010L, 0x000000000000000L,0x000000000000000L ), Arrays.asList( 0, 4 )); } public void testRandomSplit() throws Exception { long num = (long) atLeast(10); for (long i=0; i < num; i++) { executeOneRandomSplit(random()); } } private void executeOneRandomSplit(final Random random) throws Exception { long lower = randomLong(random); long len = random.nextInt(16384*1024); // not too large bitsets, else OOME! while (lower + len < lower) { // overflow lower >>= 1; } assertLongRangeSplit(lower, lower + len, random.nextInt(64) + 1, true, null, null); } private long randomLong(final Random random) { long val; switch(random.nextInt(4)) { case 0: val = 1L << (random.nextInt(63)); // patterns like 0x000000100000 (-1 yields patterns like 0x0000fff) break; case 1: val = -1L << (random.nextInt(63)); // patterns like 0xfffff00000 break; default: val = random.nextLong(); } val += random.nextInt(5)-2; if (random.nextBoolean()) { if (random.nextBoolean()) val += random.nextInt(100)-50; if (random.nextBoolean()) val = ~val; if (random.nextBoolean()) val = val<<1; if (random.nextBoolean()) val = val>>>1; } return val; } public void testSplitLongRange() throws Exception { // a hard-coded "standard" range assertLongRangeSplit(-5000L, 9500L, 4, true, Arrays.asList( 0x7fffffffffffec78L,0x7fffffffffffec7fL, 0x8000000000002510L,0x800000000000251cL, 0x7fffffffffffec8L, 0x7fffffffffffecfL, 0x800000000000250L, 0x800000000000250L, 0x7fffffffffffedL, 0x7fffffffffffefL, 0x80000000000020L, 0x80000000000024L, 0x7ffffffffffffL, 0x8000000000001L ), Arrays.asList( 0, 0, 4, 4, 8, 8, 12 )); // the same with no range splitting assertLongRangeSplit(-5000L, 9500L, 64, true, Arrays.asList( 0x7fffffffffffec78L,0x800000000000251cL ), Arrays.asList( 0 )); // this tests optimized range splitting, if one of the inner bounds // is also the bound of the next lower precision, it should be used completely assertLongRangeSplit(0L, 1024L+63L, 4, true, Arrays.asList( 0x800000000000040L, 0x800000000000043L, 0x80000000000000L, 0x80000000000003L ), Arrays.asList( 4, 8 )); // the full long range should only consist of a lowest precision range; no bitset testing here, as too much memory needed :-) assertLongRangeSplit(Long.MIN_VALUE, Long.MAX_VALUE, 8, false, Arrays.asList( 0x00L,0xffL ), Arrays.asList( 56 )); // the same with precisionStep=4 assertLongRangeSplit(Long.MIN_VALUE, Long.MAX_VALUE, 4, false, Arrays.asList( 0x0L,0xfL ), Arrays.asList( 60 )); // the same with precisionStep=2 assertLongRangeSplit(Long.MIN_VALUE, Long.MAX_VALUE, 2, false, Arrays.asList( 0x0L,0x3L ), Arrays.asList( 62 )); // the same with precisionStep=1 assertLongRangeSplit(Long.MIN_VALUE, Long.MAX_VALUE, 1, false, Arrays.asList( 0x0L,0x1L ), Arrays.asList( 63 )); // a inverse range should produce no sub-ranges assertLongRangeSplit(9500L, -5000L, 4, false, Collections.<Long>emptyList(), Collections.<Integer>emptyList()); - // a 0-length range should reproduce the range itsself + // a 0-length range should reproduce the range itself assertLongRangeSplit(9500L, 9500L, 4, false, Arrays.asList( 0x800000000000251cL,0x800000000000251cL ), Arrays.asList( 0 )); } /** Note: The neededBounds Iterable must be unsigned (easier understanding what's happening) */ private void assertIntRangeSplit(final int lower, final int upper, int precisionStep, final boolean useBitSet, final Iterable<Integer> expectedBounds, final Iterable<Integer> expectedShifts ) { final FixedBitSet bits=useBitSet ? new FixedBitSet(upper-lower+1) : null; final Iterator<Integer> neededBounds = (expectedBounds == null) ? null : expectedBounds.iterator(); final Iterator<Integer> neededShifts = (expectedShifts == null) ? null : expectedShifts.iterator(); NumericUtils.splitIntRange(new NumericUtils.IntRangeBuilder() { @Override public void addRange(int min, int max, int shift) { assertTrue("min, max should be inside bounds", min>=lower && min<=upper && max>=lower && max<=upper); if (useBitSet) for (int i=min; i<=max; i++) { assertFalse("ranges should not overlap", bits.getAndSet(i-lower) ); // extra exit condition to prevent overflow on MAX_VALUE if (i == max) break; } if (neededBounds == null) return; // make unsigned ints for easier display and understanding min ^= 0x80000000; max ^= 0x80000000; //System.out.println("0x"+Integer.toHexString(min>>>shift)+",0x"+Integer.toHexString(max>>>shift)+")/*shift="+shift+"*/,"); assertEquals( "shift", neededShifts.next().intValue(), shift); assertEquals( "inner min bound", neededBounds.next().intValue(), min>>>shift); assertEquals( "inner max bound", neededBounds.next().intValue(), max>>>shift); } }, precisionStep, lower, upper); if (useBitSet) { // after flipping all bits in the range, the cardinality should be zero bits.flip(0, upper-lower+1); assertEquals("The sub-range concenated should match the whole range", 0, bits.cardinality()); } } public void testSplitIntRange() throws Exception { // a hard-coded "standard" range assertIntRangeSplit(-5000, 9500, 4, true, Arrays.asList( 0x7fffec78,0x7fffec7f, 0x80002510,0x8000251c, 0x7fffec8, 0x7fffecf, 0x8000250, 0x8000250, 0x7fffed, 0x7fffef, 0x800020, 0x800024, 0x7ffff, 0x80001 ), Arrays.asList( 0, 0, 4, 4, 8, 8, 12 )); // the same with no range splitting assertIntRangeSplit(-5000, 9500, 32, true, Arrays.asList( 0x7fffec78,0x8000251c ), Arrays.asList( 0 )); // this tests optimized range splitting, if one of the inner bounds // is also the bound of the next lower precision, it should be used completely assertIntRangeSplit(0, 1024+63, 4, true, Arrays.asList( 0x8000040, 0x8000043, 0x800000, 0x800003 ), Arrays.asList( 4, 8 )); // the full int range should only consist of a lowest precision range; no bitset testing here, as too much memory needed :-) assertIntRangeSplit(Integer.MIN_VALUE, Integer.MAX_VALUE, 8, false, Arrays.asList( 0x00,0xff ), Arrays.asList( 24 )); // the same with precisionStep=4 assertIntRangeSplit(Integer.MIN_VALUE, Integer.MAX_VALUE, 4, false, Arrays.asList( 0x0,0xf ), Arrays.asList( 28 )); // the same with precisionStep=2 assertIntRangeSplit(Integer.MIN_VALUE, Integer.MAX_VALUE, 2, false, Arrays.asList( 0x0,0x3 ), Arrays.asList( 30 )); // the same with precisionStep=1 assertIntRangeSplit(Integer.MIN_VALUE, Integer.MAX_VALUE, 1, false, Arrays.asList( 0x0,0x1 ), Arrays.asList( 31 )); // a inverse range should produce no sub-ranges assertIntRangeSplit(9500, -5000, 4, false, Collections.<Integer>emptyList(), Collections.<Integer>emptyList()); - // a 0-length range should reproduce the range itsself + // a 0-length range should reproduce the range itself assertIntRangeSplit(9500, 9500, 4, false, Arrays.asList( 0x8000251c,0x8000251c ), Arrays.asList( 0 )); } }
false
false
null
null
diff --git a/code/src/presenter/model/Presentation.java b/code/src/presenter/model/Presentation.java index bb87999..83ec2eb 100644 --- a/code/src/presenter/model/Presentation.java +++ b/code/src/presenter/model/Presentation.java @@ -1,56 +1,58 @@ package presenter.model; import java.util.ArrayList; import java.util.List; public class Presentation { // ############ STATICS ############ private static Presentation instance = null; private static void getInstance() { if (null == instance) instance = new Presentation(); } public static void open(String path) { getInstance(); } public static void create() { getInstance(); } public static Slide next() { return get(++instance.index); } public static Slide getCurrent() { return get(instance.index); } public static Slide previous() { return get(--instance.index); } public static Slide get(int index) { + index = (index % instance.slides.size() + instance.slides.size()) + % instance.slides.size(); return instance.slides.get(index); } public static List<Slide> getSlides() { return instance.slides; } public static PresentationEditor getEditor() { return new PresentationEditor(instance.slides); } // ########## NON-STATICS ########## private List<Slide> slides; private int index = 0; public Presentation() { slides = new ArrayList<Slide>(); } } diff --git a/code/src/presenter/model/PresentationEditor.java b/code/src/presenter/model/PresentationEditor.java index a6966c9..202e65d 100644 --- a/code/src/presenter/model/PresentationEditor.java +++ b/code/src/presenter/model/PresentationEditor.java @@ -1,93 +1,95 @@ package presenter.model; import java.io.File; import java.util.List; import org.jpedal.PdfDecoder; import org.jpedal.exception.PdfException; public class PresentationEditor { private List<Slide> presentation; public PresentationEditor(List<Slide> slides) { presentation = slides; } public void add(File file) { if (file.getName().toLowerCase().matches(".*\\.jpe?g")) loadPhoto(file); else if (file.getName().toLowerCase().endsWith(".pdf")) loadFromPdf(file); else if (file.getName().toLowerCase().endsWith(".xml")) loadFromXml(file); } public void add(List<File> files) { for(File current : files) add(current); } public void add(Slide slide) { } public void moveUp(Slide slide) { moveToPosition(slide, presentation.indexOf(slide) - 1); } public void moveDown(Slide slide) { moveToPosition(slide, presentation.indexOf(slide) + 1); } private void moveToPosition(Slide slide, int position) { + position = (position % presentation.size() + presentation.size()) + % presentation.size(); remove(slide); presentation.add(position, slide); } public void remove(Slide slide) { presentation.remove(slide); } private void loadPhoto(File file) { presentation.add(new PhotoSlide(file)); } public void loadFromPdf(File file) { loadFromPdf(file, false); } public void loadFromPdf(File file, boolean useEverySecondPageAsNotes) { try { PdfDecoder decoder = new PdfDecoder(); decoder.openPdfFile(file.getAbsolutePath()); for (int i = 1; i < decoder.getPageCount(); i++) { Slide slide = new PdfSlide(file, i); presentation.add(slide); if (useEverySecondPageAsNotes) slide.addNotes(new PdfNotes(file, ++i)); } } catch (PdfException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void loadFromXml(File file) { System.out.println("presentator file"); // SAXBuilder builder = new SAXBuilder(); // try { // Element root = builder.build(new File(path)).getRootElement(); // for (Object current : root.getChildren()) // slides.add(new Slide((Element) current)); // } catch (JDOMException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } }
false
false
null
null
diff --git a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/jobmanager/JobManager.java b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/jobmanager/JobManager.java index 07fb73bc8..738dff529 100644 --- a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/jobmanager/JobManager.java +++ b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/jobmanager/JobManager.java @@ -1,1373 +1,1375 @@ /*********************************************************************************************************************** * * Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu) * * 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. * **********************************************************************************************************************/ /** * 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 eu.stratosphere.nephele.jobmanager; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import eu.stratosphere.nephele.client.AbstractJobResult; import eu.stratosphere.nephele.client.JobCancelResult; import eu.stratosphere.nephele.client.JobProgressResult; import eu.stratosphere.nephele.client.JobSubmissionResult; import eu.stratosphere.nephele.client.AbstractJobResult.ReturnCode; import eu.stratosphere.nephele.configuration.ConfigConstants; import eu.stratosphere.nephele.configuration.GlobalConfiguration; import eu.stratosphere.nephele.deployment.TaskDeploymentDescriptor; import eu.stratosphere.nephele.discovery.DiscoveryException; import eu.stratosphere.nephele.discovery.DiscoveryService; import eu.stratosphere.nephele.event.job.AbstractEvent; import eu.stratosphere.nephele.event.job.RecentJobEvent; import eu.stratosphere.nephele.execution.ExecutionState; import eu.stratosphere.nephele.execution.librarycache.LibraryCacheManager; import eu.stratosphere.nephele.executiongraph.ExecutionEdge; import eu.stratosphere.nephele.executiongraph.ExecutionGraph; import eu.stratosphere.nephele.executiongraph.ExecutionGraphIterator; import eu.stratosphere.nephele.executiongraph.ExecutionVertex; import eu.stratosphere.nephele.executiongraph.ExecutionVertexID; import eu.stratosphere.nephele.executiongraph.GraphConversionException; import eu.stratosphere.nephele.executiongraph.InternalJobStatus; import eu.stratosphere.nephele.executiongraph.JobStatusListener; import eu.stratosphere.nephele.instance.AbstractInstance; import eu.stratosphere.nephele.instance.AllocatedResource; import eu.stratosphere.nephele.instance.DummyInstance; import eu.stratosphere.nephele.instance.HardwareDescription; import eu.stratosphere.nephele.instance.InstanceConnectionInfo; import eu.stratosphere.nephele.instance.InstanceManager; import eu.stratosphere.nephele.instance.InstanceType; import eu.stratosphere.nephele.instance.InstanceTypeDescription; import eu.stratosphere.nephele.instance.local.LocalInstanceManager; import eu.stratosphere.nephele.io.IOReadableWritable; import eu.stratosphere.nephele.io.channels.ChannelID; import eu.stratosphere.nephele.jobgraph.AbstractJobVertex; import eu.stratosphere.nephele.jobgraph.JobGraph; import eu.stratosphere.nephele.jobgraph.JobID; import eu.stratosphere.nephele.jobmanager.scheduler.AbstractScheduler; import eu.stratosphere.nephele.jobmanager.scheduler.SchedulingException; import eu.stratosphere.nephele.jobmanager.splitassigner.InputSplitManager; import eu.stratosphere.nephele.jobmanager.splitassigner.InputSplitWrapper; import eu.stratosphere.nephele.managementgraph.ManagementGraph; import eu.stratosphere.nephele.managementgraph.ManagementVertexID; import eu.stratosphere.nephele.multicast.MulticastManager; import eu.stratosphere.nephele.plugins.JobManagerPlugin; import eu.stratosphere.nephele.plugins.PluginID; import eu.stratosphere.nephele.plugins.PluginManager; import eu.stratosphere.nephele.profiling.JobManagerProfiler; import eu.stratosphere.nephele.profiling.ProfilingListener; import eu.stratosphere.nephele.profiling.ProfilingUtils; import eu.stratosphere.nephele.protocols.ChannelLookupProtocol; import eu.stratosphere.nephele.protocols.ExtendedManagementProtocol; import eu.stratosphere.nephele.protocols.InputSplitProviderProtocol; import eu.stratosphere.nephele.protocols.JobManagementProtocol; import eu.stratosphere.nephele.protocols.JobManagerProtocol; import eu.stratosphere.nephele.protocols.PluginCommunicationProtocol; import eu.stratosphere.nephele.rpc.RPCService; import eu.stratosphere.nephele.taskmanager.AbstractTaskResult; import eu.stratosphere.nephele.taskmanager.TaskCancelResult; import eu.stratosphere.nephele.taskmanager.TaskCheckpointState; import eu.stratosphere.nephele.taskmanager.TaskExecutionState; import eu.stratosphere.nephele.taskmanager.TaskKillResult; import eu.stratosphere.nephele.taskmanager.TaskSubmissionResult; import eu.stratosphere.nephele.taskmanager.bytebuffered.ConnectionInfoLookupResponse; import eu.stratosphere.nephele.taskmanager.bytebuffered.RemoteReceiver; import eu.stratosphere.nephele.topology.NetworkTopology; import eu.stratosphere.nephele.types.IntegerRecord; import eu.stratosphere.nephele.types.StringRecord; import eu.stratosphere.nephele.util.SerializableArrayList; import eu.stratosphere.nephele.util.StringUtils; /** * In Nephele the job manager is the central component for communication with clients, creating * schedules for incoming jobs and supervise their execution. A job manager may only exist once in * the system and its address must be known the clients. * Task managers can discover the job manager by means of an UDP broadcast and afterwards advertise * themselves as new workers for tasks. * * @author warneke */ public class JobManager implements DeploymentManager, ExtendedManagementProtocol, InputSplitProviderProtocol, JobManagerProtocol, ChannelLookupProtocol, JobStatusListener, PluginCommunicationProtocol { private static final Log LOG = LogFactory.getLog(JobManager.class); private final RPCService rpcService; private final JobManagerProfiler profiler; private final EventCollector eventCollector; private final InputSplitManager inputSplitManager; private final AbstractScheduler scheduler; private final MulticastManager multicastManager; private InstanceManager instanceManager; private final Map<PluginID, JobManagerPlugin> jobManagerPlugins; private final int recommendedClientPollingInterval; private final ExecutorService executorService = Executors.newCachedThreadPool(); private final static int SLEEPINTERVAL = 1000; private final static int FAILURERETURNCODE = -1; private final AtomicBoolean isShutdownInProgress = new AtomicBoolean(false); private volatile boolean isShutDown = false; /** * Constructs a new job manager, starts its discovery service and its IPC service. */ public JobManager(final String configDir, final String executionMode) { // First, try to load global configuration GlobalConfiguration.loadConfiguration(configDir); final String ipcAddressString = GlobalConfiguration .getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, null); InetAddress ipcAddress = null; if (ipcAddressString != null) { try { ipcAddress = InetAddress.getByName(ipcAddressString); } catch (UnknownHostException e) { LOG.fatal("Cannot convert " + ipcAddressString + " to an IP address: " + StringUtils.stringifyException(e)); System.exit(FAILURERETURNCODE); } } final int ipcPort = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, ConfigConstants.DEFAULT_JOB_MANAGER_IPC_PORT); // First of all, start discovery manager try { DiscoveryService.startDiscoveryService(ipcAddress, ipcPort); } catch (DiscoveryException e) { LOG.fatal("Cannot start discovery manager: " + StringUtils.stringifyException(e)); System.exit(FAILURERETURNCODE); } // Read the suggested client polling interval this.recommendedClientPollingInterval = GlobalConfiguration.getInteger("jobclient.polling.internval", 5); // Load the job progress collector this.eventCollector = new EventCollector(this.recommendedClientPollingInterval); // Load the input split manager this.inputSplitManager = new InputSplitManager(); // Determine own RPC address final InetSocketAddress rpcServerAddress = new InetSocketAddress(ipcAddress, ipcPort); // Start job manager's RPC server RPCService rpcService = null; try { rpcService = new RPCService(rpcServerAddress.getPort()); } catch (IOException ioe) { LOG.fatal("Cannot start RPC server: " + StringUtils.stringifyException(ioe)); System.exit(FAILURERETURNCODE); } this.rpcService = rpcService; // Add callback handlers to the RPC service - this.rpcService.setProtocolCallbackHandler(JobManagerProtocol.class, this); - this.rpcService.setProtocolCallbackHandler(JobManagementProtocol.class, this); this.rpcService.setProtocolCallbackHandler(ChannelLookupProtocol.class, this); + this.rpcService.setProtocolCallbackHandler(ExtendedManagementProtocol.class, this); + this.rpcService.setProtocolCallbackHandler(InputSplitProviderProtocol.class, this); + this.rpcService.setProtocolCallbackHandler(JobManagementProtocol.class, this); + this.rpcService.setProtocolCallbackHandler(JobManagerProtocol.class, this); LOG.info("Starting job manager in " + executionMode + " mode"); // Load the plugins this.jobManagerPlugins = PluginManager.getJobManagerPlugins(this, configDir); // Try to load the instance manager for the given execution mode // Try to load the scheduler for the given execution mode if ("local".equals(executionMode)) { try { this.instanceManager = new LocalInstanceManager(configDir, this.rpcService); } catch (RuntimeException rte) { LOG.fatal("Cannot instantiate local instance manager: " + StringUtils.stringifyException(rte)); System.exit(FAILURERETURNCODE); } } else { final String instanceManagerClassName = JobManagerUtils.getInstanceManagerClassName(executionMode); LOG.info("Trying to load " + instanceManagerClassName + " as instance manager"); this.instanceManager = JobManagerUtils.loadInstanceManager(instanceManagerClassName); if (this.instanceManager == null) { LOG.fatal("Unable to load instance manager " + instanceManagerClassName); System.exit(FAILURERETURNCODE); } } // Try to load the scheduler for the given execution mode final String schedulerClassName = JobManagerUtils.getSchedulerClassName(executionMode); LOG.info("Trying to load " + schedulerClassName + " as scheduler"); // Try to get the instance manager class name this.scheduler = JobManagerUtils.loadScheduler(schedulerClassName, this, this.instanceManager); if (this.scheduler == null) { LOG.fatal("Unable to load scheduler " + schedulerClassName); System.exit(FAILURERETURNCODE); } // Create multicastManager this.multicastManager = new MulticastManager(this.scheduler); // Load profiler if it should be used if (GlobalConfiguration.getBoolean(ProfilingUtils.ENABLE_PROFILING_KEY, false)) { final String profilerClassName = GlobalConfiguration.getString(ProfilingUtils.JOBMANAGER_CLASSNAME_KEY, null); if (profilerClassName == null) { LOG.fatal("Cannot find class name for the profiler"); System.exit(FAILURERETURNCODE); } this.profiler = ProfilingUtils.loadJobManagerProfiler(profilerClassName, ipcAddress); if (this.profiler == null) { LOG.fatal("Cannot load profiler"); System.exit(FAILURERETURNCODE); } } else { this.profiler = null; LOG.debug("Profiler disabled"); } // Add shutdown hook for clean up tasks Runtime.getRuntime().addShutdownHook(new JobManagerCleanUp(this)); } /** * This is the main */ public void runTaskLoop() { while (!Thread.interrupted()) { // Sleep try { Thread.sleep(SLEEPINTERVAL); } catch (InterruptedException e) { break; } // Do nothing here } } public void shutdown() { if (!this.isShutdownInProgress.compareAndSet(false, true)) { return; } // Stop instance manager if (this.instanceManager != null) { this.instanceManager.shutdown(); } // Stop the discovery service DiscoveryService.stopDiscoveryService(); // Stop profiling if enabled if (this.profiler != null) { this.profiler.shutdown(); } // Stop RPC service if (this.rpcService != null) { this.rpcService.shutDown(); } // Stop the executor service if (this.executorService != null) { this.executorService.shutdown(); try { this.executorService.awaitTermination(5000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { if (LOG.isDebugEnabled()) { LOG.debug(StringUtils.stringifyException(e)); } } } // Stop the plugins final Iterator<JobManagerPlugin> it = this.jobManagerPlugins.values().iterator(); while (it.hasNext()) { it.next().shutdown(); } // Stop and clean up the job progress collector if (this.eventCollector != null) { this.eventCollector.shutdown(); } // Finally, shut down the scheduler if (this.scheduler != null) { this.scheduler.shutdown(); } this.isShutDown = true; LOG.debug("Shutdown of job manager completed"); } /** * Entry point for the program * * @param args * arguments from the command line */ @SuppressWarnings("static-access") public static void main(final String[] args) { final Option configDirOpt = OptionBuilder.withArgName("config directory").hasArg() .withDescription("Specify configuration directory.").create("configDir"); final Option executionModeOpt = OptionBuilder.withArgName("execution mode").hasArg() .withDescription("Specify execution mode.").create("executionMode"); final Options options = new Options(); options.addOption(configDirOpt); options.addOption(executionModeOpt); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { LOG.error("CLI Parsing failed. Reason: " + e.getMessage()); System.exit(FAILURERETURNCODE); } final String configDir = line.getOptionValue(configDirOpt.getOpt(), null); final String executionMode = line.getOptionValue(executionModeOpt.getOpt(), "local"); // Create a new job manager object JobManager jobManager = new JobManager(configDir, executionMode); // Run the main task loop jobManager.runTaskLoop(); // Clean up task are triggered through a shutdown hook } /** * {@inheritDoc} */ @Override public JobSubmissionResult submitJob(JobGraph job) throws IOException { // First check if job is null if (job == null) { JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, "Submitted job is null!"); return result; } if (LOG.isDebugEnabled()) { LOG.debug("Submitted job " + job.getName() + " is not null"); } // Check if any vertex of the graph has null edges AbstractJobVertex jv = job.findVertexWithNullEdges(); if (jv != null) { JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, "Vertex " + jv.getName() + " has at least one null edge"); return result; } if (LOG.isDebugEnabled()) { LOG.debug("Submitted job " + job.getName() + " has no null edges"); } // Next, check if the graph is weakly connected if (!job.isWeaklyConnected()) { JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, "Job graph is not weakly connected"); return result; } if (LOG.isDebugEnabled()) { LOG.debug("The graph of job " + job.getName() + " is weakly connected"); } // Check if job graph has cycles if (!job.isAcyclic()) { JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, "Job graph is not a DAG"); return result; } if (LOG.isDebugEnabled()) { LOG.debug("The graph of job " + job.getName() + " is acyclic"); } // Check constrains on degree jv = job.areVertexDegreesCorrect(); if (jv != null) { JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, "Degree of vertex " + jv.getName() + " is incorrect"); return result; } if (LOG.isDebugEnabled()) { LOG.debug("All vertices of job " + job.getName() + " have the correct degree"); } if (!job.isInstanceDependencyChainAcyclic()) { JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, "The dependency chain for instance sharing contains a cycle"); return result; } if (LOG.isDebugEnabled()) { LOG.debug("The dependency chain for instance sharing is acyclic"); } // Check if the job will be executed with profiling enabled boolean jobRunsWithProfiling = false; if (this.profiler != null && job.getJobConfiguration().getBoolean(ProfilingUtils.PROFILE_JOB_KEY, true)) { jobRunsWithProfiling = true; } // Allow plugins to rewrite the job graph Iterator<JobManagerPlugin> it = this.jobManagerPlugins.values().iterator(); while (it.hasNext()) { final JobManagerPlugin plugin = it.next(); if (plugin.requiresProfiling() && !jobRunsWithProfiling) { LOG.debug("Skipping job graph rewrite by plugin " + plugin + " because job " + job.getJobID() + " will not be executed with profiling"); continue; } final JobGraph inputJob = job; job = plugin.rewriteJobGraph(inputJob); if (job == null) { if (LOG.isWarnEnabled()) { LOG.warn("Plugin " + plugin + " set job graph to null, reverting changes..."); } job = inputJob; } if (job != inputJob && LOG.isDebugEnabled()) { LOG.debug("Plugin " + plugin + " rewrote job graph"); } } // Try to create initial execution graph from job graph LOG.info("Creating initial execution graph from job graph " + job.getName()); ExecutionGraph eg = null; try { eg = new ExecutionGraph(job, this.instanceManager); } catch (GraphConversionException gce) { JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, gce.getMessage()); return result; } // Allow plugins to rewrite the execution graph it = this.jobManagerPlugins.values().iterator(); while (it.hasNext()) { final JobManagerPlugin plugin = it.next(); if (plugin.requiresProfiling() && !jobRunsWithProfiling) { LOG.debug("Skipping execution graph rewrite by plugin " + plugin + " because job " + job.getJobID() + " will not be executed with profiling"); continue; } final ExecutionGraph inputGraph = eg; eg = plugin.rewriteExecutionGraph(inputGraph); if (eg == null) { LOG.warn("Plugin " + plugin + " set execution graph to null, reverting changes..."); eg = inputGraph; } if (eg != inputGraph) { LOG.debug("Plugin " + plugin + " rewrote execution graph"); } } // Register job with the progress collector if (this.eventCollector != null) { this.eventCollector.registerJob(eg, jobRunsWithProfiling, System.currentTimeMillis()); } // Check if profiling should be enabled for this job if (jobRunsWithProfiling) { this.profiler.registerProfilingJob(eg); if (this.eventCollector != null) { this.profiler.registerForProfilingData(eg.getJobID(), this.eventCollector); } // Allow plugins to register their own profiling listeners for the job it = this.jobManagerPlugins.values().iterator(); while (it.hasNext()) { final ProfilingListener listener = it.next().getProfilingListener(eg.getJobID()); if (listener != null) { this.profiler.registerForProfilingData(eg.getJobID(), listener); } } } // Register job with the dynamic input split assigner this.inputSplitManager.registerJob(eg); // Register for updates on the job status eg.registerJobStatusListener(this); // Schedule job if (LOG.isInfoEnabled()) { LOG.info("Scheduling job " + job.getName()); } try { this.scheduler.schedulJob(eg); } catch (SchedulingException e) { unregisterJob(eg); JobSubmissionResult result = new JobSubmissionResult(AbstractJobResult.ReturnCode.ERROR, e.getMessage()); return result; } // Return on success return new JobSubmissionResult(AbstractJobResult.ReturnCode.SUCCESS, null); } /** * This method is a convenience method to unregister a job from all of * Nephele's monitoring, profiling and optimization components at once. * Currently, it is only being used to unregister from profiling (if activated). * * @param executionGraph * the execution graph to remove from the job manager */ private void unregisterJob(final ExecutionGraph executionGraph) { // Remove job from profiler (if activated) if (this.profiler != null && executionGraph.getJobConfiguration().getBoolean(ProfilingUtils.PROFILE_JOB_KEY, true)) { this.profiler.unregisterProfilingJob(executionGraph); if (this.eventCollector != null) { this.profiler.unregisterFromProfilingData(executionGraph.getJobID(), this.eventCollector); } } // Cancel all pending requests for instances this.instanceManager.cancelPendingRequests(executionGraph.getJobID()); // getJobID is final member, no // synchronization necessary // Remove job from input split manager if (this.inputSplitManager != null) { this.inputSplitManager.unregisterJob(executionGraph); } // Remove all the checkpoints of the job removeAllCheckpoints(executionGraph); // Unregister job with library cache manager try { LibraryCacheManager.unregister(executionGraph.getJobID()); } catch (IOException ioe) { if (LOG.isWarnEnabled()) { LOG.warn(StringUtils.stringifyException(ioe)); } } } /** * {@inheritDoc} */ @Override public void sendHeartbeat(final InstanceConnectionInfo instanceConnectionInfo, final HardwareDescription hardwareDescription) { // Delegate call to instance manager if (this.instanceManager != null) { final Runnable heartBeatRunnable = new Runnable() { @Override public void run() { instanceManager.reportHeartBeat(instanceConnectionInfo, hardwareDescription); } }; this.executorService.execute(heartBeatRunnable); } } /** * {@inheritDoc} */ @Override public void updateTaskExecutionState(final TaskExecutionState executionState) throws IOException { // Ignore calls with executionResult == null if (executionState == null) { LOG.error("Received call to updateTaskExecutionState with executionState == null"); return; } final ExecutionGraph eg = this.scheduler.getExecutionGraphByID(executionState.getJobID()); if (eg == null) { LOG.error("Cannot find execution graph for ID " + executionState.getJobID() + " to change state to " + executionState.getExecutionState()); return; } final ExecutionVertex vertex = eg.getVertexByID(executionState.getID()); if (vertex == null) { LOG.error("Cannot find vertex with ID " + executionState.getID() + " of job " + eg.getJobID() + " to change state to " + executionState.getExecutionState()); return; } // Asynchronously update execute state of vertex vertex.updateExecutionStateAsynchronously(executionState.getExecutionState(), executionState.getDescription()); } /** * {@inheritDoc} */ @Override public JobCancelResult cancelJob(final JobID jobID) throws IOException { LOG.info("Trying to cancel job with ID " + jobID); final ExecutionGraph eg = this.scheduler.getExecutionGraphByID(jobID); if (eg == null) { return new JobCancelResult(ReturnCode.ERROR, "Cannot find job with ID " + jobID); } final Runnable cancelJobRunnable = new Runnable() { @Override public void run() { eg.updateJobStatus(InternalJobStatus.CANCELING, "Job canceled by user"); final TaskCancelResult cancelResult = cancelJob(eg); if (cancelResult != null) { LOG.error(cancelResult.getDescription()); } } }; eg.executeCommand(cancelJobRunnable); LOG.info("Cancel of job " + jobID + " successfully triggered"); return new JobCancelResult(AbstractJobResult.ReturnCode.SUCCESS, null); } /** * Cancels all the tasks in the current and upper stages of the * given execution graph. * * @param eg * the execution graph representing the job to cancel. * @return <code>null</code> if no error occurred during the cancel attempt, * otherwise the returned object will describe the error */ private TaskCancelResult cancelJob(final ExecutionGraph eg) { TaskCancelResult errorResult = null; /** * Cancel all nodes in the current and upper execution stages. */ final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(eg, eg.getIndexOfCurrentExecutionStage(), false, true); while (it.hasNext()) { final ExecutionVertex vertex = it.next(); final TaskCancelResult result = vertex.cancelTask(); if (result.getReturnCode() != AbstractTaskResult.ReturnCode.SUCCESS) { errorResult = result; } } return errorResult; } /** * {@inheritDoc} */ @Override public JobProgressResult getJobProgress(final JobID jobID) throws IOException { if (this.eventCollector == null) { return new JobProgressResult(ReturnCode.ERROR, "JobManager does not support progress reports for jobs", null); } final ArrayList<AbstractEvent> eventList = new ArrayList<AbstractEvent>(); this.eventCollector.getEventsForJob(jobID, eventList, false); return new JobProgressResult(ReturnCode.SUCCESS, null, eventList); } /** * {@inheritDoc} */ @Override public ConnectionInfoLookupResponse lookupConnectionInfo(final InstanceConnectionInfo caller, final JobID jobID, final ChannelID sourceChannelID) { final ExecutionGraph eg = this.scheduler.getExecutionGraphByID(jobID); if (eg == null) { LOG.error("Cannot find execution graph to job ID " + jobID); return ConnectionInfoLookupResponse.createReceiverNotFound(); } final InternalJobStatus jobStatus = eg.getJobStatus(); if (jobStatus == InternalJobStatus.FAILING || jobStatus == InternalJobStatus.CANCELING) { return ConnectionInfoLookupResponse.createJobIsAborting(); } final ExecutionEdge edge = eg.getEdgeByID(sourceChannelID); if (edge == null) { LOG.error("Cannot find execution edge associated with ID " + sourceChannelID); return ConnectionInfoLookupResponse.createReceiverNotFound(); } if (sourceChannelID.equals(edge.getInputChannelID())) { // Request was sent from an input channel final ExecutionVertex connectedVertex = edge.getOutputGate().getVertex(); final AbstractInstance assignedInstance = connectedVertex.getAllocatedResource().getInstance(); if (assignedInstance == null) { LOG.error("Cannot resolve lookup: vertex found for channel ID " + edge.getOutputGateIndex() + " but no instance assigned"); // LOG.info("Created receiverNotReady for " + connectedVertex + " 1"); return ConnectionInfoLookupResponse.createReceiverNotReady(); } // Check execution state final ExecutionState executionState = connectedVertex.getExecutionState(); if (executionState == ExecutionState.FINISHED) { return ConnectionInfoLookupResponse.createReceiverFoundAndReady(); } if (executionState != ExecutionState.RUNNING && executionState != ExecutionState.REPLAYING && executionState != ExecutionState.FINISHING) { // LOG.info("Created receiverNotReady for " + connectedVertex + " in state " + executionState + " 2"); return ConnectionInfoLookupResponse.createReceiverNotReady(); } if (assignedInstance.getInstanceConnectionInfo().equals(caller)) { // Receiver runs on the same task manager return ConnectionInfoLookupResponse.createReceiverFoundAndReady(edge.getOutputChannelID()); } else { // Receiver runs on a different task manager final InstanceConnectionInfo ici = assignedInstance.getInstanceConnectionInfo(); final InetSocketAddress isa = new InetSocketAddress(ici.getAddress(), ici.getDataPort()); return ConnectionInfoLookupResponse.createReceiverFoundAndReady(new RemoteReceiver(isa, edge .getConnectionID())); } } if (edge.isBroadcast()) { return multicastManager.lookupConnectionInfo(caller, jobID, sourceChannelID); } else { // Find vertex of connected input channel final ExecutionVertex targetVertex = edge.getInputGate().getVertex(); // Check execution state final ExecutionState executionState = targetVertex.getExecutionState(); if (executionState != ExecutionState.RUNNING && executionState != ExecutionState.REPLAYING && executionState != ExecutionState.FINISHING && executionState != ExecutionState.FINISHED) { if (executionState == ExecutionState.ASSIGNED) { final Runnable command = new Runnable() { /** * {@inheritDoc} */ @Override public void run() { scheduler.deployAssignedVertices(targetVertex); } }; eg.executeCommand(command); } // LOG.info("Created receiverNotReady for " + targetVertex + " in state " + executionState + " 3"); return ConnectionInfoLookupResponse.createReceiverNotReady(); } final AbstractInstance assignedInstance = targetVertex.getAllocatedResource().getInstance(); if (assignedInstance == null) { LOG.error("Cannot resolve lookup: vertex found for channel ID " + edge.getInputChannelID() + " but no instance assigned"); // LOG.info("Created receiverNotReady for " + targetVertex + " in state " + executionState + " 4"); return ConnectionInfoLookupResponse.createReceiverNotReady(); } if (assignedInstance.getInstanceConnectionInfo().equals(caller)) { // Receiver runs on the same task manager return ConnectionInfoLookupResponse.createReceiverFoundAndReady(edge.getInputChannelID()); } else { // Receiver runs on a different task manager final InstanceConnectionInfo ici = assignedInstance.getInstanceConnectionInfo(); final InetSocketAddress isa = new InetSocketAddress(ici.getAddress(), ici.getDataPort()); return ConnectionInfoLookupResponse.createReceiverFoundAndReady(new RemoteReceiver(isa, edge .getConnectionID())); } } // LOG.error("Receiver(s) not found"); // return ConnectionInfoLookupResponse.createReceiverNotFound(); } /** * {@inheritDoc} */ @Override public ManagementGraph getManagementGraph(final JobID jobID) throws IOException { final ManagementGraph mg = this.eventCollector.getManagementGraph(jobID); if (mg == null) { throw new IOException("Cannot find job with ID " + jobID); } return mg; } /** * {@inheritDoc} */ @Override public NetworkTopology getNetworkTopology(final JobID jobID) throws IOException { if (this.instanceManager != null) { return this.instanceManager.getNetworkTopology(jobID); } return null; } /** * {@inheritDoc} */ @Override public IntegerRecord getRecommendedPollingInterval() throws IOException { return new IntegerRecord(this.recommendedClientPollingInterval); } /** * {@inheritDoc} */ @Override public List<RecentJobEvent> getRecentJobs() throws IOException { final List<RecentJobEvent> eventList = new ArrayList<RecentJobEvent>(); if (this.eventCollector == null) { throw new IOException("No instance of the event collector found"); } this.eventCollector.getRecentJobs(eventList); return eventList; } /** * {@inheritDoc} */ @Override public List<AbstractEvent> getEvents(final JobID jobID) throws IOException { final List<AbstractEvent> eventList = new ArrayList<AbstractEvent>(); if (this.eventCollector == null) { throw new IOException("No instance of the event collector found"); } this.eventCollector.getEventsForJob(jobID, eventList, true); return eventList; } /** * {@inheritDoc} */ @Override public void killTask(final JobID jobID, final ManagementVertexID id) throws IOException { final ExecutionGraph eg = this.scheduler.getExecutionGraphByID(jobID); if (eg == null) { LOG.error("Cannot find execution graph for job " + jobID); return; } final ExecutionVertex vertex = eg.getVertexByID(ExecutionVertexID.fromManagementVertexID(id)); if (vertex == null) { LOG.error("Cannot find execution vertex with ID " + id); return; } LOG.info("Killing task " + vertex + " of job " + jobID); final Runnable runnable = new Runnable() { @Override public void run() { final TaskKillResult result = vertex.killTask(); if (result.getReturnCode() != AbstractTaskResult.ReturnCode.SUCCESS) { LOG.error(result.getDescription()); } } }; eg.executeCommand(runnable); } /** * {@inheritDoc} */ @Override public void killInstance(final StringRecord instanceName) throws IOException { final AbstractInstance instance = this.instanceManager.getInstanceByName(instanceName.toString()); if (instance == null) { LOG.error("Cannot find instance with name " + instanceName + " to kill it"); return; } LOG.info("Killing task manager on instance " + instance); final Runnable runnable = new Runnable() { @Override public void run() { try { instance.killTaskManager(); } catch (IOException ioe) { LOG.error(StringUtils.stringifyException(ioe)); } } }; // Hand it over to the executor service this.executorService.execute(runnable); } /** * Collects all vertices with checkpoints from the given execution graph and advises the corresponding task managers * to remove those checkpoints. * * @param executionGraph * the execution graph from which the checkpoints shall be removed */ private void removeAllCheckpoints(final ExecutionGraph executionGraph) { // Group vertex IDs by assigned instance final Map<AbstractInstance, SerializableArrayList<ExecutionVertexID>> instanceMap = new HashMap<AbstractInstance, SerializableArrayList<ExecutionVertexID>>(); final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(executionGraph, true); while (it.hasNext()) { final ExecutionVertex vertex = it.next(); final AllocatedResource allocatedResource = vertex.getAllocatedResource(); if (allocatedResource == null) { continue; } final AbstractInstance abstractInstance = allocatedResource.getInstance(); if (abstractInstance == null) { continue; } SerializableArrayList<ExecutionVertexID> vertexIDs = instanceMap.get(abstractInstance); if (vertexIDs == null) { vertexIDs = new SerializableArrayList<ExecutionVertexID>(); instanceMap.put(abstractInstance, vertexIDs); } vertexIDs.add(vertex.getID()); } // Finally, trigger the removal of the checkpoints at each instance final Iterator<Map.Entry<AbstractInstance, SerializableArrayList<ExecutionVertexID>>> it2 = instanceMap .entrySet().iterator(); while (it2.hasNext()) { final Map.Entry<AbstractInstance, SerializableArrayList<ExecutionVertexID>> entry = it2.next(); final AbstractInstance abstractInstance = entry.getKey(); if (abstractInstance == null) { LOG.error("Cannot remove checkpoint: abstractInstance is null"); continue; } if (abstractInstance instanceof DummyInstance) { continue; } final Runnable runnable = new Runnable() { @Override public void run() { try { abstractInstance.removeCheckpoints(entry.getValue()); } catch (IOException ioe) { LOG.error(StringUtils.stringifyException(ioe)); } } }; // Hand it over to the executor service this.executorService.execute(runnable); } } /** * Tests whether the job manager has been shut down completely. * * @return <code>true</code> if the job manager has been shut down completely, <code>false</code> otherwise */ public boolean isShutDown() { return this.isShutDown; } /** * {@inheritDoc} */ public Map<InstanceType, InstanceTypeDescription> getMapOfAvailableInstanceTypes() { // Delegate call to the instance manager if (this.instanceManager != null) { return this.instanceManager.getMapOfAvailableInstanceTypes(); } return null; } /** * {@inheritDoc} */ @Override public void jobStatusHasChanged(final ExecutionGraph executionGraph, final InternalJobStatus newJobStatus, final String optionalMessage) { LOG.info("Status of job " + executionGraph.getJobName() + "(" + executionGraph.getJobID() + ")" + " changed to " + newJobStatus); if (newJobStatus == InternalJobStatus.FAILING) { // Cancel all remaining tasks cancelJob(executionGraph); } if (newJobStatus == InternalJobStatus.CANCELED || newJobStatus == InternalJobStatus.FAILED || newJobStatus == InternalJobStatus.FINISHED) { // Unregister job for Nephele's monitoring, optimization components, and dynamic input split assignment unregisterJob(executionGraph); } } /** * {@inheritDoc} */ @Override public void logBufferUtilization(final JobID jobID) throws IOException { final ExecutionGraph eg = this.scheduler.getExecutionGraphByID(jobID); if (eg == null) { return; } final Set<AbstractInstance> allocatedInstance = new HashSet<AbstractInstance>(); final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(eg, true); while (it.hasNext()) { final ExecutionVertex vertex = it.next(); final ExecutionState state = vertex.getExecutionState(); if (state == ExecutionState.RUNNING || state == ExecutionState.FINISHING) { final AbstractInstance instance = vertex.getAllocatedResource().getInstance(); if (instance instanceof DummyInstance) { LOG.error("Found instance of type DummyInstance for vertex " + vertex.getName() + " (state " + state + ")"); continue; } allocatedInstance.add(instance); } } // Send requests to task managers from separate thread final Runnable requestRunnable = new Runnable() { @Override public void run() { final Iterator<AbstractInstance> it2 = allocatedInstance.iterator(); try { while (it2.hasNext()) { it2.next().logBufferUtilization(); } } catch (IOException ioe) { LOG.error(StringUtils.stringifyException(ioe)); } } }; // Hand over to the executor service this.executorService.execute(requestRunnable); } /** * {@inheritDoc} */ @Override public void deploy(final JobID jobID, final AbstractInstance instance, final List<ExecutionVertex> verticesToBeDeployed) { if (verticesToBeDeployed.isEmpty()) { LOG.error("Method 'deploy' called but list of vertices to be deployed is empty"); return; } for (final ExecutionVertex vertex : verticesToBeDeployed) { // Check vertex state if (vertex.getExecutionState() != ExecutionState.READY) { LOG.error("Expected vertex " + vertex + " to be in state READY but it is in state " + vertex.getExecutionState()); } vertex.updateExecutionState(ExecutionState.STARTING, null); } // Create a new runnable and pass it the executor service final Runnable deploymentRunnable = new Runnable() { /** * {@inheritDoc} */ @Override public void run() { // Check if all required libraries are available on the instance try { instance.checkLibraryAvailability(jobID); } catch (IOException ioe) { LOG.error("Cannot check library availability: " + StringUtils.stringifyException(ioe)); } final List<TaskDeploymentDescriptor> submissionList = new ArrayList<TaskDeploymentDescriptor>(); // Check the consistency of the call for (final ExecutionVertex vertex : verticesToBeDeployed) { submissionList.add(vertex.constructDeploymentDescriptor()); LOG.info("Starting task " + vertex + " on " + vertex.getAllocatedResource().getInstance()); } List<TaskSubmissionResult> submissionResultList = null; try { submissionResultList = instance.submitTasks(submissionList); } catch (final IOException ioe) { final String errorMsg = StringUtils.stringifyException(ioe); for (final ExecutionVertex vertex : verticesToBeDeployed) { vertex.updateExecutionStateAsynchronously(ExecutionState.FAILED, errorMsg); } } if (verticesToBeDeployed.size() != submissionResultList.size()) { LOG.error("size of submission result list does not match size of list with vertices to be deployed"); } int count = 0; for (final TaskSubmissionResult tsr : submissionResultList) { ExecutionVertex vertex = verticesToBeDeployed.get(count++); if (!vertex.getID().equals(tsr.getVertexID())) { LOG.error("Expected different order of objects in task result list"); vertex = null; for (final ExecutionVertex candVertex : verticesToBeDeployed) { if (tsr.getVertexID().equals(candVertex.getID())) { vertex = candVertex; break; } } if (vertex == null) { LOG.error("Cannot find execution vertex for vertex ID " + tsr.getVertexID()); continue; } } if (tsr.getReturnCode() != AbstractTaskResult.ReturnCode.SUCCESS) { // Change the execution state to failed and let the scheduler deal with the rest vertex.updateExecutionStateAsynchronously(ExecutionState.FAILED, tsr.getDescription()); } } } }; this.executorService.execute(deploymentRunnable); } /** * {@inheritDoc} */ @Override public InputSplitWrapper requestNextInputSplit(final JobID jobID, final ExecutionVertexID vertexID, final IntegerRecord sequenceNumber) throws IOException { final ExecutionGraph graph = this.scheduler.getExecutionGraphByID(jobID); if (graph == null) { LOG.error("Cannot find execution graph to job ID " + jobID); return null; } final ExecutionVertex vertex = graph.getVertexByID(vertexID); if (vertex == null) { LOG.error("Cannot find execution vertex for vertex ID " + vertexID); return null; } return new InputSplitWrapper(jobID, this.inputSplitManager.getNextInputSplit(vertex, sequenceNumber.getValue())); } /** * {@inheritDoc} */ @Override public void updateCheckpointState(final TaskCheckpointState taskCheckpointState) throws IOException { // Get the graph object for this final JobID jobID = taskCheckpointState.getJobID(); final ExecutionGraph executionGraph = this.scheduler.getExecutionGraphByID(jobID); if (executionGraph == null) { LOG.error("Cannot find execution graph for job " + taskCheckpointState.getJobID() + " to update checkpoint state"); return; } final ExecutionVertex vertex = executionGraph.getVertexByID(taskCheckpointState.getVertexID()); if (vertex == null) { LOG.error("Cannot find vertex with ID " + taskCheckpointState.getVertexID() + " to update checkpoint state"); return; } final Runnable taskStateChangeRunnable = new Runnable() { @Override public void run() { vertex.updateCheckpointState(taskCheckpointState.getCheckpointState()); } }; // Hand over to the executor service, as this may result in a longer operation with several IPC operations executionGraph.executeCommand(taskStateChangeRunnable); } /** * {@inheritDoc} */ @Override public void sendData(final PluginID pluginID, final IOReadableWritable data) throws IOException { final JobManagerPlugin jmp = this.jobManagerPlugins.get(pluginID); if (jmp == null) { LOG.error("Cannot find job manager plugin for plugin ID " + pluginID); return; } jmp.sendData(data); } /** * {@inheritDoc} */ @Override public IOReadableWritable requestData(final PluginID pluginID, final IOReadableWritable data) throws IOException { final JobManagerPlugin jmp = this.jobManagerPlugins.get(pluginID); if (jmp == null) { LOG.error("Cannot find job manager plugin for plugin ID " + pluginID); return null; } return jmp.requestData(data); } } diff --git a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ByteBufferedChannelManager.java b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ByteBufferedChannelManager.java index c09dccf8f..d898ea34b 100644 --- a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ByteBufferedChannelManager.java +++ b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ByteBufferedChannelManager.java @@ -1,827 +1,824 @@ /*********************************************************************************************************************** * * Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.nephele.taskmanager.bytebuffered; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import eu.stratosphere.nephele.configuration.GlobalConfiguration; import eu.stratosphere.nephele.execution.Environment; import eu.stratosphere.nephele.executiongraph.ExecutionVertexID; import eu.stratosphere.nephele.instance.InstanceConnectionInfo; import eu.stratosphere.nephele.io.AbstractID; import eu.stratosphere.nephele.io.GateID; import eu.stratosphere.nephele.io.channels.Buffer; import eu.stratosphere.nephele.io.channels.ChannelID; import eu.stratosphere.nephele.io.channels.ChannelType; import eu.stratosphere.nephele.io.channels.FileBufferManager; import eu.stratosphere.nephele.jobgraph.JobID; import eu.stratosphere.nephele.protocols.ChannelLookupProtocol; import eu.stratosphere.nephele.taskmanager.Task; import eu.stratosphere.nephele.taskmanager.bufferprovider.BufferProvider; import eu.stratosphere.nephele.taskmanager.bufferprovider.BufferProviderBroker; import eu.stratosphere.nephele.taskmanager.bufferprovider.GlobalBufferPool; import eu.stratosphere.nephele.taskmanager.bufferprovider.LocalBufferPool; import eu.stratosphere.nephele.taskmanager.bufferprovider.LocalBufferPoolOwner; import eu.stratosphere.nephele.taskmanager.transferenvelope.TransferEnvelope; import eu.stratosphere.nephele.taskmanager.transferenvelope.TransferEnvelopeDispatcher; import eu.stratosphere.nephele.taskmanager.transferenvelope.TransferEnvelopeReceiverList; public final class ByteBufferedChannelManager implements TransferEnvelopeDispatcher, BufferProviderBroker { /** * The log object used to report problems and errors. */ private static final Log LOG = LogFactory.getLog(ByteBufferedChannelManager.class); private static final boolean DEFAULT_ALLOW_SENDER_SIDE_SPILLING = false; private static final boolean DEFAULT_MERGE_SPILLED_BUFFERS = true; // TODO: Make this configurable private static final int NUMBER_OF_CHANNELS_FOR_MULTICAST = 10; private final Map<ChannelID, ChannelContext> registeredChannels = new ConcurrentHashMap<ChannelID, ChannelContext>(); private final Map<AbstractID, LocalBufferPoolOwner> localBufferPoolOwner = new ConcurrentHashMap<AbstractID, LocalBufferPoolOwner>(); private final NetworkConnectionManager networkConnectionManager; private final ChannelLookupProtocol channelLookupService; private final InstanceConnectionInfo localConnectionInfo; private final LocalBufferPool transitBufferPool; private final boolean allowSenderSideSpilling; private final boolean mergeSpilledBuffers; private final boolean multicastEnabled = true; /** * This map caches transfer envelope receiver lists. */ private final Map<ChannelID, TransferEnvelopeReceiverList> receiverCache = new ConcurrentHashMap<ChannelID, TransferEnvelopeReceiverList>(); public ByteBufferedChannelManager(final ChannelLookupProtocol channelLookupService, final InstanceConnectionInfo localInstanceConnectionInfo) throws IOException { this.channelLookupService = channelLookupService; this.localConnectionInfo = localInstanceConnectionInfo; // Initialized the file buffer manager FileBufferManager.getInstance(); // Initialize the global buffer pool GlobalBufferPool.getInstance(); // Initialize the transit buffer pool this.transitBufferPool = new LocalBufferPool(128, true); this.networkConnectionManager = new NetworkConnectionManager(this, localInstanceConnectionInfo.getAddress(), localInstanceConnectionInfo.getDataPort()); this.allowSenderSideSpilling = GlobalConfiguration.getBoolean("channel.network.allowSenderSideSpilling", DEFAULT_ALLOW_SENDER_SIDE_SPILLING); this.mergeSpilledBuffers = GlobalConfiguration.getBoolean("channel.network.mergeSpilledBuffers", DEFAULT_MERGE_SPILLED_BUFFERS); LOG.info("Initialized byte buffered channel manager with sender-side spilling " + (this.allowSenderSideSpilling ? "enabled" : "disabled") + (this.mergeSpilledBuffers ? " and spilled buffer merging enabled" : "")); } /** * Registers the given task with the byte buffered channel manager. * * @param task * the task to be registered * @param the * set of output channels which are initially active * @throws InsufficientResourcesException * thrown if the channel manager does not have enough memory buffers to safely run this task */ public void register(final Task task, final Set<ChannelID> activeOutputChannels) throws InsufficientResourcesException { // Check if we can safely run this task with the given resources checkBufferAvailability(task); final Environment environment = task.getEnvironment(); final TaskContext taskContext = task.createTaskContext(this, this.localBufferPoolOwner.remove(task.getVertexID())); final Set<GateID> outputGateIDs = environment.getOutputGateIDs(); for (final Iterator<GateID> gateIt = outputGateIDs.iterator(); gateIt.hasNext();) { final GateID gateID = gateIt.next(); final OutputGateContext outputGateContext = taskContext.createOutputGateContext(gateID); final Set<ChannelID> outputChannelIDs = environment.getOutputChannelIDsOfGate(gateID); for (final Iterator<ChannelID> channelIt = outputChannelIDs.iterator(); channelIt.hasNext();) { final ChannelID channelID = channelIt.next(); final OutputChannelContext previousContext = (OutputChannelContext) this.registeredChannels .get(channelID); final boolean isActive = true;/* activeOutputChannels.contains(channelID); */ final OutputChannelContext outputChannelContext = outputGateContext.createOutputChannelContext( channelID, previousContext, isActive, this.mergeSpilledBuffers); // Add routing entry to receiver cache to reduce latency if (outputChannelContext.getType() == ChannelType.INMEMORY) { addReceiverListHint(outputChannelContext.getChannelID(), outputChannelContext.getConnectedChannelID()); } // Add routing entry to receiver cache to save lookup for data arriving at the output channel if (outputChannelContext.getType() == ChannelType.NETWORK) { addReceiverListHint(outputChannelContext.getConnectedChannelID(), outputChannelContext.getChannelID()); } if (LOG.isDebugEnabled()) LOG.debug("Registering byte buffered output channel " + outputChannelContext.getChannelID() + " (" + (isActive ? "active" : "inactive") + ")"); this.registeredChannels.put(outputChannelContext.getChannelID(), outputChannelContext); } } final Set<GateID> inputGateIDs = environment.getInputGateIDs(); for (final Iterator<GateID> gateIt = inputGateIDs.iterator(); gateIt.hasNext();) { final GateID gateID = gateIt.next(); final InputGateContext inputGateContext = taskContext.createInputGateContext(gateID); final Set<ChannelID> inputChannelIDs = environment.getInputChannelIDsOfGate(gateID); for (final Iterator<ChannelID> channelIt = inputChannelIDs.iterator(); channelIt.hasNext();) { final ChannelID channelID = channelIt.next(); final InputChannelContext previousContext = (InputChannelContext) this.registeredChannels .get(channelID); final InputChannelContext inputChannelContext = inputGateContext.createInputChannelContext( channelID, previousContext); // Add routing entry to receiver cache to reduce latency if (inputChannelContext.getType() == ChannelType.INMEMORY) { addReceiverListHint(inputChannelContext.getChannelID(), inputChannelContext.getConnectedChannelID()); } this.registeredChannels.put(inputChannelContext.getChannelID(), inputChannelContext); } // Add input gate context to set of local buffer pool owner final LocalBufferPoolOwner bufferPoolOwner = inputGateContext.getLocalBufferPoolOwner(); if (bufferPoolOwner != null) { this.localBufferPoolOwner.put(inputGateContext.getGateID(), bufferPoolOwner); } } this.localBufferPoolOwner.put(task.getVertexID(), taskContext); redistributeGlobalBuffers(); } /** * Unregisters the given task from the byte buffered channel manager. * * @param vertexID * the ID of the task to be unregistered * @param task * the task to be unregistered */ public void unregister(final ExecutionVertexID vertexID, final Task task) { final Environment environment = task.getEnvironment(); Iterator<ChannelID> channelIterator = environment.getOutputChannelIDs().iterator(); while (channelIterator.hasNext()) { final ChannelID outputChannelID = channelIterator.next(); final ChannelContext context = this.registeredChannels.remove(outputChannelID); if (context != null) { context.destroy(); } this.receiverCache.remove(outputChannelID); } channelIterator = environment.getInputChannelIDs().iterator(); while (channelIterator.hasNext()) { final ChannelID outputChannelID = channelIterator.next(); final ChannelContext context = this.registeredChannels.remove(outputChannelID); if (context != null) { context.destroy(); } this.receiverCache.remove(outputChannelID); } final Iterator<GateID> inputGateIterator = environment.getInputGateIDs().iterator(); while (inputGateIterator.hasNext()) { final GateID inputGateID = inputGateIterator.next(); final LocalBufferPoolOwner owner = this.localBufferPoolOwner.remove(inputGateID); if (owner != null) { owner.clearLocalBufferPool(); } } final LocalBufferPoolOwner owner = this.localBufferPoolOwner.remove(vertexID); if (owner != null) { owner.clearLocalBufferPool(); } redistributeGlobalBuffers(); } /** * Shuts down the byte buffered channel manager and stops all its internal processes. */ public void shutdown() { this.networkConnectionManager.shutDown(); } public NetworkConnectionManager getNetworkConnectionManager() { return this.networkConnectionManager; } private void recycleBuffer(final TransferEnvelope envelope) { final Buffer buffer = envelope.getBuffer(); if (buffer != null) { buffer.recycleBuffer(); } } private void sendReceiverNotFoundEvent(final TransferEnvelope envelope, final ChannelID receiver) throws IOException, InterruptedException { if (ReceiverNotFoundEvent.isReceiverNotFoundEvent(envelope)) { LOG.info("Dropping request to send ReceiverNotFoundEvent as response to ReceiverNotFoundEvent"); return; } final JobID jobID = envelope.getJobID(); final TransferEnvelope transferEnvelope = ReceiverNotFoundEvent.createEnvelopeWithEvent(jobID, receiver, envelope.getSequenceNumber()); final TransferEnvelopeReceiverList receiverList = getReceiverList(jobID, receiver); if (receiverList == null) { return; } processEnvelopeEnvelopeWithoutBuffer(transferEnvelope, receiverList); } private void processEnvelope(final TransferEnvelope transferEnvelope, final boolean freeSourceBuffer) throws IOException, InterruptedException { TransferEnvelopeReceiverList receiverList = null; try { receiverList = getReceiverList(transferEnvelope.getJobID(), transferEnvelope.getSource()); } catch (InterruptedException e) { recycleBuffer(transferEnvelope); throw e; } catch (IOException e) { recycleBuffer(transferEnvelope); throw e; } if (receiverList == null) { recycleBuffer(transferEnvelope); return; } // This envelope is known to have either no buffer or an memory-based input buffer if (transferEnvelope.getBuffer() == null) { processEnvelopeEnvelopeWithoutBuffer(transferEnvelope, receiverList); } else { processEnvelopeWithBuffer(transferEnvelope, receiverList, freeSourceBuffer); } } private void processEnvelopeWithBuffer(final TransferEnvelope transferEnvelope, final TransferEnvelopeReceiverList receiverList, final boolean freeSourceBuffer) throws IOException, InterruptedException { // Handle the most common (unicast) case first if (!freeSourceBuffer) { final List<ChannelID> localReceivers = receiverList.getLocalReceivers(); if (localReceivers.size() != 1) { LOG.error("Expected receiver list to have exactly one element"); } final ChannelID localReceiver = localReceivers.get(0); final ChannelContext cc = this.registeredChannels.get(localReceiver); if (cc == null) { try { sendReceiverNotFoundEvent(transferEnvelope, localReceiver); } finally { recycleBuffer(transferEnvelope); } return; } if (!cc.isInputChannel()) { LOG.error("Local receiver " + localReceiver + " is not an input channel, but is supposed to accept a buffer"); } cc.queueTransferEnvelope(transferEnvelope); return; } // This is the in-memory or multicast case final Buffer srcBuffer = transferEnvelope.getBuffer(); try { if (receiverList.hasLocalReceivers()) { final List<ChannelID> localReceivers = receiverList.getLocalReceivers(); for (final ChannelID localReceiver : localReceivers) { final ChannelContext cc = this.registeredChannels.get(localReceiver); if (cc == null) { sendReceiverNotFoundEvent(transferEnvelope, localReceiver); continue; } if (!cc.isInputChannel()) { LOG.error("Local receiver " + localReceiver + " is not an input channel, but is supposed to accept a buffer"); continue; } final InputChannelContext inputChannelContext = (InputChannelContext) cc; final Buffer destBuffer = inputChannelContext.requestEmptyBufferBlocking(srcBuffer.size()); try { srcBuffer.copyToBuffer(destBuffer); } catch (IOException e) { destBuffer.recycleBuffer(); throw e; } // TODO: See if we can save one duplicate step here final TransferEnvelope dup = transferEnvelope.duplicateWithoutBuffer(); dup.setBuffer(destBuffer); inputChannelContext.queueTransferEnvelope(dup); } } if (receiverList.hasRemoteReceivers()) { final List<RemoteReceiver> remoteReceivers = receiverList.getRemoteReceivers(); // Generate sender hint before sending the first envelope over the network if (transferEnvelope.getSequenceNumber() == 0) { generateSenderHint(transferEnvelope, remoteReceivers); } for (final RemoteReceiver remoteReceiver : remoteReceivers) { final TransferEnvelope dup = transferEnvelope.duplicate(); this.networkConnectionManager.queueEnvelopeForTransfer(remoteReceiver, dup); } } } finally { // Recycle the source buffer srcBuffer.recycleBuffer(); } } private void processEnvelopeEnvelopeWithoutBuffer(final TransferEnvelope transferEnvelope, final TransferEnvelopeReceiverList receiverList) throws IOException, InterruptedException { // No need to copy anything final Iterator<ChannelID> localIt = receiverList.getLocalReceivers().iterator(); while (localIt.hasNext()) { final ChannelID localReceiver = localIt.next(); final ChannelContext channelContext = this.registeredChannels.get(localReceiver); if (channelContext == null) { sendReceiverNotFoundEvent(transferEnvelope, localReceiver); continue; } channelContext.queueTransferEnvelope(transferEnvelope); } if (!receiverList.hasRemoteReceivers()) { return; } // Generate sender hint before sending the first envelope over the network final List<RemoteReceiver> remoteReceivers = receiverList.getRemoteReceivers(); if (transferEnvelope.getSequenceNumber() == 0) { generateSenderHint(transferEnvelope, remoteReceivers); } final Iterator<RemoteReceiver> remoteIt = remoteReceivers.iterator(); while (remoteIt.hasNext()) { final RemoteReceiver remoteReceiver = remoteIt.next(); this.networkConnectionManager.queueEnvelopeForTransfer(remoteReceiver, transferEnvelope); } } private void addReceiverListHint(final ChannelID source, final ChannelID localReceiver) { final TransferEnvelopeReceiverList receiverList = new TransferEnvelopeReceiverList(localReceiver); if (this.receiverCache.put(source, receiverList) != null) { LOG.warn("Receiver cache already contained entry for " + source); } } private void addReceiverListHint(final ChannelID source, final RemoteReceiver remoteReceiver) { final TransferEnvelopeReceiverList receiverList = new TransferEnvelopeReceiverList(remoteReceiver); if (this.receiverCache.put(source, receiverList) != null) { LOG.warn("Receiver cache already contained entry for " + source); } } private void generateSenderHint(final TransferEnvelope transferEnvelope, final List<RemoteReceiver> remoteReceivers) { final ChannelContext channelContext = this.registeredChannels.get(transferEnvelope.getSource()); if (channelContext == null) { LOG.error("Cannot find channel context for channel ID " + transferEnvelope.getSource()); return; } // Only generate sender hints for output channels if (channelContext.isInputChannel()) { return; } final ChannelID remoteSourceID = channelContext.getConnectedChannelID(); final int connectionIndex = remoteReceivers.get(0).getConnectionIndex(); final InetSocketAddress isa = new InetSocketAddress(this.localConnectionInfo.getAddress(), this.localConnectionInfo.getDataPort()); final RemoteReceiver remoteReceiver = new RemoteReceiver(isa, connectionIndex); final TransferEnvelope senderHint = SenderHintEvent.createEnvelopeWithEvent(transferEnvelope, remoteSourceID, remoteReceiver); final Iterator<RemoteReceiver> remoteIt = remoteReceivers.iterator(); while (remoteIt.hasNext()) { final RemoteReceiver rr = remoteIt.next(); this.networkConnectionManager.queueEnvelopeForTransfer(rr, senderHint); } } /** * Returns the list of receivers for transfer envelopes produced by the channel with the given source channel ID. * * @param jobID * the ID of the job the given channel ID belongs to * @param sourceChannelID * the source channel ID for which the receiver list shall be retrieved * @return the list of receivers or <code>null</code> if the receiver could not be determined * @throws IOException * @throws InterruptedExcption */ private TransferEnvelopeReceiverList getReceiverList(final JobID jobID, final ChannelID sourceChannelID) throws IOException, InterruptedException { TransferEnvelopeReceiverList receiverList = this.receiverCache.get(sourceChannelID); if (receiverList != null) { return receiverList; } while (true) { if (Thread.currentThread().isInterrupted()) { break; } - ConnectionInfoLookupResponse lookupResponse; - synchronized (this.channelLookupService) { - lookupResponse = this.channelLookupService.lookupConnectionInfo( - this.localConnectionInfo, jobID, sourceChannelID); - } + final ConnectionInfoLookupResponse lookupResponse = this.channelLookupService.lookupConnectionInfo( + this.localConnectionInfo, jobID, sourceChannelID); if (lookupResponse.isJobAborting()) { break; } if (lookupResponse.receiverNotFound()) { LOG.error("Cannot find task(s) waiting for data from source channel with ID " + sourceChannelID); break; } if (lookupResponse.receiverNotReady()) { Thread.sleep(500); continue; } if (lookupResponse.receiverReady()) { receiverList = new TransferEnvelopeReceiverList(lookupResponse); break; } } if (receiverList != null) { this.receiverCache.put(sourceChannelID, receiverList); if (LOG.isDebugEnabled()) { final StringBuilder sb = new StringBuilder(); sb.append("Receiver list for source channel ID " + sourceChannelID + " at task manager " + this.localConnectionInfo + "\n"); if (receiverList.hasLocalReceivers()) { sb.append("\tLocal receivers:\n"); final Iterator<ChannelID> it = receiverList.getLocalReceivers().iterator(); while (it.hasNext()) { sb.append("\t\t" + it.next() + "\n"); } } if (receiverList.hasRemoteReceivers()) { sb.append("Remote receivers:\n"); final Iterator<RemoteReceiver> it = receiverList.getRemoteReceivers().iterator(); while (it.hasNext()) { sb.append("\t\t" + it.next() + "\n"); } } LOG.debug(sb.toString()); } } return receiverList; } /** * {@inheritDoc} */ @Override public void processEnvelopeFromOutputChannel(final TransferEnvelope transferEnvelope) throws IOException, InterruptedException { processEnvelope(transferEnvelope, true); } /** * {@inheritDoc} */ @Override public void processEnvelopeFromInputChannel(final TransferEnvelope transferEnvelope) throws IOException, InterruptedException { processEnvelope(transferEnvelope, false); } /** * {@inheritDoc} */ @Override public void processEnvelopeFromNetwork(final TransferEnvelope transferEnvelope, boolean freeSourceBuffer) throws IOException, InterruptedException { // Check if the envelope is the special envelope with the sender hint event if (SenderHintEvent.isSenderHintEvent(transferEnvelope)) { // Check if this is the final destination of the sender hint event before adding it final SenderHintEvent seh = (SenderHintEvent) transferEnvelope.getEventList().get(0); if (this.registeredChannels.get(seh.getSource()) != null) { addReceiverListHint(seh.getSource(), seh.getRemoteReceiver()); return; } } processEnvelope(transferEnvelope, freeSourceBuffer); } /** * Triggers the byte buffer channel manager write the current utilization of its read and write buffers to the logs. * This method is primarily for debugging purposes. */ public void logBufferUtilization() { System.out.println("Buffer utilization at " + System.currentTimeMillis()); System.out.println("\tUnused global buffers: " + GlobalBufferPool.getInstance().getCurrentNumberOfBuffers()); System.out.println("\tLocal buffer pool status:"); final Iterator<LocalBufferPoolOwner> it = this.localBufferPoolOwner.values().iterator(); while (it.hasNext()) { it.next().logBufferUtilization(); } this.networkConnectionManager.logBufferUtilization(); System.out.println("\tIncoming connections:"); final Iterator<Map.Entry<ChannelID, ChannelContext>> it2 = this.registeredChannels.entrySet() .iterator(); while (it2.hasNext()) { final Map.Entry<ChannelID, ChannelContext> entry = it2.next(); final ChannelContext context = entry.getValue(); if (context.isInputChannel()) { final InputChannelContext inputChannelContext = (InputChannelContext) context; inputChannelContext.logQueuedEnvelopes(); } } } /** * {@inheritDoc} */ @Override public BufferProvider getBufferProvider(final JobID jobID, final ChannelID sourceChannelID) throws IOException, InterruptedException { final TransferEnvelopeReceiverList receiverList = getReceiverList(jobID, sourceChannelID); // Receiver could not be determined, use transit buffer pool to read data from channel if (receiverList == null) { return this.transitBufferPool; } if (receiverList.hasLocalReceivers() && !receiverList.hasRemoteReceivers()) { final List<ChannelID> localReceivers = receiverList.getLocalReceivers(); if (localReceivers.size() == 1) { // Unicast case, get final buffer provider final ChannelID localReceiver = localReceivers.get(0); final ChannelContext cc = this.registeredChannels.get(localReceiver); if (cc == null) { // Use the transit buffer for this purpose, data will be discarded in most cases anyway. return this.transitBufferPool; } if (!cc.isInputChannel()) { throw new IOException("Channel context for local receiver " + localReceiver + " is not an input channel context"); } final InputChannelContext icc = (InputChannelContext) cc; return icc; } } return this.transitBufferPool; } /** * Checks if the byte buffered channel manager has enough resources available to safely execute the given task. * * @param task * the task to be executed * @throws InsufficientResourcesException * thrown if the byte buffered manager currently does not have enough resources available to execute the * task */ private void checkBufferAvailability(final Task task) throws InsufficientResourcesException { final int totalNumberOfBuffers = GlobalBufferPool.getInstance().getTotalNumberOfBuffers(); int numberOfAlreadyRegisteredChannels = this.registeredChannels.size(); if (this.multicastEnabled) { numberOfAlreadyRegisteredChannels += NUMBER_OF_CHANNELS_FOR_MULTICAST; } final Environment env = task.getEnvironment(); final int numberOfNewChannels = env.getNumberOfOutputChannels() + env.getNumberOfInputChannels(); final int totalNumberOfChannels = numberOfAlreadyRegisteredChannels + numberOfNewChannels; final double buffersPerChannel = (double) totalNumberOfBuffers / (double) totalNumberOfChannels; if (buffersPerChannel < 1.0) { // Construct error message final StringBuilder sb = new StringBuilder(this.localConnectionInfo.getHostName()); sb.append(" has not enough buffers available to safely execute "); sb.append(env.getTaskName()); sb.append(" ("); sb.append(totalNumberOfChannels - totalNumberOfBuffers); sb.append(" buffers are currently missing)"); throw new InsufficientResourcesException(sb.toString()); } } /** * Redistributes the global buffers among the registered tasks. */ private void redistributeGlobalBuffers() { final int totalNumberOfBuffers = GlobalBufferPool.getInstance().getTotalNumberOfBuffers(); int totalNumberOfChannels = this.registeredChannels.size(); if (this.multicastEnabled) { totalNumberOfChannels += NUMBER_OF_CHANNELS_FOR_MULTICAST; } final double buffersPerChannel = (double) totalNumberOfBuffers / (double) totalNumberOfChannels; if (buffersPerChannel < 1.0) { LOG.warn("System is low on memory buffers. This may result in reduced performance."); } if (LOG.isDebugEnabled()) { LOG.debug("Total number of buffers is " + totalNumberOfBuffers); LOG.debug("Total number of channels is " + totalNumberOfChannels); } if (this.localBufferPoolOwner.isEmpty()) { return; } final Iterator<LocalBufferPoolOwner> it = this.localBufferPoolOwner.values().iterator(); while (it.hasNext()) { final LocalBufferPoolOwner lbpo = it.next(); lbpo.setDesignatedNumberOfBuffers((int) Math.ceil(buffersPerChannel * lbpo.getNumberOfChannels())); } if (this.multicastEnabled) { this.transitBufferPool.setDesignatedNumberOfBuffers((int) Math.ceil(buffersPerChannel * NUMBER_OF_CHANNELS_FOR_MULTICAST)); } } /** * Invalidates the entries identified by the given channel IDs from the receiver lookup cache. * * @param channelIDs * the channel IDs identifying the cache entries to invalidate */ public void invalidateLookupCacheEntries(final Set<ChannelID> channelIDs) { final Iterator<ChannelID> it = channelIDs.iterator(); while (it.hasNext()) { this.receiverCache.remove(it.next()); } } public void reportAsynchronousEvent(final ExecutionVertexID vertexID) { final LocalBufferPoolOwner lbpo = this.localBufferPoolOwner.get(vertexID); if (lbpo == null) { System.out.println("Cannot find local buffer pool owner for " + vertexID); return; } lbpo.reportAsynchronousEvent(); } } diff --git a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ConnectionInfoLookupResponse.java b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ConnectionInfoLookupResponse.java index a00c3929e..169549821 100644 --- a/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ConnectionInfoLookupResponse.java +++ b/nephele/nephele-server/src/main/java/eu/stratosphere/nephele/taskmanager/bytebuffered/ConnectionInfoLookupResponse.java @@ -1,150 +1,150 @@ /*********************************************************************************************************************** * * Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.nephele.taskmanager.bytebuffered; import java.util.ArrayList; import java.util.List; import eu.stratosphere.nephele.io.channels.ChannelID; public class ConnectionInfoLookupResponse { private enum ReturnCode { NOT_FOUND, FOUND_AND_RECEIVER_READY, FOUND_BUT_RECEIVER_NOT_READY, JOB_IS_ABORTING }; // was request successful? private final ReturnCode returnCode; /** * Contains next-hop instances, this instance must forward multicast transmissions to. */ private final ArrayList<RemoteReceiver> remoteTargets = new ArrayList<RemoteReceiver>(); /** * Contains local ChannelIDs, multicast packets must be forwarded to. */ private final ArrayList<ChannelID> localTargets = new ArrayList<ChannelID>(); public ConnectionInfoLookupResponse(final ReturnCode returnCode) { - this.returnCode = ReturnCode.NOT_FOUND; + this.returnCode = returnCode; } public ConnectionInfoLookupResponse() { this.returnCode = null; } public void addRemoteTarget(final RemoteReceiver remote) { this.remoteTargets.add(remote); } public void addLocalTarget(ChannelID local) { this.localTargets.add(local); } public List<RemoteReceiver> getRemoteTargets() { return this.remoteTargets; } public List<ChannelID> getLocalTargets() { return this.localTargets; } public boolean receiverNotFound() { return (this.returnCode == ReturnCode.NOT_FOUND); } public boolean receiverNotReady() { return (this.returnCode == ReturnCode.FOUND_BUT_RECEIVER_NOT_READY); } public boolean receiverReady() { return (this.returnCode == ReturnCode.FOUND_AND_RECEIVER_READY); } public boolean isJobAborting() { return (this.returnCode == ReturnCode.JOB_IS_ABORTING); } public static ConnectionInfoLookupResponse createReceiverFoundAndReady(final ChannelID targetChannelID) { final ConnectionInfoLookupResponse response = new ConnectionInfoLookupResponse( ReturnCode.FOUND_AND_RECEIVER_READY); response.addLocalTarget(targetChannelID); return response; } public static ConnectionInfoLookupResponse createReceiverFoundAndReady(final RemoteReceiver remoteReceiver) { final ConnectionInfoLookupResponse response = new ConnectionInfoLookupResponse( ReturnCode.FOUND_AND_RECEIVER_READY); response.addRemoteTarget(remoteReceiver); return response; } /** * Constructor used to generate a plain ConnectionInfoLookupResponse object to be filled with multicast targets. * * @return */ public static ConnectionInfoLookupResponse createReceiverFoundAndReady() { final ConnectionInfoLookupResponse response = new ConnectionInfoLookupResponse( ReturnCode.FOUND_AND_RECEIVER_READY); return response; } public static ConnectionInfoLookupResponse createReceiverNotFound() { final ConnectionInfoLookupResponse response = new ConnectionInfoLookupResponse(ReturnCode.NOT_FOUND); return response; } public static ConnectionInfoLookupResponse createReceiverNotReady() { final ConnectionInfoLookupResponse response = new ConnectionInfoLookupResponse( ReturnCode.FOUND_BUT_RECEIVER_NOT_READY); return response; } public static ConnectionInfoLookupResponse createJobIsAborting() { final ConnectionInfoLookupResponse response = new ConnectionInfoLookupResponse(ReturnCode.JOB_IS_ABORTING); return response; } @Override public String toString() { StringBuilder returnstring = new StringBuilder(); returnstring.append("local targets (total: " + this.localTargets.size() + "):\n"); for (ChannelID i : this.localTargets) { returnstring.append(i + "\n"); } returnstring.append("remote targets: (total: " + this.remoteTargets.size() + "):\n"); for (final RemoteReceiver rr : this.remoteTargets) { returnstring.append(rr + "\n"); } return returnstring.toString(); } }
false
false
null
null
diff --git a/src/com/aokp/romcontrol/fragments/LEDControl.java b/src/com/aokp/romcontrol/fragments/LEDControl.java index bd5f760..91e04a5 100755 --- a/src/com/aokp/romcontrol/fragments/LEDControl.java +++ b/src/com/aokp/romcontrol/fragments/LEDControl.java @@ -1,681 +1,686 @@ package com.aokp.romcontrol.fragments; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.Notification; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.NumberPicker; import android.widget.Spinner; import android.widget.Switch; import com.aokp.romcontrol.R; import com.aokp.romcontrol.util.Helpers; import com.aokp.romcontrol.util.ShortcutPickerHelper; import net.margaritov.preference.colorpicker.ColorPickerDialog; import java.net.URISyntaxException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class LEDControl extends Fragment implements ColorPickerDialog.OnColorChangedListener, ShortcutPickerHelper.OnPickListener { private static final String TAG = "LEDControl"; private static final boolean DEBUG = false; private static final String PROP_CHARGING_LED = "persist.sys.enable-charging-led"; private static final String PROP_LED_BRIGHTNESS = "persist.sys.led-brightness"; private Button mOnTime; private Button mOffTime; private Button mEditApp; private Button mLedTest; private Switch mLedScreenOn; private Switch mChargingLedOn; private ImageView mLEDButton; private Spinner mListApps; private Button mLedBrightness; private NumberPicker mBrightnessNumberpicker; private ArrayAdapter<CharSequence> listAdapter; private ViewGroup mContainer; private Activity mActivity; private Resources mResources; private ShortcutPickerHelper mPicker; private int defaultColor; private int userColor; private String[] timeArray; private int[] timeOutput; private String[] brightnessArray; private int[] brightnessOutput; private boolean blinkOn; private boolean stopLed; private boolean mRegister = false; private int onBlink; private int offBlink; private int currentSelectedApp; private boolean hasBrightnessFeature; private boolean hasChargingFeature; private HashMap<String, CustomApps> customAppList; private ArrayList<String> unicornApps; private ArrayList<String> appList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContainer = container; mActivity = getActivity(); mResources = getResources(); return inflater.inflate(R.layout.led_control, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().setTitle(R.string.title_led); mOnTime = (Button) mActivity.findViewById(R.id.ontime); mOffTime = (Button) mActivity.findViewById(R.id.offtime); mEditApp = (Button) mActivity.findViewById(R.id.edit_button); mLedTest = (Button) mActivity.findViewById(R.id.led_test); mLEDButton = (ImageView) mActivity.findViewById(R.id.ledbutton); mLedScreenOn = (Switch) mActivity.findViewById(R.id.led_screen_on); mChargingLedOn = (Switch) mActivity.findViewById(R.id.charging_led_on); mListApps = (Spinner) mActivity.findViewById(R.id.custom_apps); mLedBrightness = (Button) mActivity.findViewById(R.id.button_led_brightness); timeArray = mResources.getStringArray(R.array.led_entries); timeOutput = mResources.getIntArray(R.array.led_values); brightnessArray = mResources.getStringArray(R.array.led_brightness_entries); brightnessOutput = mResources.getIntArray(R.array.led_brightness_values); getActivity().getActionBar().setDisplayHomeAsUpEnabled(true); defaultColor = mResources .getColor(com.android.internal.R.color.config_defaultNotificationColor); userColor = Settings.System.getInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_COLOR, defaultColor); mPicker = new ShortcutPickerHelper(this, this); customAppList = new HashMap<String, CustomApps>(); unicornApps = new ArrayList<String>(); appList = new ArrayList<String>(); currentSelectedApp = 0; mLEDButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ColorPickerDialog picker = new ColorPickerDialog(mActivity, userColor); picker.setOnColorChangedListener(LEDControl.this); picker.show(); } }); mLEDButton.setImageResource(R.drawable.led_circle_button); mOnTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { AlertDialog.Builder b = new AlertDialog.Builder(mActivity); b.setTitle(R.string.led_time_on); b.setItems(timeArray, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Settings.System.putInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_ON, timeOutput[item]); refreshSettings(); } }); AlertDialog alert = b.create(); alert.show(); } }); mOffTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { AlertDialog.Builder b = new AlertDialog.Builder(mActivity); b.setTitle(R.string.led_time_off); b.setItems(timeArray, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Settings.System.putInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_OFF, timeOutput[item]); refreshSettings(); } }); AlertDialog alert = b.create(); alert.show(); } }); mLedScreenOn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton v, boolean checked) { Settings.Secure.putInt(mActivity.getContentResolver(), Settings.Secure.LED_SCREEN_ON, checked ? 1 : 0); if (DEBUG) { Log.i(TAG, "LED flash when screen ON is set to: " + checked); } } }); hasChargingFeature = getResources().getBoolean(R.bool.has_led_charging_feature); if (hasChargingFeature) { mChargingLedOn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton v, boolean checked) { Helpers.setSystemProp(PROP_CHARGING_LED, checked ? "1" : "0"); if (DEBUG) { Log.i(TAG, "Charging LED is set to: " + checked); } } }); } else { mChargingLedOn.setVisibility(View.GONE); } parseExistingAppList(); listAdapter = new ArrayAdapter<CharSequence>(mActivity, android.R.layout.simple_spinner_item); listAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapterRefreshSetting(); mListApps.setAdapter(listAdapter); mListApps.setSelection(0); mListApps.setLongClickable(false); mListApps.setOnItemSelectedListener(new customAppSpinnerSelected()); mEditApp.setOnClickListener(new buttonEditApp()); editButtonVisibility(); mLedTest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mRegister) { mActivity.unregisterReceiver(testLedReceiver); mRegister = false; } if (!mRegister) { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); mActivity.registerReceiver(testLedReceiver, filter); mRegister = true; } final int place = currentSelectedApp; AlertDialog.Builder ad = new AlertDialog.Builder(mActivity); ad.setTitle(R.string.led_test_notification); ad.setIcon(R.mipmap.ic_launcher); String appName = unicornApps.get(place); ad.setMessage(getResources().getString(R.string.led_test_notification_message_now) + appName + getResources().getString(R.string.led_test_notification_message_note)); ad.setPositiveButton(R.string.led_test_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mRegister) { mActivity.unregisterReceiver(testLedReceiver); mRegister = false; } dialog.dismiss(); } }); ad.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (mRegister) { mActivity.unregisterReceiver(testLedReceiver); mRegister = false; } } }); ad.show(); } }); hasBrightnessFeature = getResources().getBoolean(R.bool.has_led_brightness_feature); if (hasBrightnessFeature) { mLedBrightness.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { AlertDialog.Builder b = new AlertDialog.Builder(mActivity); b.setTitle(R.string.led_change_brightness); b.setSingleChoiceItems(brightnessArray, Settings.System .getInt(mActivity.getContentResolver(), Settings.System.LED_BRIGHTNESS, 1), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { Helpers.setSystemProp(PROP_LED_BRIGHTNESS, String.valueOf(brightnessOutput[item])); Settings.System.putInt(mActivity.getContentResolver(), Settings.System.LED_BRIGHTNESS, item); } }); b.setPositiveButton(com.android.internal.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = b.create(); alert.show(); } }); } else { mLedBrightness.setVisibility(View.GONE); } refreshSettings(); startLed(); } private void adapterRefreshSetting() { if (listAdapter != null) { if (listAdapter.getCount() != 0) { listAdapter.clear(); } listAdapter.addAll(unicornApps); + if (currentSelectedApp == listAdapter.getCount()-1) { + mListApps.setSelection(0); + } } } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: if (blinkOn) { mLEDButton.setColorFilter(userColor); } else { mLEDButton.setColorFilter(Color.BLACK); } break; } } }; public void startLed() { new Thread() { @Override public void run() { Looper.prepare(); while (!stopLed) { mHandler.sendEmptyMessage(0); int delay = blinkOn ? onBlink : offBlink; try { Thread.sleep(delay); } catch (InterruptedException e) { } blinkOn = !blinkOn; } } }.start(); } public void onDestroy() { super.onDestroy(); stopLed = true; } @Override public void onColorChanged(int color) { if (DEBUG) { Log.d(TAG, "currentSelectedApp = " + currentSelectedApp); } if (currentSelectedApp == 0) { Settings.System.putInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_COLOR, color); userColor = Settings.System.getInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_COLOR, defaultColor); } else if (currentSelectedApp == unicornApps.size()) { // do nothing on this one // it really should never even be the currentSelectedApp but just in // case! } else { userColor = color; int realAppInt = currentSelectedApp - 1; String hashKey = appList.get(realAppInt); appList.remove(realAppInt); unicornApps.remove(currentSelectedApp); customAppList.remove(hashKey); addCustomApp(hashKey); saveCustomApps(); } refreshSettings(); } private String getTimeString(int milliSeconds) { float seconds = (float) milliSeconds / 1000; DecimalFormat df = new DecimalFormat("0.#"); String time = df.format(seconds) + getResources().getString(R.string.led_time_seconds); return time; } private void refreshSettings() { int on = mResources .getInteger(com.android.internal.R.integer.config_defaultNotificationLedOn); int off = mResources .getInteger(com.android.internal.R.integer.config_defaultNotificationLedOff); onBlink = Settings.System.getInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_ON, on); offBlink = Settings.System.getInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_OFF, off); mOnTime.setText(getTimeString(onBlink)); mOffTime.setText(getTimeString(offBlink)); mLEDButton.setColorFilter(userColor, PorterDuff.Mode.MULTIPLY); mLedScreenOn.setChecked(Settings.Secure.getInt(mActivity.getContentResolver(), Settings.Secure.LED_SCREEN_ON, 0) == 1); String charging_led_enabled = Helpers.getSystemProp(PROP_CHARGING_LED, "0"); if (charging_led_enabled.length() == 0) { charging_led_enabled = "0"; } mChargingLedOn.setChecked(Integer.parseInt(charging_led_enabled) == 1); } private void saveCustomApps() { List<String> moveToSettings = new ArrayList<String>(); if (customAppList != null) { for (CustomApps ca : customAppList.values()) { moveToSettings.add(ca.toString()); } final String value = TextUtils.join("|", moveToSettings); if (DEBUG) { Log.e(TAG, "Saved to Settings: " + value); } Settings.System.putString(mActivity.getContentResolver(), Settings.System.LED_CUSTOM_VALUES, value); } } private void addCustomApp(String app) { CustomApps custom = customAppList.get(app); if (custom == null) { custom = new CustomApps(app, userColor); customAppList.put(app, custom); appList.add(app); putAppInUnicornList(app); } } private void addCustomApp(String app, int color) { CustomApps custom = customAppList.get(app); if (custom == null) { custom = new CustomApps(app, color); customAppList.put(app, custom); appList.add(app); putAppInUnicornList(app); } } private void putAppInUnicornList(String packageName) { final PackageManager pm = mActivity.getPackageManager(); ApplicationInfo ai; try { ai = pm.getApplicationInfo(packageName, 0); } catch (final NameNotFoundException e) { ai = null; } final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "unknown"); unicornApps.add(unicornApps.size() - 1, applicationName); adapterRefreshSetting(); } private void parseExistingAppList() { String currentApps = Settings.System.getString(mActivity.getContentResolver(), Settings.System.LED_CUSTOM_VALUES); unicornApps.add(getResources().getString(R.string.led_custom_default)); unicornApps.add("+App"); if (DEBUG) { Log.e(TAG, "currentApps parsed: " + currentApps); } if (currentApps != null) { final String[] array = TextUtils.split(currentApps, "\\|"); for (String item : array) { if (TextUtils.isEmpty(item)) { continue; } CustomApps app = CustomApps.fromString(item); if (app != null) { addCustomApp(app.appPackage, app.appColor); } } } } private void updateLEDforNew(int id) { if (id != 0 && id != unicornApps.size()) { int key = id - 1; String hashKey = appList.get(key); CustomApps custom = customAppList.get(hashKey); userColor = custom.appColor; if (DEBUG) { Log.d(TAG, "user color from Hash = " + userColor); } } else if (id == 0) { userColor = Settings.System.getInt(mActivity.getContentResolver(), Settings.System.NOTIFICATION_LIGHT_COLOR, defaultColor); if (DEBUG) { Log.d(TAG, "user color from Hash = " + userColor); } } } /** * Let's make a spinner class for the listed apps Default should always be * on top +App should be at bottom */ class customAppSpinnerSelected implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (pos == unicornApps.size() - 1) { mPicker.pickShortcut(); if (DEBUG) { Log.e(TAG, "Pick a shortcut from click!"); } } if (pos != unicornApps.size() - 1) { updateLEDforNew(pos); } currentSelectedApp = pos; editButtonVisibility(); } @Override public void onNothingSelected(AdapterView<?> parent) { // do nothing } } class buttonEditApp implements View.OnClickListener { @Override public void onClick(View v) { final int place = currentSelectedApp; String selectedApp = unicornApps.get(place); AlertDialog.Builder ad = new AlertDialog.Builder(mActivity); ad.setTitle(R.string.led_custom_title); ad.setIcon(R.mipmap.ic_launcher); ad.setMessage( getResources().getString(R.string.led_custom_message) + selectedApp + "?"); ad.setPositiveButton(R.string.led_change_app, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mPicker.pickShortcut(); int key = place - 1; unicornApps.remove(place); String hashKey = appList.get(key); appList.remove(key); customAppList.remove(hashKey); adapterRefreshSetting(); saveCustomApps(); } }); ad.setNeutralButton(R.string.led_delete_app, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int key = place - 1; unicornApps.remove(place); String hashKey = appList.get(key); appList.remove(key); customAppList.remove(hashKey); adapterRefreshSetting(); saveCustomApps(); } }); ad.setNegativeButton(R.string.led_keep_app, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.show(); } } private BroadcastReceiver testLedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final NotificationManager nm = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); if (action.equals(Intent.ACTION_SCREEN_OFF)) { Notification.Builder nb = new Notification.Builder(context); nb.setAutoCancel(true); nb.setLights(userColor, onBlink, offBlink); Notification test = nb.getNotification(); nm.notify(1, test); } else if (action.equals(Intent.ACTION_SCREEN_ON)) { nm.cancel(1); } } }; /** * Create our own class for custom apps for easier time with HashMap storage * also make it static so it doesnt destroy the information when the class * is not in use */ static class CustomApps { public String appPackage; public int appColor; public CustomApps(String appPackage, int appColor) { this.appPackage = appPackage; this.appColor = appColor; } // create a string to return with a char to split from later public String toString() { StringBuilder sb = new StringBuilder(); sb.append(appPackage); sb.append(";"); sb.append(appColor); return sb.toString(); } public static CustomApps fromString(String value) { if (TextUtils.isEmpty(value)) { return null; } String[] app = value.split(";", -1); if (app.length != 2) { return null; } try { CustomApps item = new CustomApps(app[0], Integer.parseInt(app[1])); return item; } catch (NumberFormatException e) { return null; } } } private void editButtonVisibility() { if (currentSelectedApp == 0 || currentSelectedApp == unicornApps.size()) { mEditApp.setVisibility(View.GONE); } else { mEditApp.setVisibility(View.VISIBLE); } } @Override public void shortcutPicked(String uri, String friendlyName, Bitmap icon, boolean isApplication) { String packageName = null; final PackageManager pm = mActivity.getPackageManager(); try { Intent intent = Intent.getIntent(uri); packageName = intent.resolveActivity(pm).getPackageName(); if (DEBUG) { Log.e(TAG, uri); } if (DEBUG) { Log.e(TAG, packageName); } } catch (URISyntaxException e) { } if (packageName != null) { addCustomApp(packageName); saveCustomApps(); } } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { mPicker.onActivityResult(requestCode, resultCode, data); } else if (resultCode == Activity.RESULT_CANCELED && data != null) { // do nothing + } else if (resultCode == Activity.RESULT_CANCELED && data == null) { + mListApps.setSelection(0); } super.onActivityResult(requestCode, resultCode, data); } }
false
false
null
null
diff --git a/src/org/apache/xalan/transformer/KeyWalker.java b/src/org/apache/xalan/transformer/KeyWalker.java index 3534cdc1..42eadf91 100644 --- a/src/org/apache/xalan/transformer/KeyWalker.java +++ b/src/org/apache/xalan/transformer/KeyWalker.java @@ -1,277 +1,283 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xalan.transformer; import java.util.Vector; import org.apache.xpath.axes.LocPathIterator; import org.apache.xml.utils.PrefixResolver; import org.apache.xml.utils.QName; import org.apache.xalan.templates.KeyDeclaration; +import org.apache.xalan.res.XSLMessages; +import org.apache.xalan.res.XSLTErrorResources; import org.apache.xpath.XPathContext; import org.apache.xpath.axes.DescendantOrSelfWalker; import org.apache.xpath.objects.XObject; import org.apache.xpath.XPath; import org.w3c.dom.Node; import org.w3c.dom.DOMException; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.traversal.NodeFilter; import org.w3c.dom.traversal.NodeIterator; import javax.xml.transform.TransformerException; /** * <meta name="usage" content="internal"/> * Walker for a Key() function. */ public class KeyWalker extends DescendantOrSelfWalker { /** * Construct a KeyWalker using a LocPathIterator. * * @param locPathIterator: this is usually a KeyIterator */ public KeyWalker(LocPathIterator locPathIterator) { super(locPathIterator); } /** * Set the root node of the TreeWalker. * * @param root Document root node */ public void setRoot(Node root) { m_attrs = null; m_foundAttrs = false; m_attrPos = 0; super.setRoot(root); } /** List of attribute nodes of the current node */ transient NamedNodeMap m_attrs; /** Flag indicating that attibute nodes were found for the current node */ transient boolean m_foundAttrs; /** Current position in the attribute nodes list */ transient int m_attrPos; /** Key value that this is looking for. * @serial */ String m_lookupKey; /** * Get the next node in document order on the axes. * * @return The next node found or null. */ protected Node getNextNode() { if (!m_foundAttrs) { m_attrs = getCurrentNode().getAttributes(); m_foundAttrs = true; } if (null != m_attrs) { if (m_attrPos < m_attrs.getLength()) { return m_attrs.item(m_attrPos++); } else { m_attrs = null; } } Node next = super.getNextNode(); if (null != next) m_foundAttrs = false; return next; } /** * Test whether a specified node is visible in the logical view of a * TreeWalker or NodeIterator. This function will be called by the * implementation of TreeWalker and NodeIterator; it is not intended to * be called directly from user code. * * @param testnode The node to check to see if it passes the filter or not. * * @return a constant to determine whether the node is accepted, * rejected, or skipped, as defined above . */ public short acceptNode(Node testNode) { - + boolean foundKey = false; KeyIterator ki = (KeyIterator) m_lpi; Vector keys = ki.getKeyDeclarations(); QName name = ki.getName(); try { String lookupKey = m_lookupKey; // System.out.println("lookupKey: "+lookupKey); int nDeclarations = keys.size(); // Walk through each of the declarations made with xsl:key for (int i = 0; i < nDeclarations; i++) { KeyDeclaration kd = (KeyDeclaration) keys.elementAt(i); // Only continue if the name on this key declaration // matches the name on the iterator for this walker. if(!kd.getName().equals(name)) continue; + foundKey = true; ki.getXPathContext().setNamespaceContext(ki.getPrefixResolver()); // See if our node matches the given key declaration according to // the match attribute on xsl:key. double score = kd.getMatch().getMatchScore(ki.getXPathContext(), testNode); if (score == kd.getMatch().MATCH_SCORE_NONE) continue; // Query from the node, according the the select pattern in the // use attribute in xsl:key. XObject xuse = kd.getUse().execute(ki.getXPathContext(), testNode, ki.getPrefixResolver()); if (xuse.getType() != xuse.CLASS_NODESET) { String exprResult = xuse.str(); ((KeyIterator)m_lpi).addRefNode(exprResult, testNode); if (lookupKey.equals(exprResult)) return this.FILTER_ACCEPT; } else { NodeIterator nl = xuse.nodeset(); Node useNode; short result = -1; /* We are walking through all the nodes in this nodeset rather than stopping when we find the one we're looking for because we don't currently save the state of KeyWalker such that the next time it gets called it would continue to look in this nodeset for any further matches. TODO: Try to save the state of KeyWalker, i.e. keep this node iterator saved somewhere and finish walking through its nodes the next time KeyWalker is called before we look for any new matches. What if the next call is for the same match+use combination?? */ while (null != (useNode = nl.nextNode())) { String exprResult = m_lpi.getDOMHelper().getNodeData(useNode); ((KeyIterator)m_lpi).addRefNode(exprResult, testNode); if ((null != exprResult) && lookupKey.equals(exprResult)) result = this.FILTER_ACCEPT; //return this.FILTER_ACCEPT; } if (-1 != result) return result; } } // end for(int i = 0; i < nDeclarations; i++) } catch (TransformerException se) { // TODO: What to do? } + if (!foundKey) + throw new RuntimeException + (XSLMessages.createMessage(XSLTErrorResources.ER_NO_XSLKEY_DECLARATION, new Object[]{name.getLocalName()})); return this.FILTER_REJECT; } /** * Moves the <code>TreeWalker</code> to the next visible node in document * order relative to the current node, and returns the new node. If the * current node has no next node, or if the search for nextNode attempts * to step upward from the TreeWalker's root node, returns * <code>null</code> , and retains the current node. * * @return The new node, or <code>null</code> if the current node has no * next node in the TreeWalker's logical view. */ public Node nextNode() { Node node = super.nextNode(); // If there is no next node, we have walked the whole source tree. // Notify the iterator of that so that its callers know that there // are no more nodes to be found. if (node == null) ((KeyIterator)m_lpi).setLookForMoreNodes(false); return node; } }
false
false
null
null
diff --git a/src/com/vaadin/terminal/gwt/server/AbstractApplicationServlet.java b/src/com/vaadin/terminal/gwt/server/AbstractApplicationServlet.java index 250299905..bb544798a 100644 --- a/src/com/vaadin/terminal/gwt/server/AbstractApplicationServlet.java +++ b/src/com/vaadin/terminal/gwt/server/AbstractApplicationServlet.java @@ -1,2350 +1,2349 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.terminal.gwt.server; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.vaadin.Application; import com.vaadin.Application.SystemMessages; import com.vaadin.terminal.DownloadStream; import com.vaadin.terminal.ParameterHandler; import com.vaadin.terminal.Terminal; import com.vaadin.terminal.ThemeResource; import com.vaadin.terminal.URIHandler; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.ui.Window; /** * Abstract implementation of the ApplicationServlet which handles all * communication between the client and the server. * * It is possible to extend this class to provide own functionality but in most * cases this is unnecessary. * * * @author IT Mill Ltd. * @version * @VERSION@ * @since 6.0 */ @SuppressWarnings("serial") public abstract class AbstractApplicationServlet extends HttpServlet implements Constants { // TODO Move some (all?) of the constants to a separate interface (shared // with portlet) private static final Logger logger = Logger .getLogger(AbstractApplicationServlet.class.getName()); /** * The version number of this release. For example "6.2.0". Always in the * format "major.minor.revision[.build]". The build part is optional. All of * major, minor, revision must be integers. */ public static final String VERSION; /** * Major version number. For example 6 in 6.2.0. */ public static final int VERSION_MAJOR; /** * Minor version number. For example 2 in 6.2.0. */ public static final int VERSION_MINOR; /** * Version revision number. For example 0 in 6.2.0. */ public static final int VERSION_REVISION; /** * Build identifier. For example "nightly-20091123-c9963" in * 6.2.0.nightly-20091123-c9963. */ public static final String VERSION_BUILD; /* Initialize version numbers from string replaced by build-script. */ static { if ("@VERSION@".equals("@" + "VERSION" + "@")) { VERSION = "9.9.9.INTERNAL-DEBUG-BUILD"; } else { VERSION = "@VERSION@"; } final String[] digits = VERSION.split("\\.", 4); VERSION_MAJOR = Integer.parseInt(digits[0]); VERSION_MINOR = Integer.parseInt(digits[1]); VERSION_REVISION = Integer.parseInt(digits[2]); if (digits.length == 4) { VERSION_BUILD = digits[3]; } else { VERSION_BUILD = ""; } } /** * If the attribute is present in the request, a html fragment will be * written instead of a whole page. * * It is set to "true" by the {@link ApplicationPortlet} (Portlet 1.0) and * read by {@link AbstractApplicationServlet}. */ public static final String REQUEST_FRAGMENT = ApplicationServlet.class .getName() + ".fragment"; /** * This request attribute forces widgetsets to be loaded from under the * specified base path; e.g shared widgetset for all portlets in a portal. * * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on * {@link Constants.PORTAL_PARAMETER_VAADIN_RESOURCE_PATH} and read by * {@link AbstractApplicationServlet}. */ public static final String REQUEST_VAADIN_STATIC_FILE_PATH = ApplicationServlet.class .getName() + ".widgetsetPath"; /** * This request attribute forces widgetset used; e.g for portlets that can * not have different widgetsets. * * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on * {@link ApplicationPortlet.PORTLET_PARAMETER_WIDGETSET} and read by * {@link AbstractApplicationServlet}. */ public static final String REQUEST_WIDGETSET = ApplicationServlet.class .getName() + ".widgetset"; /** * This request attribute indicates the shared widgetset (e.g. portal-wide * default widgetset). * * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on * {@link Constants.PORTAL_PARAMETER_VAADIN_WIDGETSET} and read by * {@link AbstractApplicationServlet}. */ public static final String REQUEST_SHARED_WIDGETSET = ApplicationServlet.class .getName() + ".sharedWidgetset"; /** * If set, do not load the default theme but assume that loading it is * handled e.g. by ApplicationPortlet. * * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on * {@link Constants.PORTAL_PARAMETER_VAADIN_THEME} and read by * {@link AbstractApplicationServlet}. */ public static final String REQUEST_DEFAULT_THEME = ApplicationServlet.class .getName() + ".defaultThemeUri"; /** * This request attribute is used to add styles to the main element. E.g * "height:500px" generates a style="height:500px" to the main element, * useful from some embedding situations (e.g portlet include.) * * It is typically set by the {@link ApplicationPortlet} (Portlet 1.0) based * on {@link ApplicationPortlet.PORTLET_PARAMETER_STYLE} and read by * {@link AbstractApplicationServlet}. */ public static final String REQUEST_APPSTYLE = ApplicationServlet.class .getName() + ".style"; private Properties applicationProperties; private boolean productionMode = false; private final String resourcePath = null; private int resourceCacheTime = 3600; static final String UPLOAD_URL_PREFIX = "APP/UPLOAD/"; /** * Called by the servlet container to indicate to a servlet that the servlet * is being placed into service. * * @param servletConfig * the object containing the servlet's configuration and * initialization parameters * @throws javax.servlet.ServletException * if an exception has occurred that interferes with the * servlet's normal operation. */ @SuppressWarnings("unchecked") @Override public void init(javax.servlet.ServletConfig servletConfig) throws javax.servlet.ServletException { super.init(servletConfig); // Stores the application parameters into Properties object applicationProperties = new Properties(); for (final Enumeration<String> e = servletConfig .getInitParameterNames(); e.hasMoreElements();) { final String name = e.nextElement(); applicationProperties.setProperty(name, servletConfig.getInitParameter(name)); } // Overrides with server.xml parameters final ServletContext context = servletConfig.getServletContext(); for (final Enumeration<String> e = context.getInitParameterNames(); e .hasMoreElements();) { final String name = e.nextElement(); applicationProperties.setProperty(name, context.getInitParameter(name)); } checkProductionMode(); checkCrossSiteProtection(); checkResourceCacheTime(); } private void checkCrossSiteProtection() { if (getApplicationOrSystemProperty( SERVLET_PARAMETER_DISABLE_XSRF_PROTECTION, "false").equals( "true")) { /* * Print an information/warning message about running with xsrf * protection disabled */ logger.warning(WARNING_XSRF_PROTECTION_DISABLED); } } private void checkProductionMode() { // Check if the application is in production mode. // We are in production mode if Debug=false or productionMode=true if (getApplicationOrSystemProperty(SERVLET_PARAMETER_DEBUG, "true") .equals("false")) { // "Debug=true" is the old way and should no longer be used productionMode = true; } else if (getApplicationOrSystemProperty( SERVLET_PARAMETER_PRODUCTION_MODE, "false").equals("true")) { // "productionMode=true" is the real way to do it productionMode = true; } if (!productionMode) { /* Print an information/warning message about running in debug mode */ logger.warning(NOT_PRODUCTION_MODE_INFO); } } private void checkResourceCacheTime() { // Check if the browser caching time has been set in web.xml try { String rct = getApplicationOrSystemProperty( SERVLET_PARAMETER_RESOURCE_CACHE_TIME, "3600"); resourceCacheTime = Integer.parseInt(rct); } catch (NumberFormatException nfe) { // Default is 1h resourceCacheTime = 3600; logger.warning(WARNING_RESOURCE_CACHING_TIME_NOT_NUMERIC); } } /** * Gets an application property value. * * @param parameterName * the Name or the parameter. * @return String value or null if not found */ protected String getApplicationProperty(String parameterName) { String val = applicationProperties.getProperty(parameterName); if (val != null) { return val; } // Try lower case application properties for backward compatibility with // 3.0.2 and earlier val = applicationProperties.getProperty(parameterName.toLowerCase()); return val; } /** * Gets an system property value. * * @param parameterName * the Name or the parameter. * @return String value or null if not found */ protected String getSystemProperty(String parameterName) { String val = null; String pkgName; final Package pkg = getClass().getPackage(); if (pkg != null) { pkgName = pkg.getName(); } else { final String className = getClass().getName(); pkgName = new String(className.toCharArray(), 0, className.lastIndexOf('.')); } val = System.getProperty(pkgName + "." + parameterName); if (val != null) { return val; } // Try lowercased system properties val = System.getProperty(pkgName + "." + parameterName.toLowerCase()); return val; } /** * Gets an application or system property value. * * @param parameterName * the Name or the parameter. * @param defaultValue * the Default to be used. * @return String value or default if not found */ private String getApplicationOrSystemProperty(String parameterName, String defaultValue) { String val = null; // Try application properties val = getApplicationProperty(parameterName); if (val != null) { return val; } // Try system properties val = getSystemProperty(parameterName); if (val != null) { return val; } return defaultValue; } /** * Returns true if the servlet is running in production mode. Production * mode disables all debug facilities. * * @return true if in production mode, false if in debug mode */ public boolean isProductionMode() { return productionMode; } /** * Returns the amount of milliseconds the browser should cache a file. * Default is 1 hour (3600 ms). * * @return The amount of milliseconds files are cached in the browser */ public int getResourceCacheTime() { return resourceCacheTime; } /** * Receives standard HTTP requests from the public service method and * dispatches them. * * @param request * the object that contains the request the client made of the * servlet. * @param response * the object that contains the response the servlet returns to * the client. * @throws ServletException * if an input or output error occurs while the servlet is * handling the TRACE request. * @throws IOException * if the request for the TRACE cannot be handled. */ @SuppressWarnings("unchecked") @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestType requestType = getRequestType(request); if (!ensureCookiesEnabled(requestType, request, response)) { return; } if (requestType == RequestType.STATIC_FILE) { serveStaticResources(request, response); return; } Application application = null; boolean transactionStarted = false; boolean requestStarted = false; try { // If a duplicate "close application" URL is received for an // application that is not open, redirect to the application's main // page. // This is needed as e.g. Spring Security remembers the last // URL from the application, which is the logout URL, and repeats // it. // We can tell apart a real onunload request from a repeated one // based on the real one having content (at least the UIDL security // key). if (requestType == RequestType.UIDL && request.getParameterMap().containsKey( ApplicationConnection.PARAM_UNLOADBURST) && request.getContentLength() < 1 && getExistingApplication(request, false) == null) { redirectToApplication(request, response); return; } // Find out which application this request is related to application = findApplicationInstance(request, requestType); if (application == null) { return; } /* * Get or create a WebApplicationContext and an ApplicationManager * for the session */ WebApplicationContext webApplicationContext = WebApplicationContext .getApplicationContext(request.getSession()); CommunicationManager applicationManager = webApplicationContext .getApplicationManager(application, this); /* Update browser information from the request */ updateBrowserProperties(webApplicationContext.getBrowser(), request); /* * Call application requestStart before Application.init() is called * (bypasses the limitation in TransactionListener) */ if (application instanceof HttpServletRequestListener) { ((HttpServletRequestListener) application).onRequestStart( request, response); requestStarted = true; } // Start the newly created application startApplication(request, application, webApplicationContext); /* * Transaction starts. Call transaction listeners. Transaction end * is called in the finally block below. */ webApplicationContext.startTransaction(application, request); transactionStarted = true; /* Handle the request */ if (requestType == RequestType.FILE_UPLOAD) { applicationManager.handleFileUpload(request, response); return; } else if (requestType == RequestType.UIDL) { // Handles AJAX UIDL requests Window window = applicationManager.getApplicationWindow( request, this, application, null); applicationManager.handleUidlRequest(request, response, this, window); return; } // Removes application if it has stopped (mayby by thread or // transactionlistener) if (!application.isRunning()) { endApplication(request, response, application); return; } // Finds the window within the application Window window = getApplicationWindow(request, applicationManager, application); if (window == null) { throw new ServletException(ERROR_NO_WINDOW_FOUND); } // Sets terminal type for the window, if not already set if (window.getTerminal() == null) { window.setTerminal(webApplicationContext.getBrowser()); } // Handle parameters final Map<String, String[]> parameters = request.getParameterMap(); if (window != null && parameters != null) { window.handleParameters(parameters); } /* * Call the URI handlers and if this turns out to be a download * request, send the file to the client */ if (handleURI(applicationManager, window, request, response)) { return; } // Send initial AJAX page that kickstarts a Vaadin application writeAjaxPage(request, response, window, application); } catch (final SessionExpiredException e) { // Session has expired, notify user handleServiceSessionExpired(request, response); } catch (final GeneralSecurityException e) { handleServiceSecurityException(request, response); } catch (final Throwable e) { handleServiceException(request, response, application, e); } finally { // Notifies transaction end try { if (transactionStarted) { ((WebApplicationContext) application.getContext()) .endTransaction(application, request); } } finally { if (requestStarted) { ((HttpServletRequestListener) application).onRequestEnd( request, response); } } } } /** * Check that cookie support is enabled in the browser. Only checks UIDL * requests. * * @param requestType * Type of the request as returned by * {@link #getRequestType(HttpServletRequest)} * @param request * The request from the browser * @param response * The response to which an error can be written * @return false if cookies are disabled, true otherwise * @throws IOException */ private boolean ensureCookiesEnabled(RequestType requestType, HttpServletRequest request, HttpServletResponse response) throws IOException { if (requestType == RequestType.UIDL && !isRepaintAll(request)) { // In all other but the first UIDL request a cookie should be // returned by the browser. // This can be removed if cookieless mode (#3228) is supported if (request.getRequestedSessionId() == null) { // User has cookies disabled criticalNotification(request, response, getSystemMessages() .getCookiesDisabledCaption(), getSystemMessages() .getCookiesDisabledMessage(), null, getSystemMessages() .getCookiesDisabledURL()); return false; } } return true; } private void updateBrowserProperties(WebBrowser browser, HttpServletRequest request) { browser.updateBrowserProperties(request.getLocale(), request.getRemoteAddr(), request.isSecure(), request.getHeader("user-agent"), request.getParameter("sw"), request.getParameter("sh")); } protected ClassLoader getClassLoader() throws ServletException { // Gets custom class loader final String classLoaderName = getApplicationOrSystemProperty( "ClassLoader", null); ClassLoader classLoader; if (classLoaderName == null) { classLoader = getClass().getClassLoader(); } else { try { final Class<?> classLoaderClass = getClass().getClassLoader() .loadClass(classLoaderName); final Constructor<?> c = classLoaderClass .getConstructor(new Class[] { ClassLoader.class }); classLoader = (ClassLoader) c .newInstance(new Object[] { getClass().getClassLoader() }); } catch (final Exception e) { throw new ServletException( "Could not find specified class loader: " + classLoaderName, e); } } return classLoader; } /** * Send a notification to client's application. Used to notify client of * critical errors, session expiration and more. Server has no knowledge of * what application client refers to. * * @param request * the HTTP request instance. * @param response * the HTTP response to write to. * @param caption * the notification caption * @param message * to notification body * @param details * a detail message to show in addition to the message. Currently * shown directly below the message but could be hidden behind a * details drop down in the future. Mainly used to give * additional information not necessarily useful to the end user. * @param url * url to load when the message is dismissed. Null will reload * the current page. * @throws IOException * if the writing failed due to input/output error. */ protected final void criticalNotification(HttpServletRequest request, HttpServletResponse response, String caption, String message, String details, String url) throws IOException { if (isUIDLRequest(request)) { if (caption != null) { caption = "\"" + JsonPaintTarget.escapeJSON(caption) + "\""; } if (details != null) { if (message == null) { message = details; } else { message += "<br/><br/>" + details; } } if (message != null) { message = "\"" + JsonPaintTarget.escapeJSON(message) + "\""; } if (url != null) { url = "\"" + JsonPaintTarget.escapeJSON(url) + "\""; } String output = "for(;;);[{\"changes\":[], \"meta\" : {" + "\"appError\": {" + "\"caption\":" + caption + "," + "\"message\" : " + message + "," + "\"url\" : " + url + "}}, \"resources\": {}, \"locales\":[]}]"; writeResponse(response, "application/json; charset=UTF-8", output); } else { // Create an HTML reponse with the error String output = ""; if (url != null) { output += "<a href=\"" + url + "\">"; } if (caption != null) { output += "<b>" + caption + "</b><br/>"; } if (message != null) { output += message; output += "<br/><br/>"; } if (details != null) { output += details; output += "<br/><br/>"; } if (url != null) { output += "</a>"; } writeResponse(response, "text/html; charset=UTF-8", output); } } /** * Writes the response in {@code output} using the contentType given in * {@code contentType} to the provided {@link HttpServletResponse} * * @param response * @param contentType * @param output * Output to write (UTF-8 encoded) * @throws IOException */ private void writeResponse(HttpServletResponse response, String contentType, String output) throws IOException { response.setContentType(contentType); final ServletOutputStream out = response.getOutputStream(); // Set the response type final PrintWriter outWriter = new PrintWriter(new BufferedWriter( new OutputStreamWriter(out, "UTF-8"))); outWriter.print(output); outWriter.flush(); outWriter.close(); out.flush(); } /** * Returns the application instance to be used for the request. If an * existing instance is not found a new one is created or null is returned * to indicate that the application is not available. * * @param request * @param requestType * @return * @throws MalformedURLException * @throws IllegalAccessException * @throws InstantiationException * @throws ServletException * @throws SessionExpiredException */ private Application findApplicationInstance(HttpServletRequest request, RequestType requestType) throws MalformedURLException, ServletException, SessionExpiredException { boolean requestCanCreateApplication = requestCanCreateApplication( request, requestType); /* Find an existing application for this request. */ Application application = getExistingApplication(request, requestCanCreateApplication); if (application != null) { /* * There is an existing application. We can use this as long as the * user not specifically requested to close or restart it. */ final boolean restartApplication = (request .getParameter(URL_PARAMETER_RESTART_APPLICATION) != null); final boolean closeApplication = (request .getParameter(URL_PARAMETER_CLOSE_APPLICATION) != null); if (restartApplication) { closeApplication(application, request.getSession(false)); return createApplication(request); } else if (closeApplication) { closeApplication(application, request.getSession(false)); return null; } else { return application; } } // No existing application was found if (requestCanCreateApplication) { /* * If the request is such that it should create a new application if * one as not found, we do that. */ return createApplication(request); } else { /* * The application was not found and a new one should not be * created. Assume the session has expired. */ throw new SessionExpiredException(); } } /** * Check if the request should create an application if an existing * application is not found. * * @param request * @param requestType * @return true if an application should be created, false otherwise */ boolean requestCanCreateApplication(HttpServletRequest request, RequestType requestType) { if (requestType == RequestType.UIDL && isRepaintAll(request)) { /* * UIDL request contains valid repaintAll=1 event, the user probably * wants to initiate a new application through a custom index.html * without using writeAjaxPage. */ return true; } else if (requestType == RequestType.OTHER) { /* * I.e URIs that are not application resources or static (theme) * files. */ return true; } return false; } /** * Gets resource path using different implementations. Required to * supporting different servlet container implementations (application * servers). * * @param servletContext * @param path * the resource path. * @return the resource path. */ protected static String getResourcePath(ServletContext servletContext, String path) { String resultPath = null; resultPath = servletContext.getRealPath(path); if (resultPath != null) { return resultPath; } else { try { final URL url = servletContext.getResource(path); resultPath = url.getFile(); } catch (final Exception e) { // FIXME: Handle exception logger.log(Level.INFO, "Could not find resource path " + path, e); } } return resultPath; } /** * Handles the requested URI. An application can add handlers to do special * processing, when a certain URI is requested. The handlers are invoked * before any windows URIs are processed and if a DownloadStream is returned * it is sent to the client. * * @param stream * the download stream. * * @param request * the HTTP request instance. * @param response * the HTTP response to write to. * @throws IOException * * @see com.vaadin.terminal.URIHandler */ private void handleDownload(DownloadStream stream, HttpServletRequest request, HttpServletResponse response) throws IOException { if (stream.getParameter("Location") != null) { response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.addHeader("Location", stream.getParameter("Location")); return; } // Download from given stream final InputStream data = stream.getStream(); if (data != null) { // Sets content type response.setContentType(stream.getContentType()); // Sets cache headers final long cacheTime = stream.getCacheTime(); if (cacheTime <= 0) { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); } else { response.setHeader("Cache-Control", "max-age=" + cacheTime / 1000); response.setDateHeader("Expires", System.currentTimeMillis() + cacheTime); response.setHeader("Pragma", "cache"); // Required to apply // caching in some // Tomcats } // Copy download stream parameters directly // to HTTP headers. final Iterator<String> i = stream.getParameterNames(); if (i != null) { while (i.hasNext()) { final String param = i.next(); response.setHeader(param, stream.getParameter(param)); } } // suggest local filename from DownloadStream if Content-Disposition // not explicitly set String contentDispositionValue = stream .getParameter("Content-Disposition"); if (contentDispositionValue == null) { contentDispositionValue = "filename=\"" + stream.getFileName() + "\""; response.setHeader("Content-Disposition", contentDispositionValue); } int bufferSize = stream.getBufferSize(); if (bufferSize <= 0 || bufferSize > MAX_BUFFER_SIZE) { bufferSize = DEFAULT_BUFFER_SIZE; } final byte[] buffer = new byte[bufferSize]; int bytesRead = 0; final OutputStream out = response.getOutputStream(); while ((bytesRead = data.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); out.flush(); } out.close(); data.close(); } } /** * Creates a new application and registers it into WebApplicationContext * (aka session). This is not meant to be overridden. Override * getNewApplication to create the application instance in a custom way. * * @param request * @return * @throws ServletException * @throws MalformedURLException */ private Application createApplication(HttpServletRequest request) throws ServletException, MalformedURLException { Application newApplication = getNewApplication(request); final WebApplicationContext context = WebApplicationContext .getApplicationContext(request.getSession()); context.addApplication(newApplication); return newApplication; } private void handleServiceException(HttpServletRequest request, HttpServletResponse response, Application application, Throwable e) throws IOException, ServletException { // if this was an UIDL request, response UIDL back to client if (getRequestType(request) == RequestType.UIDL) { Application.SystemMessages ci = getSystemMessages(); criticalNotification(request, response, ci.getInternalErrorCaption(), ci.getInternalErrorMessage(), null, ci.getInternalErrorURL()); if (application != null) { application.getErrorHandler() .terminalError(new RequestError(e)); } else { throw new ServletException(e); } } else { // Re-throw other exceptions throw new ServletException(e); } } /** * Returns the theme for given request/window * * @param request * @param window * @return */ private String getThemeForWindow(HttpServletRequest request, Window window) { // Finds theme name String themeName; if (request.getParameter(URL_PARAMETER_THEME) != null) { themeName = request.getParameter(URL_PARAMETER_THEME); } else { themeName = window.getTheme(); } if (themeName == null) { // no explicit theme for window defined if (request.getAttribute(REQUEST_DEFAULT_THEME) != null) { // the default theme is defined in request (by portal) themeName = (String) request .getAttribute(REQUEST_DEFAULT_THEME); } else { // using the default theme defined by Vaadin themeName = getDefaultTheme(); } } // XSS preventation, theme names shouldn't contain special chars anyway. // The servlet denies them via url parameter. themeName = stripSpecialChars(themeName); return themeName; } /** - * A helper method to strip away (replace with spaces) characters that might - * somehow be used for XSS attacs. Leaves at least alphanumeric characters - * intact. Also removes eg. ( and ), so values should be safe in javascript - * too. + * A helper method to strip away characters that might somehow be used for + * XSS attacs. Leaves at least alphanumeric characters intact. Also removes + * eg. ( and ), so values should be safe in javascript too. * * @param themeName * @return */ protected static String stripSpecialChars(String themeName) { StringBuilder sb = new StringBuilder(); char[] charArray = themeName.toCharArray(); for (int i = 0; i < charArray.length; i++) { char c = charArray[i]; if (!CHAR_BLACKLIST.contains(c)) { sb.append(c); } } return sb.toString(); } private static final Collection<Character> CHAR_BLACKLIST = new HashSet<Character>( Arrays.asList(new Character[] { '&', '"', '\'', '<', '>', '(', ')', ';' })); /** * Returns the default theme. Must never return null. * * @return */ public static String getDefaultTheme() { return DEFAULT_THEME_NAME; } /** * Calls URI handlers for the request. If an URI handler returns a * DownloadStream the stream is passed to the client for downloading. * * @param applicationManager * @param window * @param request * @param response * @return true if an DownloadStream was sent to the client, false otherwise * @throws IOException */ protected boolean handleURI(CommunicationManager applicationManager, Window window, HttpServletRequest request, HttpServletResponse response) throws IOException { // Handles the URI DownloadStream download = applicationManager.handleURI(window, request, response, this); // A download request if (download != null) { // Client downloads an resource handleDownload(download, request, response); return true; } return false; } void handleServiceSessionExpired(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (isOnUnloadRequest(request)) { /* * Request was an unload request (e.g. window close event) and the * client expects no response if it fails. */ return; } try { Application.SystemMessages ci = getSystemMessages(); if (getRequestType(request) != RequestType.UIDL) { // 'plain' http req - e.g. browser reload; // just go ahead redirect the browser response.sendRedirect(ci.getSessionExpiredURL()); } else { /* * Invalidate session (weird to have session if we're saying * that it's expired, and worse: portal integration will fail * since the session is not created by the portal. * * Session must be invalidated before criticalNotification as it * commits the response. */ request.getSession().invalidate(); // send uidl redirect criticalNotification(request, response, ci.getSessionExpiredCaption(), ci.getSessionExpiredMessage(), null, ci.getSessionExpiredURL()); } } catch (SystemMessageException ee) { throw new ServletException(ee); } } private void handleServiceSecurityException(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (isOnUnloadRequest(request)) { /* * Request was an unload request (e.g. window close event) and the * client expects no response if it fails. */ return; } try { Application.SystemMessages ci = getSystemMessages(); if (getRequestType(request) != RequestType.UIDL) { // 'plain' http req - e.g. browser reload; // just go ahead redirect the browser response.sendRedirect(ci.getCommunicationErrorURL()); } else { // send uidl redirect criticalNotification(request, response, ci.getCommunicationErrorCaption(), ci.getCommunicationErrorMessage(), INVALID_SECURITY_KEY_MSG, ci.getCommunicationErrorURL()); /* * Invalidate session. Portal integration will fail otherwise * since the session is not created by the portal. */ request.getSession().invalidate(); } } catch (SystemMessageException ee) { throw new ServletException(ee); } log("Invalid security key received from " + request.getRemoteHost()); } /** * Creates a new application for the given request. * * @param request * the HTTP request. * @return A new Application instance. * @throws ServletException */ protected abstract Application getNewApplication(HttpServletRequest request) throws ServletException; /** * Starts the application if it is not already running. * * @param request * @param application * @param webApplicationContext * @throws ServletException * @throws MalformedURLException */ private void startApplication(HttpServletRequest request, Application application, WebApplicationContext webApplicationContext) throws ServletException, MalformedURLException { if (!application.isRunning()) { // Create application final URL applicationUrl = getApplicationUrl(request); // Initial locale comes from the request Locale locale = request.getLocale(); application.setLocale(locale); application.start(applicationUrl, applicationProperties, webApplicationContext); } } /** * Check if this is a request for a static resource and, if it is, serve the * resource to the client. * * @param request * @param response * @return true if a file was served and the request has been handled, false * otherwise. * @throws IOException * @throws ServletException */ private boolean serveStaticResources(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // FIXME What does 10 refer to? String pathInfo = request.getPathInfo(); if (pathInfo == null || pathInfo.length() <= 10) { return false; } if ((request.getContextPath() != null) && (request.getRequestURI().startsWith("/VAADIN/"))) { serveStaticResourcesInVAADIN(request.getRequestURI(), request, response); return true; } else if (request.getRequestURI().startsWith( request.getContextPath() + "/VAADIN/")) { serveStaticResourcesInVAADIN( request.getRequestURI().substring( request.getContextPath().length()), request, response); return true; } return false; } /** * Serve resources from VAADIN directory. * * @param filename * The filename to serve. Should always start with /VAADIN/. * @param request * @param response * @throws IOException * @throws ServletException */ private void serveStaticResourcesInVAADIN(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final ServletContext sc = getServletContext(); URL resourceUrl = sc.getResource(filename); if (resourceUrl == null) { // try if requested file is found from classloader // strip leading "/" otherwise stream from JAR wont work filename = filename.substring(1); resourceUrl = getClassLoader().getResource(filename); if (resourceUrl == null) { // cannot serve requested file logger.info("Requested resource [" + filename + "] not found from filesystem or through class loader." + " Add widgetset and/or theme JAR to your classpath or add files to WebContent/VAADIN folder."); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } // Find the modification timestamp long lastModifiedTime = 0; try { lastModifiedTime = resourceUrl.openConnection().getLastModified(); // Remove milliseconds to avoid comparison problems (milliseconds // are not returned by the browser in the "If-Modified-Since" // header). lastModifiedTime = lastModifiedTime - lastModifiedTime % 1000; if (browserHasNewestVersion(request, lastModifiedTime)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } catch (Exception e) { // Failed to find out last modified timestamp. Continue without it. logger.log( Level.FINEST, "Failed to find out last modified timestamp. Continuing without it.", e); } // Set type mime type if we can determine it based on the filename final String mimetype = sc.getMimeType(filename); if (mimetype != null) { response.setContentType(mimetype); } // Provide modification timestamp to the browser if it is known. if (lastModifiedTime > 0) { response.setDateHeader("Last-Modified", lastModifiedTime); /* * The browser is allowed to cache for 1 hour without checking if * the file has changed. This forces browsers to fetch a new version * when the Vaadin version is updated. This will cause more requests * to the servlet than without this but for high volume sites the * static files should never be served through the servlet. The * cache timeout can be configured by setting the resourceCacheTime * parameter in web.xml */ response.setHeader("Cache-Control", "max-age: " + String.valueOf(resourceCacheTime)); } // Write the resource to the client. final OutputStream os = response.getOutputStream(); final byte buffer[] = new byte[DEFAULT_BUFFER_SIZE]; int bytes; InputStream is = resourceUrl.openStream(); while ((bytes = is.read(buffer)) >= 0) { os.write(buffer, 0, bytes); } is.close(); } /** * Checks if the browser has an up to date cached version of requested * resource. Currently the check is performed using the "If-Modified-Since" * header. Could be expanded if needed. * * @param request * The HttpServletRequest from the browser. * @param resourceLastModifiedTimestamp * The timestamp when the resource was last modified. 0 if the * last modification time is unknown. * @return true if the If-Modified-Since header tells the cached version in * the browser is up to date, false otherwise */ private boolean browserHasNewestVersion(HttpServletRequest request, long resourceLastModifiedTimestamp) { if (resourceLastModifiedTimestamp < 1) { // We do not know when it was modified so the browser cannot have an // up-to-date version return false; } /* * The browser can request the resource conditionally using an * If-Modified-Since header. Check this against the last modification * time. */ try { // If-Modified-Since represents the timestamp of the version cached // in the browser long headerIfModifiedSince = request .getDateHeader("If-Modified-Since"); if (headerIfModifiedSince >= resourceLastModifiedTimestamp) { // Browser has this an up-to-date version of the resource return true; } } catch (Exception e) { // Failed to parse header. Fail silently - the browser does not have // an up-to-date version in its cache. } return false; } protected enum RequestType { FILE_UPLOAD, UIDL, OTHER, STATIC_FILE, APPLICATION_RESOURCE; } protected RequestType getRequestType(HttpServletRequest request) { if (isFileUploadRequest(request)) { return RequestType.FILE_UPLOAD; } else if (isUIDLRequest(request)) { return RequestType.UIDL; } else if (isStaticResourceRequest(request)) { return RequestType.STATIC_FILE; } else if (isApplicationRequest(request)) { return RequestType.APPLICATION_RESOURCE; } else if (request.getHeader("FileId") != null) { return RequestType.FILE_UPLOAD; } return RequestType.OTHER; } private boolean isApplicationRequest(HttpServletRequest request) { String path = getRequestPathInfo(request); if (path != null && path.startsWith("/APP/")) { return true; } return false; } private boolean isStaticResourceRequest(HttpServletRequest request) { String pathInfo = request.getPathInfo(); if (pathInfo == null || pathInfo.length() <= 10) { return false; } if ((request.getContextPath() != null) && (request.getRequestURI().startsWith("/VAADIN/"))) { return true; } else if (request.getRequestURI().startsWith( request.getContextPath() + "/VAADIN/")) { return true; } return false; } private boolean isUIDLRequest(HttpServletRequest request) { String pathInfo = getRequestPathInfo(request); if (pathInfo == null) { return false; } String compare = AJAX_UIDL_URI; if (pathInfo.startsWith(compare + "/") || pathInfo.endsWith(compare)) { return true; } return false; } private boolean isFileUploadRequest(HttpServletRequest request) { String pathInfo = getRequestPathInfo(request); if (pathInfo == null) { return false; } if (pathInfo.startsWith("/" + UPLOAD_URL_PREFIX)) { return true; } return false; } private boolean isOnUnloadRequest(HttpServletRequest request) { return request.getParameter(ApplicationConnection.PARAM_UNLOADBURST) != null; } /** * Get system messages from the current application class * * @return */ protected SystemMessages getSystemMessages() { try { Class<? extends Application> appCls = getApplicationClass(); Method m = appCls.getMethod("getSystemMessages", (Class[]) null); return (Application.SystemMessages) m.invoke(null, (Object[]) null); } catch (ClassNotFoundException e) { // This should never happen throw new SystemMessageException(e); } catch (SecurityException e) { throw new SystemMessageException( "Application.getSystemMessage() should be static public", e); } catch (NoSuchMethodException e) { // This is completely ok and should be silently ignored } catch (IllegalArgumentException e) { // This should never happen throw new SystemMessageException(e); } catch (IllegalAccessException e) { throw new SystemMessageException( "Application.getSystemMessage() should be static public", e); } catch (InvocationTargetException e) { // This should never happen throw new SystemMessageException(e); } return Application.getSystemMessages(); } protected abstract Class<? extends Application> getApplicationClass() throws ClassNotFoundException; /** * Return the URL from where static files, e.g. the widgetset and the theme, * are served. In a standard configuration the VAADIN folder inside the * returned folder is what is used for widgetsets and themes. * * The returned folder is usually the same as the context path and * independent of the application. * * @param request * @return The location of static resources (should contain the VAADIN * directory). Never ends with a slash (/). */ protected String getStaticFilesLocation(HttpServletRequest request) { // request may have an attribute explicitly telling location (portal // case) String staticFileLocation = (String) request .getAttribute(REQUEST_VAADIN_STATIC_FILE_PATH); if (staticFileLocation != null) { // TODO remove trailing slash if any? return staticFileLocation; } return getWebApplicationsStaticFileLocation(request); } /** * The default method to fetch static files location. This method does not * check for request attribute {@value #REQUEST_VAADIN_STATIC_FILE_PATH}. * * @param request * @return */ private String getWebApplicationsStaticFileLocation( HttpServletRequest request) { String staticFileLocation; // if property is defined in configurations, use that staticFileLocation = getApplicationOrSystemProperty( PARAMETER_VAADIN_RESOURCES, null); if (staticFileLocation != null) { return staticFileLocation; } // the last (but most common) option is to generate default location // from request // if context is specified add it to widgetsetUrl String ctxPath = request.getContextPath(); // FIXME: ctxPath.length() == 0 condition is probably unnecessary and // might even be wrong. if (ctxPath.length() == 0 && request.getAttribute("javax.servlet.include.context_path") != null) { // include request (e.g portlet), get context path from // attribute ctxPath = (String) request .getAttribute("javax.servlet.include.context_path"); } // Remove heading and trailing slashes from the context path ctxPath = removeHeadingOrTrailing(ctxPath, "/"); if (ctxPath.equals("")) { return ""; } else { return "/" + ctxPath; } } /** * Remove any heading or trailing "what" from the "string". * * @param string * @param what * @return */ private static String removeHeadingOrTrailing(String string, String what) { while (string.startsWith(what)) { string = string.substring(1); } while (string.endsWith(what)) { string = string.substring(0, string.length() - 1); } return string; } /** * Write a redirect response to the main page of the application. * * @param request * @param response * @throws IOException * if sending the redirect fails due to an input/output error or * a bad application URL */ private void redirectToApplication(HttpServletRequest request, HttpServletResponse response) throws IOException { String applicationUrl = getApplicationUrl(request).toExternalForm(); response.sendRedirect(response.encodeRedirectURL(applicationUrl)); } /** * This method writes the html host page (aka kickstart page) that starts * the actual Vaadin application. * <p> * If one needs to override parts of the host page, it is suggested that one * overrides on of several submethods which are called by this method: * <ul> * <li> {@link #setAjaxPageHeaders(HttpServletResponse)} * <li> {@link #writeAjaxPageHtmlHeadStart(BufferedWriter)} * <li> {@link #writeAjaxPageHtmlHeader(BufferedWriter, String, String)} * <li> {@link #writeAjaxPageHtmlBodyStart(BufferedWriter)} * <li> * {@link #writeAjaxPageHtmlVaadinScripts(Window, String, Application, BufferedWriter, String, String, String, String, String, String)} * <li> * {@link #writeAjaxPageHtmlMainDiv(BufferedWriter, String, String, String)} * <li> {@link #writeAjaxPageHtmlBodyEnd(BufferedWriter)} * </ul> * * @param request * the HTTP request. * @param response * the HTTP response to write to. * @param out * @param unhandledParameters * @param window * @param terminalType * @param theme * @throws IOException * if the writing failed due to input/output error. * @throws MalformedURLException * if the application is denied access the persistent data store * represented by the given URL. */ protected void writeAjaxPage(HttpServletRequest request, HttpServletResponse response, Window window, Application application) throws IOException, MalformedURLException, ServletException { // e.g portlets only want a html fragment boolean fragment = (request.getAttribute(REQUEST_FRAGMENT) != null); if (fragment) { // if this is a fragment request, the actual application is put to // request so ApplicationPortlet can save it for a later use request.setAttribute(Application.class.getName(), application); } final BufferedWriter page = new BufferedWriter(new OutputStreamWriter( response.getOutputStream(), "UTF-8")); String title = ((window.getCaption() == null) ? "Vaadin 6" : window .getCaption()); /* Fetch relative url to application */ // don't use server and port in uri. It may cause problems with some // virtual server configurations which lose the server name String appUrl = getApplicationUrl(request).getPath(); if (appUrl.endsWith("/")) { appUrl = appUrl.substring(0, appUrl.length() - 1); } String themeName = getThemeForWindow(request, window); String themeUri = getThemeUri(themeName, request); if (!fragment) { setAjaxPageHeaders(response); writeAjaxPageHtmlHeadStart(page); writeAjaxPageHtmlHeader(page, title, themeUri); writeAjaxPageHtmlBodyStart(page); } String appId = appUrl; if ("".equals(appUrl)) { appId = "ROOT"; } appId = appId.replaceAll("[^a-zA-Z0-9]", ""); // Add hashCode to the end, so that it is still (sort of) predictable, // but indicates that it should not be used in CSS and such: int hashCode = appId.hashCode(); if (hashCode < 0) { hashCode = -hashCode; } appId = appId + "-" + hashCode; writeAjaxPageHtmlVaadinScripts(window, themeName, application, page, appUrl, themeUri, appId, request); /*- Add classnames; * .v-app * .v-app-loading * .v-app-<simpleName for app class> * .v-theme-<themeName, remove non-alphanum> */ String appClass = "v-app-" + getApplicationCSSClassName(); String themeClass = ""; if (themeName != null) { themeClass = "v-theme-" + themeName.replaceAll("[^a-zA-Z0-9]", ""); } else { themeClass = "v-theme-" + getDefaultTheme().replaceAll("[^a-zA-Z0-9]", ""); } String classNames = "v-app v-app-loading " + themeClass + " " + appClass; String divStyle = null; if (request.getAttribute(REQUEST_APPSTYLE) != null) { divStyle = "style=\"" + request.getAttribute(REQUEST_APPSTYLE) + "\""; } writeAjaxPageHtmlMainDiv(page, appId, classNames, divStyle); if (!fragment) { page.write("</body>\n</html>\n"); } page.close(); } /** * Returns the application class identifier for use in the application CSS * class name in the root DIV. The application CSS class name is of form * "v-app-"+getApplicationCSSClassName(). * * This method should normally not be overridden. * * @return The CSS class name to use in combination with "v-app-". */ protected String getApplicationCSSClassName() { try { return getApplicationClass().getSimpleName(); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "getApplicationCSSClassName failed", e); return "unknown"; } } /** * Get the URI for the application theme. * * A portal-wide default theme is fetched from the portal shared resource * directory (if any), other themes from the portlet. * * @param themeName * @param request * @return */ private String getThemeUri(String themeName, HttpServletRequest request) { final String staticFilePath; if (themeName.equals(request.getAttribute(REQUEST_DEFAULT_THEME))) { // our window theme is the portal wide default theme, make it load // from portals directory is defined staticFilePath = getStaticFilesLocation(request); } else { /* * theme is a custom theme, which is not necessarily located in * portals VAADIN directory. Let the default servlet conf decide * (omitting request parameter) the location. Note that theme can * still be placed to portal directory with servlet parameter. */ staticFilePath = getWebApplicationsStaticFileLocation(request); } return staticFilePath + "/" + THEME_DIRECTORY_PATH + themeName; } /** * Method to write the div element into which that actual Vaadin application * is rendered. * <p> * Override this method if you want to add some custom html around around * the div element into which the actual Vaadin application will be * rendered. * * @param page * @param appId * @param classNames * @param divStyle * @throws IOException */ protected void writeAjaxPageHtmlMainDiv(final BufferedWriter page, String appId, String classNames, String divStyle) throws IOException { page.write("<div id=\"" + appId + "\" class=\"" + classNames + "\" " + (divStyle != null ? divStyle : "") + "></div>\n"); page.write("<noscript>" + getNoScriptMessage() + "</noscript>"); } /** * Method to write the script part of the page which loads needed Vaadin * scripts and themes. * <p> * Override this method if you want to add some custom html around scripts. * * @param window * @param themeName * @param application * @param page * @param appUrl * @param themeUri * @param appId * @param request * @throws ServletException * @throws IOException */ protected void writeAjaxPageHtmlVaadinScripts(Window window, String themeName, Application application, final BufferedWriter page, String appUrl, String themeUri, String appId, HttpServletRequest request) throws ServletException, IOException { // request widgetset takes precedence (e.g portlet include) String requestWidgetset = (String) request .getAttribute(REQUEST_WIDGETSET); String sharedWidgetset = (String) request .getAttribute(REQUEST_SHARED_WIDGETSET); if (requestWidgetset == null && sharedWidgetset == null) { // Use the value from configuration or DEFAULT_WIDGETSET. // If no shared widgetset is specified, the default widgetset is // assumed to be in the servlet/portlet itself. requestWidgetset = getApplicationOrSystemProperty( PARAMETER_WIDGETSET, DEFAULT_WIDGETSET); } String widgetset; String widgetsetBasePath; if (requestWidgetset != null) { widgetset = requestWidgetset; widgetsetBasePath = getWebApplicationsStaticFileLocation(request); } else { widgetset = sharedWidgetset; widgetsetBasePath = getStaticFilesLocation(request); } final String widgetsetFilePath = widgetsetBasePath + "/" + WIDGETSET_DIRECTORY_PATH + widgetset + "/" + widgetset + ".nocache.js?" + new Date().getTime(); // Get system messages Application.SystemMessages systemMessages = null; try { systemMessages = getSystemMessages(); } catch (SystemMessageException e) { // failing to get the system messages is always a problem throw new ServletException("CommunicationError!", e); } page.write("<script type=\"text/javascript\">\n"); page.write("//<![CDATA[\n"); page.write("if(!vaadin || !vaadin.vaadinConfigurations) {\n " + "if(!vaadin) { var vaadin = {}} \n" + "vaadin.vaadinConfigurations = {};\n" + "if (!vaadin.themesLoaded) { vaadin.themesLoaded = {}; }\n"); if (!isProductionMode()) { page.write("vaadin.debug = true;\n"); } page.write("document.write('<iframe tabIndex=\"-1\" id=\"__gwt_historyFrame\" " + "style=\"position:absolute;width:0;height:0;border:0;overflow:" + "hidden;\" src=\"javascript:false\"></iframe>');\n"); page.write("document.write(\"<script language='javascript' src='" + widgetsetFilePath + "'><\\/script>\");\n}\n"); page.write("vaadin.vaadinConfigurations[\"" + appId + "\"] = {"); page.write("appUri:'" + appUrl + "', "); if (window != application.getMainWindow()) { page.write("windowName: '" + window.getName() + "', "); } page.write("themeUri:"); page.write(themeUri != null ? "'" + themeUri + "'" : "null"); page.write(", versionInfo : {vaadinVersion:\""); page.write(VERSION); page.write("\",applicationVersion:\""); page.write(JsonPaintTarget.escapeJSON(application.getVersion())); page.write("\"}"); if (systemMessages != null) { // Write the CommunicationError -message to client String caption = systemMessages.getCommunicationErrorCaption(); if (caption != null) { caption = "\"" + caption + "\""; } String message = systemMessages.getCommunicationErrorMessage(); if (message != null) { message = "\"" + message + "\""; } String url = systemMessages.getCommunicationErrorURL(); if (url != null) { url = "\"" + url + "\""; } page.write(",\"comErrMsg\": {" + "\"caption\":" + caption + "," + "\"message\" : " + message + "," + "\"url\" : " + url + "}"); // Write the AuthenticationError -message to client caption = systemMessages.getAuthenticationErrorCaption(); if (caption != null) { caption = "\"" + caption + "\""; } message = systemMessages.getAuthenticationErrorMessage(); if (message != null) { message = "\"" + message + "\""; } url = systemMessages.getAuthenticationErrorURL(); if (url != null) { url = "\"" + url + "\""; } page.write(",\"authErrMsg\": {" + "\"caption\":" + caption + "," + "\"message\" : " + message + "," + "\"url\" : " + url + "}"); } page.write("};\n//]]>\n</script>\n"); if (themeName != null) { // Custom theme's stylesheet, load only once, in different // script // tag to be dominate styles injected by widget // set page.write("<script type=\"text/javascript\">\n"); page.write("//<![CDATA[\n"); page.write("if(!vaadin.themesLoaded['" + themeName + "']) {\n"); page.write("var stylesheet = document.createElement('link');\n"); page.write("stylesheet.setAttribute('rel', 'stylesheet');\n"); page.write("stylesheet.setAttribute('type', 'text/css');\n"); page.write("stylesheet.setAttribute('href', '" + themeUri + "/styles.css');\n"); page.write("document.getElementsByTagName('head')[0].appendChild(stylesheet);\n"); page.write("vaadin.themesLoaded['" + themeName + "'] = true;\n}\n"); page.write("//]]>\n</script>\n"); } // Warn if the widgetset has not been loaded after 15 seconds on // inactivity page.write("<script type=\"text/javascript\">\n"); page.write("//<![CDATA[\n"); page.write("setTimeout('if (typeof " + widgetset.replace('.', '_') + " == \"undefined\") {alert(\"Failed to load the widgetset: " + widgetsetFilePath + "\")};',15000);\n" + "//]]>\n</script>\n"); } /** * * Method to open the body tag of the html kickstart page. * <p> * This method is responsible for closing the head tag and opening the body * tag. * <p> * Override this method if you want to add some custom html to the page. * * @param page * @throws IOException */ protected void writeAjaxPageHtmlBodyStart(final BufferedWriter page) throws IOException { page.write("\n</head>\n<body scroll=\"auto\" class=\"" + ApplicationConnection.GENERATED_BODY_CLASSNAME + "\">\n"); } /** * Method to write the contents of head element in html kickstart page. * <p> * Override this method if you want to add some custom html to the header of * the page. * * @param page * @param title * @param themeUri * @throws IOException */ protected void writeAjaxPageHtmlHeader(final BufferedWriter page, String title, String themeUri) throws IOException { page.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n"); // Force IE9 into IE8 mode. Remove when IE 9 mode works (#5546), chrome // frame if available #5261 page.write("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=8,chrome=1\"/>\n"); page.write("<style type=\"text/css\">" + "html, body {height:100%;margin:0;}</style>"); // Add favicon links page.write("<link rel=\"shortcut icon\" type=\"image/vnd.microsoft.icon\" href=\"" + themeUri + "/favicon.ico\" />"); page.write("<link rel=\"icon\" type=\"image/vnd.microsoft.icon\" href=\"" + themeUri + "/favicon.ico\" />"); page.write("<title>" + safeEscapeForHtml(title) + "</title>"); } /** * Method to write the beginning of the html page. * <p> * This method is responsible for writing appropriate doc type declarations * and to open html and head tags. * <p> * Override this method if you want to add some custom html to the very * beginning of the page. * * @param page * @throws IOException */ protected void writeAjaxPageHtmlHeadStart(final BufferedWriter page) throws IOException { // write html header page.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Transitional//EN\" " + "\"http://www.w3.org/TR/xhtml1/" + "DTD/xhtml1-transitional.dtd\">\n"); page.write("<html xmlns=\"http://www.w3.org/1999/xhtml\"" + ">\n<head>\n"); } /** * Method to set http request headers for the Vaadin kickstart page. * <p> * Override this method if you need to customize http headers of the page. * * @param response */ protected void setAjaxPageHeaders(HttpServletResponse response) { // Window renders are not cacheable response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("text/html; charset=UTF-8"); } /** * Returns a message printed for browsers without scripting support or if * browsers scripting support is disabled. */ protected String getNoScriptMessage() { return "You have to enable javascript in your browser to use an application built with Vaadin."; } /** * Gets the current application URL from request. * * @param request * the HTTP request. * @throws MalformedURLException * if the application is denied access to the persistent data * store represented by the given URL. */ URL getApplicationUrl(HttpServletRequest request) throws MalformedURLException { final URL reqURL = new URL( (request.isSecure() ? "https://" : "http://") + request.getServerName() + ((request.isSecure() && request.getServerPort() == 443) || (!request.isSecure() && request .getServerPort() == 80) ? "" : ":" + request.getServerPort()) + request.getRequestURI()); String servletPath = ""; if (request.getAttribute("javax.servlet.include.servlet_path") != null) { // this is an include request servletPath = request.getAttribute( "javax.servlet.include.context_path").toString() + request .getAttribute("javax.servlet.include.servlet_path"); } else { servletPath = request.getContextPath() + request.getServletPath(); } if (servletPath.length() == 0 || servletPath.charAt(servletPath.length() - 1) != '/') { servletPath = servletPath + "/"; } URL u = new URL(reqURL, servletPath); return u; } /** * Gets the existing application for given request. Looks for application * instance for given request based on the requested URL. * * @param request * the HTTP request. * @param allowSessionCreation * true if a session should be created if no session exists, * false if no session should be created * @return Application instance, or null if the URL does not map to valid * application. * @throws MalformedURLException * if the application is denied access to the persistent data * store represented by the given URL. * @throws IllegalAccessException * @throws InstantiationException * @throws SessionExpiredException */ protected Application getExistingApplication(HttpServletRequest request, boolean allowSessionCreation) throws MalformedURLException, SessionExpiredException { // Ensures that the session is still valid final HttpSession session = request.getSession(allowSessionCreation); if (session == null) { throw new SessionExpiredException(); } WebApplicationContext context = WebApplicationContext .getApplicationContext(session); // Gets application list for the session. final Collection<Application> applications = context.getApplications(); // Search for the application (using the application URI) from the list for (final Iterator<Application> i = applications.iterator(); i .hasNext();) { final Application sessionApplication = i.next(); final String sessionApplicationPath = sessionApplication.getURL() .getPath(); String requestApplicationPath = getApplicationUrl(request) .getPath(); if (requestApplicationPath.equals(sessionApplicationPath)) { // Found a running application if (sessionApplication.isRunning()) { return sessionApplication; } // Application has stopped, so remove it before creating a new // application WebApplicationContext.getApplicationContext(session) .removeApplication(sessionApplication); break; } } // Existing application not found return null; } /** * Ends the application. * * @param request * the HTTP request. * @param response * the HTTP response to write to. * @param application * the application to end. * @throws IOException * if the writing failed due to input/output error. */ private void endApplication(HttpServletRequest request, HttpServletResponse response, Application application) throws IOException { String logoutUrl = application.getLogoutURL(); if (logoutUrl == null) { logoutUrl = application.getURL().toString(); } final HttpSession session = request.getSession(); if (session != null) { WebApplicationContext.getApplicationContext(session) .removeApplication(application); } response.sendRedirect(response.encodeRedirectURL(logoutUrl)); } /** * Gets the existing application or create a new one. Get a window within an * application based on the requested URI. * * @param request * the HTTP Request. * @param application * the Application to query for window. * @return Window matching the given URI or null if not found. * @throws ServletException * if an exception has occurred that interferes with the * servlet's normal operation. */ private Window getApplicationWindow(HttpServletRequest request, CommunicationManager applicationManager, Application application) throws ServletException { // Finds the window where the request is handled Window assumedWindow = null; String path = getRequestPathInfo(request); // Main window as the URI is empty if (!(path == null || path.length() == 0 || path.equals("/"))) { if (path.startsWith("/APP/")) { // Use main window for application resources return application.getMainWindow(); } String windowName = null; if (path.charAt(0) == '/') { path = path.substring(1); } final int index = path.indexOf('/'); if (index < 0) { windowName = path; path = ""; } else { windowName = path.substring(0, index); } assumedWindow = application.getWindow(windowName); } return applicationManager.getApplicationWindow(request, this, application, assumedWindow); } /** * Returns the path info; note that this _can_ be different than * request.getPathInfo() (e.g application runner). * * @param request * @return */ String getRequestPathInfo(HttpServletRequest request) { return request.getPathInfo(); } /** * Gets relative location of a theme resource. * * @param theme * the Theme name. * @param resource * the Theme resource. * @return External URI specifying the resource */ public String getResourceLocation(String theme, ThemeResource resource) { if (resourcePath == null) { return resource.getResourceId(); } return resourcePath + theme + "/" + resource.getResourceId(); } private boolean isRepaintAll(HttpServletRequest request) { return (request.getParameter(URL_PARAMETER_REPAINT_ALL) != null) && (request.getParameter(URL_PARAMETER_REPAINT_ALL).equals("1")); } private void closeApplication(Application application, HttpSession session) { if (application == null) { return; } application.close(); if (session != null) { WebApplicationContext context = WebApplicationContext .getApplicationContext(session); context.removeApplication(application); } } /** * Implementation of ParameterHandler.ErrorEvent interface. */ public class ParameterHandlerErrorImpl implements ParameterHandler.ErrorEvent, Serializable { private ParameterHandler owner; private Throwable throwable; /** * Gets the contained throwable. * * @see com.vaadin.terminal.Terminal.ErrorEvent#getThrowable() */ public Throwable getThrowable() { return throwable; } /** * Gets the source ParameterHandler. * * @see com.vaadin.terminal.ParameterHandler.ErrorEvent#getParameterHandler() */ public ParameterHandler getParameterHandler() { return owner; } } /** * Implementation of URIHandler.ErrorEvent interface. */ public class URIHandlerErrorImpl implements URIHandler.ErrorEvent, Serializable { private final URIHandler owner; private final Throwable throwable; /** * * @param owner * @param throwable */ private URIHandlerErrorImpl(URIHandler owner, Throwable throwable) { this.owner = owner; this.throwable = throwable; } /** * Gets the contained throwable. * * @see com.vaadin.terminal.Terminal.ErrorEvent#getThrowable() */ public Throwable getThrowable() { return throwable; } /** * Gets the source URIHandler. * * @see com.vaadin.terminal.URIHandler.ErrorEvent#getURIHandler() */ public URIHandler getURIHandler() { return owner; } } public class RequestError implements Terminal.ErrorEvent, Serializable { private final Throwable throwable; public RequestError(Throwable throwable) { this.throwable = throwable; } public Throwable getThrowable() { return throwable; } } /** * Override this method if you need to use a specialized communicaiton * mananger implementation. * * TODO figure out the right place for CM instantiation, must be * overridieable * * @param application * @return */ public CommunicationManager createCommunicationManager( Application application) { return new CommunicationManager(application); } /** * Escapes characters to html entities. An exception is made for some * "safe characters" to keep the text somewhat readable. * * @param unsafe * @return a safe string to be added inside an html tag */ protected static final String safeEscapeForHtml(String unsafe) { StringBuilder safe = new StringBuilder(); char[] charArray = unsafe.toCharArray(); for (int i = 0; i < charArray.length; i++) { char c = charArray[i]; if (isSafe(c)) { safe.append(c); } else { safe.append("&#"); safe.append((int) c); safe.append(";"); } } return safe.toString(); } private static boolean isSafe(char c) { return // c > 47 && c < 58 || // alphanum c > 64 && c < 91 || // A-Z c > 96 && c < 123 // a-z ; } }
true
false
null
null
diff --git a/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLRunner.java b/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLRunner.java index d4c2f66..05cfaec 100644 --- a/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLRunner.java +++ b/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLRunner.java @@ -1,50 +1,49 @@ /* org.manalith.ircbot.plugin.kvl/KVLRunner.java ManalithBot - An open source IRC bot based on the PircBotX Framework. Copyright (C) 2012 Seong-ho, Cho <[email protected]> This program is under the GNU Public License version 3 or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.manalith.ircbot.plugin.kvl; public class KVLRunner { private KVLTable kvlTable; public KVLRunner() { kvlTable = null; } private void initKVLRun() throws Exception { - KVLTableBuilder tBuilder = new KVLTableBuilder( - "http://kernel.org/index.shtml"/* array */); + KVLTableBuilder tBuilder = new KVLTableBuilder("http://www.kernel.org"/* array */); kvlTable = tBuilder.generateKernelVersionTable(); } public String run(String arg) { String result = ""; try { initKVLRun(); } catch (Exception e) { result = e.getMessage(); return result; } if (arg.equals("") || arg.equals("latest")) { result = kvlTable.toString(); } else if (arg.equals("all")) { result = kvlTable.getAllVersionInfo(); } else if (arg.equals("help")) { - result = "!kernel (latest[default]|all|help)"; + result = "!커널 (latest[default]|all|help)"; } else { result = "인식할 수 없는 옵션."; } return result; } } diff --git a/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLTableBuilder.java b/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLTableBuilder.java index 81c8010..c279981 100644 --- a/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLTableBuilder.java +++ b/ManalithBot/src/main/java/org/manalith/ircbot/plugin/kvl/KVLTableBuilder.java @@ -1,68 +1,68 @@ /* org.manalith.ircbot.plugin.kvl/KVLTableBuilder.java ManalithBot - An open source IRC bot based on the PircBot Framework. Copyright (C) 2011, 2012 Seong-ho, Cho <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.manalith.ircbot.plugin.kvl; import java.io.IOException; import java.util.Iterator; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class KVLTableBuilder { private String url; public KVLTableBuilder() { - setURL(""); + this.setURL(""); } public KVLTableBuilder(String newURL) { - setURL(newURL); + this.setURL(newURL); } private void setURL(String url) { this.url = url; } private String getURL() { return url; } public KVLTable generateKernelVersionTable() throws IOException { KVLTable result = new KVLTable(); String newTag = null; String newVerElement = null; Iterator<Element> e = Jsoup.connect(getURL()).get() - .select("table.kver>tbody>tr").iterator(); + .select("table#releases>tbody>tr").iterator(); while (e.hasNext()) { Elements tds = e.next().select("td"); newTag = tds.get(0).text().replaceAll("\\:", ""); newVerElement = tds.get(1).text(); result.addVersionInfo(newTag, newVerElement); } return result; } }
false
false
null
null
diff --git a/src/com/oresomecraft/maps/battles/maps/Equator.java b/src/com/oresomecraft/maps/battles/maps/Equator.java index 97271b2..4b81d41 100644 --- a/src/com/oresomecraft/maps/battles/maps/Equator.java +++ b/src/com/oresomecraft/maps/battles/maps/Equator.java @@ -1,117 +1,110 @@ package com.oresomecraft.maps.battles.maps; import com.oresomecraft.maps.MapConfig; import com.oresomecraft.maps.battles.BattleMap; import com.oresomecraft.maps.battles.IBattleMap; import org.bukkit.*; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.*; import com.oresomecraft.OresomeBattles.api.*; @MapConfig public class Equator extends BattleMap implements IBattleMap, Listener { public Equator() { super.initiate(this, name, fullName, creators, modes); setTDMTime(8); setAllowBuild(false); disableDrops(new Material[]{Material.GLASS, Material.LEATHER_HELMET, Material.STONE_SWORD}); setAutoSpawnProtection(4); } String name = "equator"; String fullName = "Equator"; String creators = "Afridge1O1, SuperDuckFace, Numinex, XUHAVON, beadycottonwood and ViolentShadow"; Gamemode[] modes = {Gamemode.TDM, Gamemode.CTF}; public void readyTDMSpawns() { redSpawns.add(new Location(w, 53, 75, -24)); redSpawns.add(new Location(w, 26, 74, -50)); redSpawns.add(new Location(w, 60, 75, 12)); blueSpawns.add(new Location(w, -53, 75, 24)); blueSpawns.add(new Location(w, -26, 74, 50)); blueSpawns.add(new Location(w, -60, 74, -12)); Location redFlag = new Location(w, 75, 76, -4); Location blueFlag = new Location(w, -75, 76, 4); setCTFFlags(name, redFlag, blueFlag); setKoTHMonument(new Location(w, 0, 69, 0)); } public void readyFFASpawns() { FFASpawns.add(new Location(w, 2, 84, -48)); FFASpawns.add(new Location(w, -3, 84, 58)); } public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); - ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, (short) 11); - ItemStack RED_GLASS = new ItemStack(Material.GLASS, (short) 14); + ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, 1, (short) 11); + ItemStack RED_GLASS = new ItemStack(Material.GLASS, 1, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); ItemStack LEATHER_PANTS = new ItemStack(Material.LEATHER_LEGGINGS, 1); ItemStack LEATHER_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); ItemStack SWORD = new ItemStack(Material.STONE_SWORD, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 5); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack HEALTH = new ItemStack(Material.GOLDEN_APPLE, 3); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack TORCH = new ItemStack(Material.TORCH, 1); - ItemStack OPSWORD = new ItemStack(Material.DIAMOND_SWORD, 1); ItemMeta torch = TORCH.getItemMeta(); torch.setDisplayName(ChatColor.RED + "Blazing Stick"); TORCH.setItemMeta(torch); TORCH.addUnsafeEnchantment(Enchantment.FIRE_ASPECT, 1); - ItemMeta opsword = OPSWORD.getItemMeta(); - opsword.setDisplayName(ChatColor.BLUE + "Soul Destroyer"); - OPSWORD.setItemMeta(opsword); - OPSWORD.setDurability((short) 1561); - OPSWORD.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 10); - InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS}); + InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS, TORCH}); p.getInventory().setBoots(LEATHER_BOOTS); p.getInventory().setLeggings(LEATHER_PANTS); p.getInventory().setChestplate(LEATHER_CHESTPLATE); if(p.getTeam() == Team.TDM_RED); p.getInventory().setHelmet(RED_GLASS); if(p.getTeam() == Team.TDM_BLUE); p.getInventory().setHelmet(BLUE_GLASS); i.setItem(0, SWORD); - i.setItem(1, OPSWORD); - i.setItem(2, BOW); - i.setItem(3, STEAK); - i.setItem(4, HEALTH); - i.setItem(5, EXP); - i.setItem(6, TORCH); + i.setItem(1, BOW); + i.setItem(2, STEAK); + i.setItem(3, HEALTH); + i.setItem(4, EXP); + i.setItem(5, TORCH); i.setItem(10, ARROWS); } // Region. (Top corner block and bottom corner block. // Top left corner. public int x1 = 103; public int y1 = 115; public int z1 = 103; //Bottom right corner. public int x2 = -103; public int y2 = 0; public int z2 = -103; }
false
true
public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, (short) 11); ItemStack RED_GLASS = new ItemStack(Material.GLASS, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); ItemStack LEATHER_PANTS = new ItemStack(Material.LEATHER_LEGGINGS, 1); ItemStack LEATHER_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); ItemStack SWORD = new ItemStack(Material.STONE_SWORD, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 5); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack HEALTH = new ItemStack(Material.GOLDEN_APPLE, 3); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack TORCH = new ItemStack(Material.TORCH, 1); ItemStack OPSWORD = new ItemStack(Material.DIAMOND_SWORD, 1); ItemMeta torch = TORCH.getItemMeta(); torch.setDisplayName(ChatColor.RED + "Blazing Stick"); TORCH.setItemMeta(torch); TORCH.addUnsafeEnchantment(Enchantment.FIRE_ASPECT, 1); ItemMeta opsword = OPSWORD.getItemMeta(); opsword.setDisplayName(ChatColor.BLUE + "Soul Destroyer"); OPSWORD.setItemMeta(opsword); OPSWORD.setDurability((short) 1561); OPSWORD.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 10); InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS}); p.getInventory().setBoots(LEATHER_BOOTS); p.getInventory().setLeggings(LEATHER_PANTS); p.getInventory().setChestplate(LEATHER_CHESTPLATE); if(p.getTeam() == Team.TDM_RED); p.getInventory().setHelmet(RED_GLASS); if(p.getTeam() == Team.TDM_BLUE); p.getInventory().setHelmet(BLUE_GLASS); i.setItem(0, SWORD); i.setItem(1, OPSWORD); i.setItem(2, BOW); i.setItem(3, STEAK); i.setItem(4, HEALTH); i.setItem(5, EXP); i.setItem(6, TORCH); i.setItem(10, ARROWS); }
public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, 1, (short) 11); ItemStack RED_GLASS = new ItemStack(Material.GLASS, 1, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); ItemStack LEATHER_PANTS = new ItemStack(Material.LEATHER_LEGGINGS, 1); ItemStack LEATHER_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); ItemStack SWORD = new ItemStack(Material.STONE_SWORD, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 5); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack HEALTH = new ItemStack(Material.GOLDEN_APPLE, 3); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack TORCH = new ItemStack(Material.TORCH, 1); ItemMeta torch = TORCH.getItemMeta(); torch.setDisplayName(ChatColor.RED + "Blazing Stick"); TORCH.setItemMeta(torch); TORCH.addUnsafeEnchantment(Enchantment.FIRE_ASPECT, 1); InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS, TORCH}); p.getInventory().setBoots(LEATHER_BOOTS); p.getInventory().setLeggings(LEATHER_PANTS); p.getInventory().setChestplate(LEATHER_CHESTPLATE); if(p.getTeam() == Team.TDM_RED); p.getInventory().setHelmet(RED_GLASS); if(p.getTeam() == Team.TDM_BLUE); p.getInventory().setHelmet(BLUE_GLASS); i.setItem(0, SWORD); i.setItem(1, BOW); i.setItem(2, STEAK); i.setItem(3, HEALTH); i.setItem(4, EXP); i.setItem(5, TORCH); i.setItem(10, ARROWS); }
diff --git a/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/monitor/internal/list/ListAlarmMonitor.java b/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/monitor/internal/list/ListAlarmMonitor.java index 864d8f9ab..722162c2d 100644 --- a/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/monitor/internal/list/ListAlarmMonitor.java +++ b/org.openscada.ae.monitor.dataitem/src/org/openscada/ae/monitor/dataitem/monitor/internal/list/ListAlarmMonitor.java @@ -1,204 +1,204 @@ /* * This file is part of the OpenSCADA project * Copyright (C) 2006-2011 TH4 SYSTEMS GmbH (http://th4-systems.com) * * OpenSCADA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenSCADA 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenSCADA. If not, see * <http://opensource.org/licenses/lgpl-3.0.html> for a copy of the LGPLv3 License. */ package org.openscada.ae.monitor.dataitem.monitor.internal.list; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.Executor; import java.util.regex.Pattern; import org.openscada.ae.Event.EventBuilder; import org.openscada.ae.event.EventProcessor; import org.openscada.ae.monitor.common.EventHelper; import org.openscada.ae.monitor.dataitem.AbstractVariantMonitor; import org.openscada.ae.monitor.dataitem.DataItemMonitor; import org.openscada.ca.ConfigurationDataHelper; import org.openscada.core.Variant; import org.openscada.core.VariantEditor; import org.openscada.da.client.DataItemValue.Builder; import org.openscada.da.core.WriteAttributeResult; import org.openscada.da.core.WriteAttributeResults; import org.openscada.utils.osgi.pool.ObjectPoolTracker; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ListAlarmMonitor extends AbstractVariantMonitor implements DataItemMonitor { private final static Logger logger = LoggerFactory.getLogger ( ListAlarmMonitor.class ); public static final String FACTORY_ID = "ae.monitor.da.listAlarm"; - private final static Pattern splitPattern = Pattern.compile ( "[, \t\n\r]+" ); - private Collection<Variant> referenceList; private boolean listIsAlarm; private final int defaultPriority; public ListAlarmMonitor ( final BundleContext context, final Executor executor, final ObjectPoolTracker poolTracker, final EventProcessor eventProcessor, final String id, final int defaultPriority ) { super ( context, executor, poolTracker, eventProcessor, id, id, "VALUE" ); this.defaultPriority = defaultPriority; } @Override protected String getFactoryId () { return FACTORY_ID; } @Override protected String getConfigurationId () { return getId (); } @Override protected int getDefaultPriority () { return this.defaultPriority; } @Override public void update ( final Map<String, String> properties ) throws Exception { super.update ( properties ); final ConfigurationDataHelper cfg = new ConfigurationDataHelper ( properties ); // parameter - "referenceList" - final Collection<Variant> newReferenceList = parseValues ( cfg.getString ( "referenceList", "" ) ); + final Collection<Variant> newReferenceList = parseValues ( cfg.getString ( "referenceList", "" ), cfg.getString ( "splitPattern", "[, \t\n\r]+" ) ); if ( isDifferent ( this.referenceList, newReferenceList ) ) { final EventBuilder builder = EventHelper.newConfigurationEvent ( getId (), "Change reference value list", Variant.valueOf ( newReferenceList ), new Date () ); injectEventAttributes ( builder ); publishEvent ( builder ); this.referenceList = newReferenceList; } // parameter - "listIsAlarm" final boolean listIsAlarm = cfg.getBoolean ( "listIsAlarm", true ); if ( isDifferent ( this.listIsAlarm, listIsAlarm ) ) { final EventBuilder builder = EventHelper.newConfigurationEvent ( getId (), "Items in reference list are alarm", Variant.valueOf ( listIsAlarm ), new Date () ); injectEventAttributes ( builder ); publishEvent ( builder ); this.listIsAlarm = listIsAlarm; } reprocess (); } - protected Collection<Variant> parseValues ( final String data ) + protected Collection<Variant> parseValues ( final String data, final String splitPatternString ) { if ( data == null ) { return Collections.emptyList (); } + final Pattern splitPattern = Pattern.compile ( splitPatternString ); + final Collection<Variant> result = new LinkedList<Variant> (); final String toks[] = splitPattern.split ( data ); for ( final String item : toks ) { final VariantEditor ve = new VariantEditor (); ve.setAsText ( item ); final Variant value = (Variant)ve.getValue (); if ( value != null ) { result.add ( value ); } } return result; } @Override protected void injectAttributes ( final Builder builder ) { super.injectAttributes ( builder ); builder.setAttribute ( this.prefix + ".referenceList", Variant.valueOf ( this.referenceList ) ); builder.setAttribute ( this.prefix + ".listIsAlarm", Variant.valueOf ( this.listIsAlarm ) ); } @Override protected void handleConfigUpdate ( final Map<String, String> configUpdate, final Map<String, Variant> attributes, final WriteAttributeResults result ) { super.handleConfigUpdate ( configUpdate, attributes, result ); final Variant reference = attributes.get ( this.prefix + ".referenceList" ); if ( reference != null ) { configUpdate.put ( "referenceList", reference.asString ( "" ) ); result.put ( this.prefix + ".referenceList", WriteAttributeResult.OK ); } final Variant listIsAlarm = attributes.get ( this.prefix + ".listIsAlarm" ); if ( listIsAlarm != null ) { final Boolean value = listIsAlarm.asBoolean ( null ); if ( value != null ) { configUpdate.put ( "listIsAlarm", value ? "true" : "false" ); result.put ( this.prefix + ".listIsAlarm", WriteAttributeResult.OK ); } } } @Override protected void update ( final Builder builder ) { logger.debug ( "Handle data update: {}", builder ); if ( this.value == null || this.value.isNull () || this.timestamp == null || this.referenceList == null ) { setUnsafe (); } else if ( isOk ( this.value ) ) { setOk ( Variant.valueOf ( this.value ), this.timestamp ); } else { setFailure ( Variant.valueOf ( this.value ), this.timestamp ); } } protected boolean isOk ( final Variant value ) { if ( this.referenceList.contains ( value ) ) { return !this.listIsAlarm; } else { return this.listIsAlarm; } } }
false
false
null
null
diff --git a/src/main/java/net/greghaines/jesque/worker/WorkerPool.java b/src/main/java/net/greghaines/jesque/worker/WorkerPool.java index eb403d2..675f698 100644 --- a/src/main/java/net/greghaines/jesque/worker/WorkerPool.java +++ b/src/main/java/net/greghaines/jesque/worker/WorkerPool.java @@ -1,239 +1,256 @@ /* * Copyright 2011 Greg Haines * * 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 net.greghaines.jesque.worker; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import net.greghaines.jesque.Config; /** * Creates a fixed number of identical <code>Workers</code>, each on a * separate <code>Thread</code>. * * @author Greg Haines */ public class WorkerPool implements Worker { private final List<Worker> workers; private final List<Thread> threads; /** * Create a WorkerPool with the given number of Workers and the * default <code>ThreadFactory</code>. * * @param config used to create a connection to Redis and the package * prefix for incoming jobs * @param queues the list of queues to poll * @param jobTypes the list of job types to execute * @param numWorkers the number of Workers to create */ public WorkerPool(final Config config, final Collection<String> queues, final Collection<? extends Class<?>> jobTypes, final int numWorkers) { this(config, queues, jobTypes, numWorkers, Executors.defaultThreadFactory()); } /** * Create a WorkerPool with the given number of Workers and the * given <code>ThreadFactory</code>. * * @param config used to create a connection to Redis and the package * prefix for incoming jobs * @param queues the list of queues to poll * @param jobTypes the list of job types to execute * @param numWorkers the number of Workers to create * @param threadFactory the factory to create pre-configured Threads */ public WorkerPool(final Config config, final Collection<String> queues, final Collection<? extends Class<?>> jobTypes, final int numWorkers, final ThreadFactory threadFactory) { this.workers = new ArrayList<Worker>(numWorkers); this.threads = new ArrayList<Thread>(numWorkers); for (int i = 0; i < numWorkers; i++) { final Worker worker = new WorkerImpl(config, queues, jobTypes); this.workers.add(worker); this.threads.add(threadFactory.newThread(worker)); } } /** * Shutdown this pool and wait untill all threads are finished. * * @param now if true, an effort will be made to stop any jobs in progress * @throws InterruptedException */ public void endAndJoin(final boolean now) throws InterruptedException { end(now); for (final Thread thread : this.threads) { while (thread.isAlive()) { thread.join(); } } } - + + /** + * Wait untill all threads are finished. + * + * @throws InterruptedException + */ + public void join() + throws InterruptedException + { + for (final Thread thread : this.threads) + { + while (thread.isAlive()) + { + thread.join(); + } + } + } + public String getName() { final StringBuilder sb = new StringBuilder(128 * this.threads.size()); String prefix = ""; for (final Worker worker : this.workers) { sb.append(prefix).append(worker.getName()); prefix = " | "; } return sb.toString(); } public void run() { for (final Thread thread : this.threads) { thread.start(); } Thread.yield(); } public void addListener(final WorkerListener listener) { for (final Worker worker : this.workers) { worker.addListener(listener); } } public void addListener(final WorkerListener listener, final WorkerEvent... events) { for (final Worker worker : this.workers) { worker.addListener(listener, events); } } public void removeListener(final WorkerListener listener) { for (final Worker worker : this.workers) { worker.removeListener(listener); } } public void removeListener(final WorkerListener listener, final WorkerEvent... events) { for (final Worker worker : this.workers) { worker.removeListener(listener, events); } } public void removeAllListeners() { for (final Worker worker : this.workers) { worker.removeAllListeners(); } } public void removeAllListeners(final WorkerEvent... events) { for (final Worker worker : this.workers) { worker.removeAllListeners(events); } } public void end(final boolean now) { for (final Worker worker : this.workers) { worker.end(now); } } public void togglePause(final boolean paused) { for (final Worker worker : this.workers) { worker.togglePause(paused); } } public void addQueue(final String queueName) { for (final Worker worker : this.workers) { worker.addQueue(queueName); } } public void removeQueue(final String queueName, final boolean all) { for (final Worker worker : this.workers) { worker.removeQueue(queueName, all); } } public void removeAllQueues() { for (final Worker worker : this.workers) { worker.removeAllQueues(); } } public void setQueues(final Collection<String> queues) { for (final Worker worker : this.workers) { worker.setQueues(queues); } } public void addJobType(final Class<?> jobType) { for (final Worker worker : this.workers) { worker.addJobType(jobType); } } public void removeJobType(final Class<?> jobType) { for (final Worker worker : this.workers) { worker.removeJobType(jobType); } } public void setJobTypes(final Collection<? extends Class<?>> jobTypes) { for (final Worker worker : this.workers) { worker.setJobTypes(jobTypes); } } }
true
false
null
null
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java index a523552ba..b86ec854d 100644 --- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java +++ b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java @@ -1,161 +1,161 @@ package brooklyn.entity.brooklynnode; import java.net.URI; import java.util.List; import java.util.Map; import brooklyn.config.ConfigKey; import brooklyn.entity.basic.ConfigKeys; import brooklyn.entity.basic.SoftwareProcess; import brooklyn.entity.java.UsesJava; import brooklyn.entity.proxying.ImplementedBy; import brooklyn.event.AttributeSensor; import brooklyn.event.basic.BasicAttributeSensor; import brooklyn.event.basic.BasicAttributeSensorAndConfigKey; import brooklyn.event.basic.BasicAttributeSensorAndConfigKey.StringAttributeSensorAndConfigKey; import brooklyn.event.basic.PortAttributeSensorAndConfigKey; import brooklyn.util.collections.MutableMap; import brooklyn.util.flags.SetFromFlag; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @ImplementedBy(BrooklynNodeImpl.class) public interface BrooklynNode extends SoftwareProcess, UsesJava { @SetFromFlag("copyToRundir") public static final BasicAttributeSensorAndConfigKey<Map<String,String>> COPY_TO_RUNDIR = new BasicAttributeSensorAndConfigKey( Map.class, "brooklynnode.copytorundir", "URLs of resources to be copied across to the server, giving the path they are to be copied to", MutableMap.of()); @SetFromFlag("version") public static final ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(ConfigKeys.SUGGESTED_VERSION, "0.6.0-SNAPSHOT"); // BROOKLYN_VERSION // Takes presidence over downloadUrl, if non-null @SetFromFlag("distroUploadUrl") public static final ConfigKey<String> DISTRO_UPLOAD_URL = ConfigKeys.newStringConfigKey( "brooklynnode.distro.uploadurl", "URL for uploading the brooklyn distro (retrieved locally and pushed to remote install location)", null); @SetFromFlag("downloadUrl") BasicAttributeSensorAndConfigKey<String> DOWNLOAD_URL = new StringAttributeSensorAndConfigKey( SoftwareProcess.DOWNLOAD_URL, "<#if version?contains(\"SNAPSHOT\")>"+ "https://oss.sonatype.org/service/local/artifact/maven/redirect?r=snapshots&g=io.brooklyn&v=${version}&a=brooklyn-dist&c=dist&e=tar.gz" + "<#else>"+ "http://search.maven.org/remotecontent?filepath=io/brooklyn/brooklyn-dist/${version}/brooklyn-dist-${version}-dist.tar.gz"+ "</#if>"); @SetFromFlag("managementUser") ConfigKey<String> MANAGEMENT_USER = ConfigKeys.newConfigKey("brooklynnode.managementUser", "The user for logging into the brooklyn web-console (also used for health-checks)", "admin"); @SetFromFlag("managementPassword") ConfigKey<String> MANAGEMENT_PASSWORD = ConfigKeys.newStringConfigKey("brooklynnode.managementPassword", "Password for MANAGEMENT_USER.", "password"); @SetFromFlag("app") public static final BasicAttributeSensorAndConfigKey<String> APP = new BasicAttributeSensorAndConfigKey<String>( String.class, "brooklynnode.app", "Application (fully qualified class name) to launch using the brooklyn CLI", null); @SetFromFlag("locations") public static final BasicAttributeSensorAndConfigKey<String> LOCATIONS = new BasicAttributeSensorAndConfigKey<String>( String.class, "brooklynnode.locations", "Locations to use when launching the app", null); /** * Exposed just for testing; remote path is not passed into the launched brooklyn so this won't be used! * This will likely change in a future version. */ @VisibleForTesting @SetFromFlag("brooklynGlobalPropertiesRemotePath") public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH = ConfigKeys.newStringConfigKey( "brooklynnode.brooklynproperties.global.remotepath", "Remote path for the global brooklyn.properties file to be uploaded", "${HOME}/.brooklyn/brooklyn.properties"); @SetFromFlag("brooklynGlobalPropertiesUri") public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_URI = ConfigKeys.newStringConfigKey( "brooklynnode.brooklynproperties.global.uri", "URI for the global brooklyn properties file (to upload to ~/.brooklyn/brooklyn.properties", null); @SetFromFlag("brooklynGlobalPropertiesContents") public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_CONTENTS = ConfigKeys.newStringConfigKey( "brooklynnode.brooklynproperties.global.contents", "Contents for the global brooklyn properties file (to upload to ~/.brooklyn/brooklyn.properties", null); /** * @deprecated since 0.6.0; use BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH */ @SetFromFlag("brooklynPropertiesRemotePath") public static final ConfigKey<String> BROOKLYN_PROPERTIES_REMOTE_PATH = BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH; /** * @deprecated since 0.6.0; use BROOKLYN_GLOBAL_PROPERTIES_URI */ @SetFromFlag("brooklynPropertiesUri") public static final ConfigKey<String> BROOKLYN_PROPERTIES_URI = BROOKLYN_GLOBAL_PROPERTIES_URI; /** * @deprecated since 0.6.0; use BROOKLYN_GLOBAL_PROPERTIES_CONTENTS */ @SetFromFlag("brooklynPropertiesContents") public static final ConfigKey<String> BROOKLYN_PROPERTIES_CONTENTS = BROOKLYN_GLOBAL_PROPERTIES_CONTENTS; @SetFromFlag("brooklynLocalPropertiesRemotePath") public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH = ConfigKeys.newStringConfigKey( "brooklynnode.brooklynproperties.local.remotepath", "Remote path for the launch-specific brooklyn.properties file to be uploaded", "${driver.runDir}/brooklyn-local.properties"); @SetFromFlag("brooklynLocalPropertiesUri") public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_URI = ConfigKeys.newStringConfigKey( "brooklynnode.brooklynproperties.local.uri", "URI for the launch-specific brooklyn properties file (to upload to ~/.brooklyn/brooklyn.properties", null); @SetFromFlag("brooklynLocalPropertiesContents") public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_CONTENTS = ConfigKeys.newStringConfigKey( "brooklynnode.brooklynproperties.local.contents", "Contents for the launch-specific brooklyn properties file (to upload to ~/.brooklyn/brooklyn.properties", null); // For use in testing primarily @SetFromFlag("brooklynCatalogRemotePath") public static final ConfigKey<String> BROOKLYN_CATALOG_REMOTE_PATH = ConfigKeys.newStringConfigKey( "brooklynnode.brooklyncatalog.remotepath", "Remote path for the brooklyn catalog.xml file to be uploaded", "${HOME}/.brooklyn/catalog.xml"); @SetFromFlag("brooklynCatalogUri") public static final ConfigKey<String> BROOKLYN_CATALOG_URI = ConfigKeys.newStringConfigKey( "brooklynnode.brooklyncatalog.uri", "URI for the brooklyn catalog.xml file (to upload to ~/.brooklyn/catalog.xml", null); @SetFromFlag("brooklynCatalogContents") public static final ConfigKey<String> BROOKLYN_CATALOG_CONTENTS = ConfigKeys.newStringConfigKey( "brooklynnode.brooklyncatalog.contents", "Contents for the brooklyn catalog.xml file (to upload to ~/.brooklyn/catalog.xml", null); @SetFromFlag("enabledHttpProtocols") public static final BasicAttributeSensorAndConfigKey<List<String>> ENABLED_HTTP_PROTOCOLS = new BasicAttributeSensorAndConfigKey( List.class, "brooklynnode.webconsole.enabledHttpProtocols", "List of enabled protocols (e.g. http, https)", ImmutableList.of("http")); @SetFromFlag("httpPort") public static final PortAttributeSensorAndConfigKey HTTP_PORT = new PortAttributeSensorAndConfigKey( "brooklynnode.webconsole.httpPort", "HTTP Port for the brooklyn web-console", "8081+"); @SetFromFlag("httpsPort") public static final PortAttributeSensorAndConfigKey HTTPS_PORT = new PortAttributeSensorAndConfigKey( - "brooklynnode.webconsole.httpPort", "HTTP Port for the brooklyn web-console", "8081+"); + "brooklynnode.webconsole.httpsPort", "HTTPS Port for the brooklyn web-console", "8443+"); @SetFromFlag("noWebConsoleSecurity") public static final BasicAttributeSensorAndConfigKey<Boolean> NO_WEB_CONSOLE_AUTHENTICATION = new BasicAttributeSensorAndConfigKey<Boolean>( Boolean.class, "brooklynnode.webconsole.nosecurity", "Whether to start the web console with no security", false); @SetFromFlag("bindAddress") public static final BasicAttributeSensorAndConfigKey<String> WEB_CONSOLE_BIND_ADDRESS = new BasicAttributeSensorAndConfigKey<String>( String.class, "brooklynnode.webconsole.bindAddress", "Specifies the IP address of the NIC to bind the Brooklyn Management Console to", null); @SetFromFlag("classpath") public static final BasicAttributeSensorAndConfigKey<List<String>> CLASSPATH = new BasicAttributeSensorAndConfigKey( List.class, "brooklynnode.classpath", "classpath to use, as list of URL entries", Lists.newArrayList()); @SetFromFlag("portMapper") public static final ConfigKey<Function<? super Integer, ? extends Integer>> PORT_MAPPER = (ConfigKey) ConfigKeys.newConfigKey(Function.class, "brooklynnode.webconsole.portMapper", "Function for mapping private to public ports, for use in inferring the brooklyn URI", Functions.<Integer>identity()); public static final AttributeSensor<URI> WEB_CONSOLE_URI = new BasicAttributeSensor<URI>( URI.class, "brooklynnode.webconsole.url", "URL of the brooklyn web-console"); @SetFromFlag("noShutdownOnExit") public static final ConfigKey<Boolean> NO_SHUTDOWN_ON_EXIT = ConfigKeys.newBooleanConfigKey("brooklynnode.noshutdownonexit", "Whether to shutdown entities on exit", false); } diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java index 569d49d20..d2ac86b88 100644 --- a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java +++ b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java @@ -1,255 +1,255 @@ package brooklyn.entity.brooklynnode; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.io.File; import java.net.URI; import java.util.List; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import brooklyn.entity.basic.ApplicationBuilder; import brooklyn.entity.basic.BasicApplication; import brooklyn.entity.basic.BasicApplicationImpl; import brooklyn.entity.basic.Entities; import brooklyn.entity.proxying.EntitySpec; import brooklyn.event.feed.http.HttpValueFunctions; import brooklyn.event.feed.http.JsonFunctions; import brooklyn.location.Location; import brooklyn.location.LocationSpec; import brooklyn.location.basic.LocalhostMachineProvisioningLocation; import brooklyn.location.basic.PortRanges; import brooklyn.test.EntityTestUtils; import brooklyn.test.HttpTestUtils; import brooklyn.test.entity.TestApplication; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.io.Files; public class BrooklynNodeIntegrationTest { // TODO Need test for copying/setting classpath private static final File BROOKLYN_PROPERTIES_PATH = new File(System.getProperty("user.home")+"/.brooklyn/brooklyn.properties"); private static final File BROOKLYN_PROPERTIES_BAK_PATH = new File(BROOKLYN_PROPERTIES_PATH+".test.bak"); private File pseudoBrooklynPropertiesFile; private File pseudoBrooklynCatalogFile; private List<? extends Location> locs; private TestApplication app; @BeforeMethod(alwaysRun=true) public void setUp() throws Exception { pseudoBrooklynPropertiesFile = File.createTempFile("brooklynnode-test", ".properties"); pseudoBrooklynPropertiesFile.delete(); pseudoBrooklynCatalogFile = File.createTempFile("brooklynnode-test", ".catalog"); pseudoBrooklynCatalogFile.delete(); app = ApplicationBuilder.newManagedApp(TestApplication.class); Location localhost = app.getManagementSupport().getManagementContext().getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)); locs = ImmutableList.of(localhost); } @AfterMethod(alwaysRun=true) public void tearDown() throws Exception { if (app != null) Entities.destroyAll(app.getManagementSupport().getManagementContext()); if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete(); if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete(); } @Test(groups="Integration") public void testCanStartAndStop() throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1")); app.start(locs); EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true); brooklynNode.stop(); EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false); } @Test(groups="Integration") public void testCanStartAndStopWithoutAuthentication() throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION, true) .configure(BrooklynNode.MANAGEMENT_USER, null)); app.start(locs); EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true); brooklynNode.stop(); EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false); } @Test(groups="Integration") public void testSetsGlobalBrooklynPropertiesFromContents() throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1") .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath()) .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_CONTENTS, "abc=def")); app.start(locs); assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def")); } @Test(groups="Integration") public void testSetsLocalBrooklynPropertiesFromContents() throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1") .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath()) .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, "abc=def")); app.start(locs); assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def")); } @Test(groups="Integration") public void testSetsBrooklynPropertiesFromUri() throws Exception { File brooklynPropertiesSourceFile = File.createTempFile("brooklynnode-test", ".properties"); Files.write("abc=def", brooklynPropertiesSourceFile, Charsets.UTF_8); BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1") .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath()) .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_URI, brooklynPropertiesSourceFile.toURI().toString())); app.start(locs); assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def")); } @Test(groups="Integration") public void testSetsBrooklynCatalogFromContents() throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1") .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath()) .configure(BrooklynNode.BROOKLYN_CATALOG_CONTENTS, "<catalog/>")); app.start(locs); assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("<catalog/>")); } @Test(groups="Integration") public void testSetsBrooklynCatalogFromUri() throws Exception { File brooklynCatalogSourceFile = File.createTempFile("brooklynnode-test", ".catalog"); Files.write("abc=def", brooklynCatalogSourceFile, Charsets.UTF_8); BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1") .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath()) .configure(BrooklynNode.BROOKLYN_CATALOG_URI, brooklynCatalogSourceFile.toURI().toString())); app.start(locs); assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("abc=def")); } @Test(groups="Integration") public void testCopiesResources() throws Exception { File sourceFile = File.createTempFile("brooklynnode-test", ".properties"); Files.write("abc=def", sourceFile, Charsets.UTF_8); File tempDir = Files.createTempDir(); File expectedFile = new File(tempDir, "myfile.txt"); try { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1") .configure(BrooklynNode.SUGGESTED_RUN_DIR, tempDir.getAbsolutePath()) .configure(BrooklynNode.COPY_TO_RUNDIR, ImmutableMap.of(sourceFile.getAbsolutePath(), "${RUN}/myfile.txt"))); app.start(locs); assertEquals(Files.readLines(expectedFile, Charsets.UTF_8), ImmutableList.of("abc=def")); } finally { expectedFile.delete(); tempDir.delete(); sourceFile.delete(); } } @Test(groups="Integration") public void testSetsBrooklynWebConsolePort() throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, "127.0.0.1") .configure(BrooklynNode.HTTP_PORT, PortRanges.fromString("45000+"))); app.start(locs); Integer httpPort = brooklynNode.getAttribute(BrooklynNode.HTTP_PORT); URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); assertTrue(httpPort >= 45000 && httpPort < 54100, "httpPort="+httpPort); assertEquals((Integer)webConsoleUri.getPort(), httpPort); HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri.toString(), 200, 401); } @Test(groups="Integration") public void testStartsApp() throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION, true) .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName())); app.start(locs); URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications"); List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class); assertEquals(appType, ImmutableList.of(BasicApplication.class.getName())); } @Test(groups="Integration") public void testUsesLocation() throws Exception { - String brooklynPropertiesContents = "brooklyn.location.named.mynamedloc=localhost"; + String brooklynPropertiesContents = "brooklyn.location.named.mynamedloc=localhost:(name=myname)"; Files.copy(BROOKLYN_PROPERTIES_PATH, BROOKLYN_PROPERTIES_BAK_PATH); try { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION, true) .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_CONTENTS, brooklynPropertiesContents) .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName()) .configure(BrooklynNode.LOCATIONS, "named:mynamedloc")); app.start(locs); URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); // Check that "mynamedloc" has been picked up from the brooklyn.properties String locsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations"); List<String> locNames = parseJsonList(locsContent, ImmutableList.of("name"), String.class); assertTrue(locNames.contains("mynamedloc"), "locNames="+locNames); // Find the id of the concrete location instance of the app String appsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications"); List<String[]> appLocationIds = parseJsonList(appsContent, ImmutableList.of("spec", "locations"), String[].class); String appLocationId = Iterables.getOnlyElement(appLocationIds)[0]; // Check that the concrete location is of the required type String locatedLocationsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations/usage/LocatedLocations"); String appLocationName = parseJson(locatedLocationsContent, ImmutableList.of(appLocationId, "name"), String.class); - assertEquals(appLocationName, "mynamedloc"); + assertEquals(appLocationName, "myname"); } finally { Files.copy(BROOKLYN_PROPERTIES_BAK_PATH, BROOKLYN_PROPERTIES_PATH); } } private <T> T parseJson(String json, List<String> elements, Class<T> clazz) { Function<String, T> func = HttpValueFunctions.chain( JsonFunctions.asJson(), JsonFunctions.walk(elements), JsonFunctions.cast(clazz)); return func.apply(json); } private <T> List<T> parseJsonList(String json, List<String> elements, Class<T> clazz) { Function<String, List<T>> func = HttpValueFunctions.chain( JsonFunctions.asJson(), JsonFunctions.forEach(HttpValueFunctions.chain( JsonFunctions.walk(elements), JsonFunctions.cast(clazz)))); return func.apply(json); } }
false
false
null
null
diff --git a/src/mel/fencing/server/Game.java b/src/mel/fencing/server/Game.java index 7ce4592..3f643f9 100644 --- a/src/mel/fencing/server/Game.java +++ b/src/mel/fencing/server/Game.java @@ -1,374 +1,374 @@ package mel.fencing.server; public class Game { //TODO RFI consider using powers of two so one bit each for color, canAdvance/Attack, canRetreat, and canParry public static final int COLOR_NONE = -10; public static final int COLOR_WHITE = 0; public static final int COLOR_BLACK = 10; public static final int TURN_MOVE = 0; public static final int TURN_PARRY = 1; public static final int TURN_PARRY_OR_RETREAT = 2; public static final int TURN_BLACK_MOVE = COLOR_BLACK+TURN_MOVE; public static final int TURN_BLACK_PARRY = COLOR_BLACK+TURN_PARRY; public static final int TURN_BLACK_PARRY_OR_RETREAT = COLOR_BLACK+TURN_PARRY_OR_RETREAT; public static final int TURN_WHITE_MOVE = COLOR_WHITE+TURN_MOVE; public static final int TURN_WHITE_PARRY = COLOR_WHITE+TURN_PARRY; public static final int TURN_WHITE_PARRY_OR_RETREAT = COLOR_WHITE+TURN_PARRY_OR_RETREAT; public static final int TURN_GAME_OVER = -1; UserSession black; UserSession white; Deck deck; Hand whiteHand = new Hand(); Hand blackHand = new Hand(); int blackHP = 5; int whiteHP = 5; int blackpos = 23; int whitepos = 1; int turn = TURN_WHITE_MOVE; int parryVal = -1; int parryCount = -1; boolean finalParry = false; private Game(UserSession challenger, UserSession target) { black = challenger; white = target; deck = new Deck(); deck.shuffle(); black.setGame(this); black.setColor(COLOR_BLACK); white.setGame(this); white.setColor(COLOR_WHITE); sendNames(); blackHand.fill(deck); sendBlackHand(); whiteHand.fill(deck); sendWhiteHand(); } public static Game newGame(UserSession challenger, UserSession target) { return new Game(challenger, target); } private void sendWhiteHand() { white.send(whiteHand.toString()); } private void sendBlackHand() { black.send(blackHand.toString()); } private void sendNames() { white.send("w"+black.getUsername()); black.send("b"+white.getUsername()); } private final int playerColor(UserSession player) { if(player == white) return COLOR_WHITE; if(player == black) return COLOR_BLACK; return COLOR_NONE; } synchronized void jumpAttack(UserSession player, String values) { if(values.length() != 3) send(player, "ESyntax error in attack:"+values); int distance = parseDigit(values.charAt(0)); int value = parseDigit(values.charAt(1)); int count = parseDigit(values.charAt(2)); if(value<0 || count<1) send(player, "ESyntax error in attack:"+values); int color = playerColor(player); if(color == COLOR_NONE) send(player, "EYou are not a player in this game"); if(turn != color+TURN_MOVE) { if(turn == color+TURN_PARRY || turn == color+TURN_PARRY_OR_RETREAT) send(player, "EDefend before attacking"); else send(player, "ENot your turn to attack"); return; } Hand hand = handOf(color); if(!hand.hasCardWithCards(distance, value, count)) { send(player, "EYou don't have the cards to jump-attack ("+distance+":"+value+","+count+")"); return; } if(blackpos - whitepos != (distance+value)) { send(player, "EYou are the wrong distance to jump-attack with a "+distance+" and "+value); return; } parryVal = value; parryCount = count; movePosOf(color, distance); hand.removeByValue(distance); hand.removeByValue(value, count); hand.fill(deck); if(deck.isEmpty()) { finalParry = true; notifyFinalParry(); } turn = otherColor(color)+TURN_PARRY_OR_RETREAT; notifyPositions(); notifyHand(player, hand); notifyAttack(value, count, distance); notifyTurn(); } private void notifyAttack(int value, int count, int distance) { sendAll("a"+value+""+count+""+distance); } private void notifyFinalParry() { sendAll("f"); } synchronized void standingAttack(UserSession player, String values) { if(values.length() != 2) send(player, "ESyntax error in attack:"+values); int value = parseDigit(values.charAt(0)); int count = parseDigit(values.charAt(1)); if(value<0 || count<1) send(player, "ESyntax error in attack:"+values); int color = playerColor(player); if(color == COLOR_NONE) send(player, "EYou are not a player in this game"); if(turn != color+TURN_MOVE) { if(turn == color+TURN_PARRY || turn == color+TURN_PARRY_OR_RETREAT) send(player, "EDefend before attacking"); else send(player, "ENot your turn to attack"); return; } Hand hand = handOf(color); if(!hand.hasCards(value, count)) { send(player, "EYou don't have the cards to attack ("+value+","+count+")"); return; } if(blackpos - whitepos != value) { send(player, "EYou are the wrong distance to attack with a "+value); return; } parryVal = value; parryCount = count; hand.removeByValue(value, count); hand.fill(deck); if(checkmate(color)) { notifyCannotParry(color); turn = TURN_GAME_OVER; } else { if(deck.isEmpty()) { finalParry = true; notifyFinalParry(); } turn = otherColor(color)+TURN_PARRY; } notifyHand(player, hand); notifyAttack(value, count, 0); notifyTurn(); } private void notifyCannotParry(int color) { sendAll(color == Game.COLOR_WHITE ? "A1" : "B1"); } private boolean checkmate(int color) { Hand hand = handOf(otherColor(color)); - return hand.hasCards(parryVal, parryCount); + return !hand.hasCards(parryVal, parryCount); } synchronized void move(UserSession player, String values) { if(values.length() != 1) send(player, "ESyntax error in advance:"+values); int distance = parseDigit(values.charAt(0)); if(distance < 0) send(player, "ESyntax error in advance:"+values); int color = playerColor(player); if(color == COLOR_NONE) send(player, "EYou are not a player in this game"); if(turn != color+TURN_MOVE) { if(turn == color+TURN_PARRY || turn == color+TURN_PARRY_OR_RETREAT) send(player, "EDefend before advancing"); else send(player, "ENot your turn to advance"); return; } if(blackpos-whitepos<=distance) { send(player, "EMay not move through other fencer"); return; } Hand hand = handOf(color); if(!hand.hasCard(distance)) { // hacked or buggy client send(player, "EYou don't have the advance card "+distance); return; } movePosOf(color, distance); hand.removeByValue(distance); hand.fill(deck); if(deck.isEmpty()) { endGame(); return; } turn = otherColor(color)+TURN_MOVE; notifyPositions(); notifyHand(player, hand); notifyMove(distance); notifyTurn(); } private void notifyMove(int distance) { sendAll("m"+distance); } private void notifyRetreat(int distance) { sendAll("r"+distance); } synchronized void retreat(UserSession player, String values) { if(values.length() != 1) send(player, "ESyntax error in retreat:"+values); int distance = parseDigit(values.charAt(0)); if(distance < 0) send(player, "ESyntax error in retreat:"+values); int color = playerColor(player); if(color == COLOR_NONE) send(player, "EYou are not a player in this game"); if(turn != color+TURN_PARRY_OR_RETREAT && turn != color+TURN_MOVE) { if(turn == color+TURN_PARRY) send(player, "EYou cannot retreat from a standing attack"); else send(player, "ENot your turn to retreat"); return; } Hand hand = handOf(color); if(!hand.hasCard(distance)) { // hacked or buggy client send(player, "EYou don't have the advance card "+distance); return; } movePosOf(color, -distance); hand.removeByValue(distance); hand.fill(deck); if(deck.isEmpty() || fencerOffStrip()) { endGame(); return; } turn = otherColor(color)+TURN_MOVE; if(finalParry) endGame(); notifyPositions(); notifyHand(player, hand); notifyRetreat(distance); notifyTurn(); } synchronized void parry(UserSession player) { int color = playerColor(player); if(color == COLOR_NONE) send(player, "EYou are not a player in this game"); if(turn != color+TURN_PARRY_OR_RETREAT && turn != color+TURN_PARRY) { if(turn == color+TURN_MOVE) send(player, "EThere is no attack to parry"); else send(player, "ENot your turn to parry"); return; } Hand hand = handOf(color); if(!hand.hasCards(parryVal, parryCount)) { send(player, "EYou don't have the cards to parry ("+parryVal+","+parryCount+")"); return; } hand.removeByValue(parryVal, parryCount); turn = color+TURN_MOVE; sendAll("q"); // notify parry occured if(finalParry) endGame(); notifyTurn(); } private void endGame() { turn = TURN_GAME_OVER; if(whitepos < 1) { sendAll("B0"); return; } if(blackpos > 23) { sendAll("A0"); return; } int finalDistance = blackpos - whitepos; int whiteCount = whiteHand.countCards(finalDistance); int blackCount = blackHand.countCards(finalDistance); if(whiteCount > blackCount) { sendAll("A2"); return; } if(blackCount > whiteCount) { sendAll("B2"); return; } if(12-whitepos > blackpos-12) { sendAll("B3"); return; } if(12-whitepos < blackpos-12) { sendAll("A3"); return; } sendAll("X"); Server.lobby.removeFromGame(black); Server.lobby.removeFromGame(white); } private final boolean fencerOffStrip() { return whitepos < 1 || blackpos > 23; } private void send(UserSession who, String what) { if(who != null) who.send(what); } private void sendAll(String what) { send(white, what); send(black, what); } static private final int parseDigit(char in) { if(in<'0' || in > '9') return -1; return in-'0'; } private void notifyPositions() { StringBuilder sb = new StringBuilder(3); sb.append("x"); sb.append((char)('a'+whitepos-1)); sb.append((char)('a'+blackpos-1)); sendAll(sb.toString()); } private final void notifyHand(UserSession player, Hand hand) { send(player, hand.toString()); } private void notifyTurn() { sendAll("t"+turn); } private final int otherColor(int color) { if(color == COLOR_WHITE) return COLOR_BLACK; if(color == COLOR_BLACK) return COLOR_WHITE; return COLOR_NONE; } private final Hand handOf(int color) { if(color == COLOR_WHITE) return whiteHand; if(color == COLOR_BLACK) return blackHand; return null; } private final void movePosOf(int color, int offset) { if(color == COLOR_WHITE) whitepos += offset; if(color == COLOR_BLACK) blackpos -= offset; } }
true
false
null
null
diff --git a/src/com/google/javascript/jscomp/TypedScopeCreator.java b/src/com/google/javascript/jscomp/TypedScopeCreator.java index c7005b2b..8426f735 100644 --- a/src/com/google/javascript/jscomp/TypedScopeCreator.java +++ b/src/com/google/javascript/jscomp/TypedScopeCreator.java @@ -1,1532 +1,1534 @@ /* * Copyright 2004 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.jscomp.TypeCheck.ENUM_DUP; import static com.google.javascript.jscomp.TypeCheck.ENUM_NOT_CONSTANT; import static com.google.javascript.jscomp.TypeCheck.MULTIPLE_VAR_DEF; import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_OBJECT_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.DATE_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.ERROR_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.EVAL_ERROR_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.FUNCTION_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NO_OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NO_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_OBJECT_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.RANGE_ERROR_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.REFERENCE_ERROR_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.REGEXP_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.REGEXP_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_OBJECT_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.SYNTAX_ERROR_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.TYPE_ERROR_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.URI_ERROR_FUNCTION_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CodingConvention.DelegateRelationship; import com.google.javascript.jscomp.CodingConvention.ObjectLiteralCast; import com.google.javascript.jscomp.CodingConvention.SubclassRelationship; import com.google.javascript.jscomp.CodingConvention.SubclassType; import com.google.javascript.jscomp.NodeTraversal.AbstractShallowStatementCallback; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.EnumType; import com.google.javascript.rhino.jstype.FunctionParamBuilder; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; /** * Creates the symbol table of variables available in the current scope and * their types. * * Scopes created by this class are very different from scopes created * by the syntactic scope creator. These scopes have type information, and * include some qualified names in addition to variables * (like Class.staticMethod). * * When building scope information, also declares relevant information * about types in the type registry. */ final class TypedScopeCreator implements ScopeCreator { /** * A suffix for naming delegate proxies differently from their base. */ static final String DELEGATE_PROXY_SUFFIX = "(Proxy)"; static final DiagnosticType MALFORMED_TYPEDEF = DiagnosticType.warning( "JSC_MALFORMED_TYPEDEF", "Typedef for {0} does not have any type information"); static final DiagnosticType ENUM_INITIALIZER = DiagnosticType.warning( "JSC_ENUM_INITIALIZER_NOT_ENUM", "enum initializer must be an object literal or an enum"); static final DiagnosticType CONSTRUCTOR_EXPECTED = DiagnosticType.warning( "JSC_REFLECT_CONSTRUCTOR_EXPECTED", "Constructor expected as first argument"); private final AbstractCompiler compiler; private final ErrorReporter typeParsingErrorReporter; private final TypeValidator validator; private final CodingConvention codingConvention; private final JSTypeRegistry typeRegistry; private List<ObjectType> delegateProxyPrototypes = Lists.newArrayList(); /** * Defer attachment of types to nodes until all type names * have been resolved. Then, we can resolve the type and attach it. */ private class DeferredSetType { final Node node; final JSType type; DeferredSetType(Node node, JSType type) { Preconditions.checkNotNull(node); Preconditions.checkNotNull(type); this.node = node; this.type = type; // Other parts of this pass may read off the node. // (like when we set the LHS of an assign with a typed RHS function.) node.setJSType(type); } void resolve(Scope scope) { node.setJSType(type.resolve(typeParsingErrorReporter, scope)); } } TypedScopeCreator(AbstractCompiler compiler) { this(compiler, compiler.getCodingConvention()); } TypedScopeCreator(AbstractCompiler compiler, CodingConvention codingConvention) { this.compiler = compiler; this.validator = compiler.getTypeValidator(); this.codingConvention = codingConvention; this.typeRegistry = compiler.getTypeRegistry(); this.typeParsingErrorReporter = typeRegistry.getErrorReporter(); } /** * Creates a scope with all types declared. Declares newly discovered types * and type properties in the type registry. */ public Scope createScope(Node root, Scope parent) { // Constructing the global scope is very different than constructing // inner scopes, because only global scopes can contain named classes that // show up in the type registry. Scope newScope = null; AbstractScopeBuilder scopeBuilder = null; if (parent == null) { // Find all the classes in the global scope. newScope = createInitialScope(root); GlobalScopeBuilder globalScopeBuilder = new GlobalScopeBuilder(newScope); scopeBuilder = globalScopeBuilder; NodeTraversal.traverse(compiler, root, scopeBuilder); } else { newScope = new Scope(parent, root); LocalScopeBuilder localScopeBuilder = new LocalScopeBuilder(newScope); scopeBuilder = localScopeBuilder; localScopeBuilder.build(); } scopeBuilder.resolveStubDeclarations(); scopeBuilder.resolveTypes(); // Gather the properties in each function that we found in the // global scope, if that function has a @this type that we can // build properties on. for (Node functionNode : scopeBuilder.nonExternFunctions) { JSType type = functionNode.getJSType(); if (type != null && type instanceof FunctionType) { FunctionType fnType = (FunctionType) type; ObjectType fnThisType = fnType.getTypeOfThis(); if (!fnThisType.isUnknownType()) { NodeTraversal.traverse(compiler, functionNode.getLastChild(), scopeBuilder.new CollectProperties(fnThisType)); } } } if (parent == null) { codingConvention.defineDelegateProxyPrototypeProperties( typeRegistry, newScope, delegateProxyPrototypes); } return newScope; } /** * Create the outermost scope. This scope contains native binding such as * {@code Object}, {@code Date}, etc. */ @VisibleForTesting Scope createInitialScope(Node root) { NodeTraversal.traverse(compiler, root, new DiscoverEnums(typeRegistry)); Scope s = new Scope(root, compiler); declareNativeFunctionType(s, ARRAY_FUNCTION_TYPE); declareNativeFunctionType(s, BOOLEAN_OBJECT_FUNCTION_TYPE); declareNativeFunctionType(s, DATE_FUNCTION_TYPE); declareNativeFunctionType(s, ERROR_FUNCTION_TYPE); declareNativeFunctionType(s, EVAL_ERROR_FUNCTION_TYPE); declareNativeFunctionType(s, FUNCTION_FUNCTION_TYPE); declareNativeFunctionType(s, NUMBER_OBJECT_FUNCTION_TYPE); declareNativeFunctionType(s, OBJECT_FUNCTION_TYPE); declareNativeFunctionType(s, RANGE_ERROR_FUNCTION_TYPE); declareNativeFunctionType(s, REFERENCE_ERROR_FUNCTION_TYPE); declareNativeFunctionType(s, REGEXP_FUNCTION_TYPE); declareNativeFunctionType(s, STRING_OBJECT_FUNCTION_TYPE); declareNativeFunctionType(s, SYNTAX_ERROR_FUNCTION_TYPE); declareNativeFunctionType(s, TYPE_ERROR_FUNCTION_TYPE); declareNativeFunctionType(s, URI_ERROR_FUNCTION_TYPE); declareNativeValueType(s, "undefined", VOID_TYPE); // The typedef construct needs the any type, so that it can be assigned // to anything. This is kind of a hack, and an artifact of the typedef // syntax we've chosen. declareNativeValueType(s, "goog.typedef", NO_TYPE); // ActiveXObject is unqiuely special, because it can be used to construct // any type (the type that it creates is related to the arguments you // pass to it). declareNativeValueType(s, "ActiveXObject", NO_OBJECT_TYPE); return s; } private void declareNativeFunctionType(Scope scope, JSTypeNative tId) { FunctionType t = typeRegistry.getNativeFunctionType(tId); declareNativeType(scope, t.getInstanceType().getReferenceName(), t); declareNativeType( scope, t.getPrototype().getReferenceName(), t.getPrototype()); } private void declareNativeValueType(Scope scope, String name, JSTypeNative tId) { declareNativeType(scope, name, typeRegistry.getNativeType(tId)); } private void declareNativeType(Scope scope, String name, JSType t) { scope.declare(name, null, t, null, false); } private static class DiscoverEnums extends AbstractShallowStatementCallback { private final JSTypeRegistry registry; DiscoverEnums(JSTypeRegistry registry) { this.registry = registry; } @Override public void visit(NodeTraversal t, Node node, Node parent) { Node nameNode = null; switch (node.getType()) { case Token.VAR: for (Node child = node.getFirstChild(); child != null; child = child.getNext()) { identifyEnumInNameNode( child, NodeUtil.getInfoForNameNode(child)); } break; case Token.EXPR_RESULT: Node maybeAssign = node.getFirstChild(); if (maybeAssign.getType() == Token.ASSIGN) { identifyEnumInNameNode( maybeAssign.getFirstChild(), maybeAssign.getJSDocInfo()); } break; } } private void identifyEnumInNameNode(Node nameNode, JSDocInfo info) { if (info != null && info.hasEnumParameterType()) { registry.identifyEnumName(nameNode.getQualifiedName()); } } } /** * Given a node, determines whether that node names a prototype * property, and if so, returns the qualfied name node representing * the owner of that property. Otherwise, returns null. */ private static Node getPrototypePropertyOwner(Node n) { if (n.getType() == Token.GETPROP) { Node firstChild = n.getFirstChild(); if (firstChild.getType() == Token.GETPROP && firstChild.getLastChild().getString().equals("prototype")) { Node maybeOwner = firstChild.getFirstChild(); if (maybeOwner.isQualifiedName()) { return maybeOwner; } } } return null; } private void attachLiteralTypes(Node n) { switch (n.getType()) { case Token.NULL: n.setJSType(getNativeType(NULL_TYPE)); break; case Token.VOID: n.setJSType(getNativeType(VOID_TYPE)); break; case Token.STRING: n.setJSType(getNativeType(STRING_TYPE)); break; case Token.NUMBER: n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.TRUE: case Token.FALSE: n.setJSType(getNativeType(BOOLEAN_TYPE)); break; case Token.REGEXP: n.setJSType(getNativeType(REGEXP_TYPE)); break; case Token.REF_SPECIAL: n.setJSType(getNativeType(UNKNOWN_TYPE)); break; case Token.OBJECTLIT: if (n.getJSType() == null) { n.setJSType(typeRegistry.createAnonymousObjectType()); } break; // NOTE(nicksantos): If we ever support Array tuples, // we will need to put ARRAYLIT here as well. } } private JSType getNativeType(JSTypeNative nativeType) { return typeRegistry.getNativeType(nativeType); } private abstract class AbstractScopeBuilder implements NodeTraversal.Callback { /** * The scope that we're builidng. */ final Scope scope; private final List<DeferredSetType> deferredSetTypes = Lists.newArrayList(); /** * Functions that we found in the global scope and not in externs. */ private final List<Node> nonExternFunctions = Lists.newArrayList(); /** * Type-less stubs. * * If at the end of traversal, we still don't have types for these * stubs, then we should declare UNKNOWN types. */ private final List<StubDeclaration> stubDeclarations = Lists.newArrayList(); /** * The current source file that we're in. */ private String sourceName = null; private AbstractScopeBuilder(Scope scope) { this.scope = scope; } void setDeferredType(Node node, JSType type) { deferredSetTypes.add(new DeferredSetType(node, type)); } void resolveTypes() { // Resolve types and attach them to nodes. for (DeferredSetType deferred : deferredSetTypes) { deferred.resolve(scope); } // Resolve types and attach them to scope slots. Iterator<Var> vars = scope.getVars(); while (vars.hasNext()) { vars.next().resolveType(typeParsingErrorReporter); } // Tell the type registry that any remaining types // are unknown. typeRegistry.resolveTypesInScope(scope); } @Override public final boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) { if (n.getType() == Token.FUNCTION || n.getType() == Token.SCRIPT) { sourceName = (String) n.getProp(Node.SOURCENAME_PROP); } // We do want to traverse the name of a named function, but we don't // want to traverse the arguments or body. return parent == null || parent.getType() != Token.FUNCTION || n == parent.getFirstChild() || parent == scope.getRootNode(); } @Override public void visit(NodeTraversal t, Node n, Node parent) { attachLiteralTypes(n); switch (n.getType()) { case Token.CALL: checkForClassDefiningCalls(t, n, parent); break; case Token.FUNCTION: if (t.getInput() == null || !t.getInput().isExtern()) { nonExternFunctions.add(n); } // VARs and ASSIGNs are handled in different branches of this // switch statement. if (parent.getType() != Token.ASSIGN && parent.getType() != Token.NAME) { defineDeclaredFunction(n, parent); } break; case Token.ASSIGN: // Handle constructor and enum definitions. defineNamedTypeAssign(n, parent); // Handle initialization of properties. Node firstChild = n.getFirstChild(); if (firstChild.getType() == Token.GETPROP && firstChild.isQualifiedName()) { maybeDeclareQualifiedName(t, n.getJSDocInfo(), firstChild, n, firstChild.getNext()); } break; case Token.CATCH: defineCatch(n, parent); break; case Token.VAR: defineVar(n, parent); break; case Token.GETPROP: // Handle stubbed properties. if (parent.getType() == Token.EXPR_RESULT && n.isQualifiedName()) { maybeDeclareQualifiedName(t, n.getJSDocInfo(), n, parent, null); } break; } } /** * Returns the type specified in a JSDoc annotation near a GETPROP or NAME. * * Extracts type information from either the {@code @type} tag or from * the {@code @return} and {@code @param} tags. */ JSType getDeclaredTypeInAnnotation( NodeTraversal t, Node node, JSDocInfo info) { return getDeclaredTypeInAnnotation(t.getSourceName(), node, info); } JSType getDeclaredTypeInAnnotation(String sourceName, Node node, JSDocInfo info) { JSType jsType = null; Node objNode = node.getType() == Token.GETPROP ? node.getFirstChild() : null; if (info != null) { if (info.hasType()) { jsType = info.getType().evaluate(scope, typeRegistry); } else if (FunctionTypeBuilder.isFunctionTypeDeclaration(info)) { String fnName = node.getQualifiedName(); // constructors are often handled separately. if (info.isConstructor() && typeRegistry.getType(fnName) != null) { return null; } FunctionTypeBuilder builder = new FunctionTypeBuilder( fnName, compiler, node, sourceName, scope) .inferTemplateTypeName(info) .inferReturnType(info) .inferParameterTypes(info) .inferInheritance(info); // Infer the context type. boolean searchedForThisType = false; if (objNode != null) { if (objNode.getType() == Token.GETPROP && objNode.getLastChild().getString().equals("prototype")) { builder.inferThisType(info, objNode.getFirstChild()); searchedForThisType = true; } else if (objNode.getType() == Token.THIS) { builder.inferThisType(info, objNode.getJSType()); searchedForThisType = true; } } if (!searchedForThisType) { builder.inferThisType(info, (Node) null); } jsType = builder.buildAndRegister(); } } return jsType; } /** * Asserts that it's ok to define this node's name. * The node should have a source name and be of the specified type. */ void assertDefinitionNode(Node n, int type) { Preconditions.checkState(sourceName != null); Preconditions.checkState(n.getType() == type); } /** * Defines a catch parameter. */ void defineCatch(Node n, Node parent) { assertDefinitionNode(n, Token.CATCH); Node catchName = n.getFirstChild(); defineSlot(catchName, n, null); } /** * Defines a VAR initialization. */ void defineVar(Node n, Node parent) { assertDefinitionNode(n, Token.VAR); JSDocInfo info = n.getJSDocInfo(); if (n.hasMoreThanOneChild()) { if (info != null) { // multiple children compiler.report(JSError.make(sourceName, n, MULTIPLE_VAR_DEF)); } for (Node name : n.children()) { defineName(name, n, parent, name.getJSDocInfo()); } } else { Node name = n.getFirstChild(); defineName(name, n, parent, (info != null) ? info : name.getJSDocInfo()); } } /** * Defines a declared function. */ void defineDeclaredFunction(Node n, Node parent) { assertDefinitionNode(n, Token.FUNCTION); JSDocInfo info = n.getJSDocInfo(); int parentType = parent.getType(); Preconditions.checkState( (scope.isLocal() || parentType != Token.ASSIGN) && parentType != Token.NAME, "function defined as standalone function when it is being " + "assigned"); String functionName = n.getFirstChild().getString(); FunctionType functionType = getFunctionType(functionName, n, info, null); if (NodeUtil.isFunctionDeclaration(n)) { defineSlot(n.getFirstChild(), n, functionType); } } /** * Defines a qualified name assign to an enum or constructor. */ void defineNamedTypeAssign(Node n, Node parent) { assertDefinitionNode(n, Token.ASSIGN); JSDocInfo info = n.getJSDocInfo(); // TODO(nicksantos): We should support direct assignment to a // prototype, as in: // Foo.prototype = { // a: function() { ... }, // b: function() { ... } // }; // Right now (6/23/08), we understand most of this syntax, but we // don't tie the "a" and "b" methods to the context of Foo. Node rvalue = n.getLastChild(); Node lvalue = n.getFirstChild(); info = (info != null) ? info : rvalue.getJSDocInfo(); if (rvalue.getType() == Token.FUNCTION || info != null && info.isConstructor()) { getFunctionType(lvalue.getQualifiedName(), rvalue, info, lvalue); } else if (info != null && info.hasEnumParameterType()) { JSType type = getEnumType(lvalue.getQualifiedName(), n, rvalue, info.getEnumParameterType().evaluate(scope, typeRegistry)); if (type != null) { setDeferredType(lvalue, type); } } } /** * Defines a variable based on the {@link Token#NAME} node passed. * @param name The {@link Token#NAME} node. * @param var The parent of the {@code name} node, which must be a * {@link Token#VAR} node. * @param parent {@code var}'s parent. * @param info the {@link JSDocInfo} information relating to this * {@code name} node. */ private void defineName(Node name, Node var, Node parent, JSDocInfo info) { Node value = name.getFirstChild(); if (value != null && value.getType() == Token.FUNCTION) { // function String functionName = name.getString(); FunctionType functionType = getFunctionType(functionName, value, info, null); if (functionType.isReturnTypeInferred() && scope.isLocal()) { defineSlot(name, var, null); } else { defineSlot(name, var, functionType); } } else { // variable's type JSType type = null; if (info == null) { // the variable's type will be inferred CompilerInput input = compiler.getInput(sourceName); Preconditions.checkNotNull(input, sourceName); type = input.isExtern() ? getNativeType(UNKNOWN_TYPE) : null; } else if (info.hasEnumParameterType()) { type = getEnumType(name.getString(), var, value, info.getEnumParameterType().evaluate(scope, typeRegistry)); } else if (info.isConstructor()) { type = getFunctionType(name.getString(), value, info, name); } else { type = getDeclaredTypeInAnnotation(sourceName, name, info); } defineSlot(name, var, type); } } /** * Gets the function type from the function node and its attached * {@link JSDocInfo}. * @param name the function's name * @param rValue the function node. It must be a {@link Token#FUNCTION}. * @param info the {@link JSDocInfo} attached to the function definition * @param lvalueNode The node where this function is being * assigned. For example, {@code A.prototype.foo = ...} would be used to * determine that this function is a method of A.prototype. May be * null to indicate that this is not being assigned to a qualified name. */ private FunctionType getFunctionType(String name, Node rValue, JSDocInfo info, @Nullable Node lvalueNode) { FunctionType functionType = null; // Global function aliases should be registered with the type registry. if (rValue != null && rValue.isQualifiedName() && scope.isGlobal()) { Var var = scope.getVar(rValue.getQualifiedName()); if (var != null && var.getType() instanceof FunctionType) { functionType = (FunctionType) var.getType(); if (functionType != null && functionType.isConstructor()) { typeRegistry.declareType(name, functionType.getInstanceType()); } } return functionType; } Node owner = null; if (lvalueNode != null) { owner = getPrototypePropertyOwner(lvalueNode); } Node errorRoot = rValue == null ? lvalueNode : rValue; boolean isFnLiteral = rValue != null && rValue.getType() == Token.FUNCTION; Node fnRoot = isFnLiteral ? rValue : null; Node parametersNode = isFnLiteral ? rValue.getFirstChild().getNext() : null; Node fnBlock = isFnLiteral ? parametersNode.getNext() : null; if (functionType == null && info != null && info.hasType()) { JSType type = info.getType().evaluate(scope, typeRegistry); // Known to be not null since we have the FUNCTION token there. type = type.restrictByNotNullOrUndefined(); if (type.isFunctionType()) { functionType = (FunctionType) type; functionType.setJSDocInfo(info); } } if (functionType == null) { // Find the type of any overridden function. FunctionType overriddenPropType = null; if (lvalueNode != null && lvalueNode.getType() == Token.GETPROP && lvalueNode.isQualifiedName()) { Var var = scope.getVar( lvalueNode.getFirstChild().getQualifiedName()); if (var != null) { ObjectType ownerType = ObjectType.cast(var.getType()); if (ownerType != null) { String propName = lvalueNode.getLastChild().getString(); overriddenPropType = findOverriddenFunction(ownerType, propName); } } } functionType = new FunctionTypeBuilder(name, compiler, errorRoot, sourceName, scope) .setSourceNode(fnRoot) .inferFromOverriddenFunction(overriddenPropType, parametersNode) .inferTemplateTypeName(info) .inferReturnType(info) .inferInheritance(info) .inferThisType(info, owner) .inferParameterTypes(parametersNode, info) .inferReturnStatementsAsLastResort(fnBlock) .buildAndRegister(); } // assigning the function type to the function node if (rValue != null) { setDeferredType(rValue, functionType); } // all done return functionType; } /** * Find the function that's being overridden on this type, if any. */ private FunctionType findOverriddenFunction( ObjectType ownerType, String propName) { // First, check to see if the property is implemented // on a superclass. JSType propType = ownerType.getPropertyType(propName); if (propType instanceof FunctionType) { return (FunctionType) propType; } else { // If it's not, then check to see if it's implemented // on an implemented interface. for (ObjectType iface : ownerType.getCtorImplementedInterfaces()) { propType = iface.getPropertyType(propName); if (propType instanceof FunctionType) { return (FunctionType) propType; } } } return null; } /** * Gets an enum type. If the definition is correct, the object literal used * to define the enum is traversed to gather the elements name, and this * method checks for duplicates. This method also enforces that all * elements' name be syntactic constants according to the * {@link CodingConvention} used. * * @param name the enum's name such as {@code HELLO} or {@code goog.foo.BAR} * @param value the enum's original value. This value may be {@code null}. * @param parent the value's parent * @param elementsType the type of the elements of this enum * @return the enum type */ private EnumType getEnumType(String name, Node parent, Node value, JSType elementsType) { EnumType enumType = null; // no value with @enum if (value != null) { if (value.getType() == Token.OBJECTLIT) { // collect enum elements enumType = typeRegistry.createEnumType(name, elementsType); // populate the enum type. Node key = value.getFirstChild(); while (key != null) { String keyName = NodeUtil.getStringValue(key); if (enumType.hasOwnProperty(keyName)) { compiler.report(JSError.make(sourceName, key, ENUM_DUP, keyName)); } else if (!codingConvention.isValidEnumKey(keyName)) { compiler.report( JSError.make(sourceName, key, ENUM_NOT_CONSTANT, keyName)); } else { enumType.defineElement(keyName); } key = key.getNext(); key = (key == null) ? null : key.getNext(); } } else if (value.isQualifiedName()) { Var var = scope.getVar(value.getQualifiedName()); if (var != null && var.getType() instanceof EnumType) { enumType = (EnumType) var.getType(); } } } if (enumType == null) { compiler.report(JSError.make(sourceName, parent, ENUM_INITIALIZER)); } else if (scope.isGlobal()) { if (name != null && !name.isEmpty()) { typeRegistry.declareType(name, enumType.getElementsType()); } } return enumType; } /** * Defines a typed variable. The defining node will be annotated with the * variable's type or {@code null} if its type is inferred. * @param name the defining node. It must be a {@link Token#NAME}. * @param parent the {@code name}'s parent. * @param type the variable's type. It may be {@code null}, in which case * the variable's type will be inferred. */ private void defineSlot(Node name, Node parent, JSType type) { defineSlot(name, parent, type, type == null); } /** * Defines a typed variable. The defining node will be annotated with the * variable's type of {@link JSTypeNative#UNKNOWN_TYPE} if its type is * inferred. * * Slots may be any variable or any qualified name in the global scope. * * @param n the defining NAME or GETPROP node. * @param parent the {@code n}'s parent. * @param type the variable's type. It may be {@code null} if * {@code inferred} is {@code true}. */ void defineSlot(Node n, Node parent, JSType type, boolean inferred) { Preconditions.checkArgument(inferred || type != null); // Only allow declarations of NAMEs and qualfied names. boolean shouldDeclareOnGlobalThis = false; if (n.getType() == Token.NAME) { Preconditions.checkArgument( parent.getType() == Token.FUNCTION || parent.getType() == Token.VAR || parent.getType() == Token.LP || parent.getType() == Token.CATCH); shouldDeclareOnGlobalThis = scope.isGlobal() && (parent.getType() == Token.VAR || parent.getType() == Token.FUNCTION); } else { Preconditions.checkArgument( n.getType() == Token.GETPROP && (parent.getType() == Token.ASSIGN || parent.getType() == Token.EXPR_RESULT)); } String variableName = n.getQualifiedName(); Preconditions.checkArgument(!variableName.isEmpty()); // If n is a property, then we should really declare it in the // scope where the root object appears. This helps out people // who declare "global" names in an anonymous namespace. Scope scopeToDeclareIn = scope; if (n.getType() == Token.GETPROP && !scope.isGlobal() && isQnameRootedInGlobalScope(n)) { Scope globalScope = scope.getGlobalScope(); // don't try to declare in the global scope if there's // already a symbol there with this name. if (!globalScope.isDeclared(variableName, false)) { scopeToDeclareIn = scope.getGlobalScope(); } } // declared in closest scope? if (scopeToDeclareIn.isDeclared(variableName, false)) { Var oldVar = scopeToDeclareIn.getVar(variableName); validator.expectUndeclaredVariable( sourceName, n, parent, oldVar, variableName, type); } else { if (!inferred) { setDeferredType(n, type); } CompilerInput input = compiler.getInput(sourceName); scopeToDeclareIn.declare(variableName, n, type, input, inferred); if (shouldDeclareOnGlobalThis) { ObjectType globalThis = typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS); boolean isExtern = input.isExtern(); if (inferred) { globalThis.defineInferredProperty(variableName, type == null ? getNativeType(JSTypeNative.NO_TYPE) : type, isExtern); } else { globalThis.defineDeclaredProperty(variableName, type, isExtern); } } // If we're in the global scope, also declare var.prototype // in the scope chain. if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) { FunctionType fnType = (FunctionType) type; if (fnType.isConstructor() || fnType.isInterface()) { FunctionType superClassCtor = fnType.getSuperClassConstructor(); scopeToDeclareIn.declare(variableName + ".prototype", n, fnType.getPrototype(), compiler.getInput(sourceName), /* declared iff there's an explicit supertype */ superClassCtor == null || superClassCtor.getInstanceType().equals( getNativeType(OBJECT_TYPE))); } } } } /** * Check if the given node is a property of a name in the global scope. */ private boolean isQnameRootedInGlobalScope(Node n) { Node root = NodeUtil.getRootOfQualifiedName(n); if (root.getType() == Token.NAME) { Var var = scope.getVar(root.getString()); if (var != null) { return var.isGlobal(); } } return false; } /** * Look for a type declaration on a GETPROP node. * * @param info The doc info for this property. * @param n A top-level GETPROP node (it should not be contained inside * another GETPROP). * @param rhsValue The node that {@code n} is being initialized to, * or {@code null} if this is a stub declaration. */ private JSType getDeclaredGetPropType(NodeTraversal t, JSDocInfo info, Node n, Node rhsValue) { if (info != null && info.hasType()) { return getDeclaredTypeInAnnotation(t, n, info); } else if (info != null && info.hasEnumParameterType()) { return n.getJSType(); } else if (rhsValue != null && rhsValue.getType() == Token.FUNCTION) { return rhsValue.getJSType(); } else { return getDeclaredTypeInAnnotation(t, n, info); } } /** * Look for class-defining calls. * Because JS has no 'native' syntax for defining classes, * this is often very coding-convention dependent and business-logic heavy. */ private void checkForClassDefiningCalls( NodeTraversal t, Node n, Node parent) { SubclassRelationship relationship = codingConvention.getClassesDefinedByCall(n); if (relationship != null) { ObjectType superClass = ObjectType.cast( typeRegistry.getType(relationship.superclassName)); ObjectType subClass = ObjectType.cast( typeRegistry.getType(relationship.subclassName)); if (superClass != null && subClass != null) { FunctionType superCtor = superClass.getConstructor(); FunctionType subCtor = subClass.getConstructor(); if (relationship.type == SubclassType.INHERITS) { validator.expectSuperType(t, n, superClass, subClass); } if (superCtor != null && subCtor != null) { codingConvention.applySubclassRelationship( superCtor, subCtor, relationship.type); } } } String singletonGetterClassName = codingConvention.getSingletonGetterClassName(n); if (singletonGetterClassName != null) { ObjectType objectType = ObjectType.cast( typeRegistry.getType(singletonGetterClassName)); if (objectType != null) { FunctionType functionType = objectType.getConstructor(); if (functionType != null) { FunctionType getterType = typeRegistry.createFunctionType(objectType); codingConvention.applySingletonGetter(functionType, getterType, objectType); } } } DelegateRelationship delegateRelationship = codingConvention.getDelegateRelationship(n); if (delegateRelationship != null) { applyDelegateRelationship(delegateRelationship); } ObjectLiteralCast objectLiteralCast = codingConvention.getObjectLiteralCast(t, n); if (objectLiteralCast != null) { ObjectType type = ObjectType.cast( typeRegistry.getType(objectLiteralCast.typeName)); if (type != null && type.getConstructor() != null) { setDeferredType(objectLiteralCast.objectNode, type); } else { compiler.report(JSError.make(t.getSourceName(), n, CONSTRUCTOR_EXPECTED)); } } } /** * Apply special properties that only apply to delegates. */ private void applyDelegateRelationship( DelegateRelationship delegateRelationship) { ObjectType delegatorObject = ObjectType.cast( typeRegistry.getType(delegateRelationship.delegator)); ObjectType delegateBaseObject = ObjectType.cast( typeRegistry.getType(delegateRelationship.delegateBase)); ObjectType delegateSuperObject = ObjectType.cast( typeRegistry.getType(codingConvention.getDelegateSuperclassName())); if (delegatorObject != null && delegateBaseObject != null && delegateSuperObject != null) { FunctionType delegatorCtor = delegatorObject.getConstructor(); FunctionType delegateBaseCtor = delegateBaseObject.getConstructor(); FunctionType delegateSuperCtor = delegateSuperObject.getConstructor(); if (delegatorCtor != null && delegateBaseCtor != null && delegateSuperCtor != null) { FunctionParamBuilder functionParamBuilder = new FunctionParamBuilder(typeRegistry); functionParamBuilder.addRequiredParams( getNativeType(U2U_CONSTRUCTOR_TYPE)); FunctionType findDelegate = typeRegistry.createFunctionType( typeRegistry.createDefaultObjectUnion(delegateBaseObject), functionParamBuilder.build()); FunctionType delegateProxy = typeRegistry.createConstructorType( delegateBaseObject.getReferenceName() + DELEGATE_PROXY_SUFFIX, null, null, null); delegateProxy.setPrototypeBasedOn(delegateBaseObject); codingConvention.applyDelegateRelationship( delegateSuperObject, delegateBaseObject, delegatorObject, delegateProxy, findDelegate); delegateProxyPrototypes.add(delegateProxy.getPrototype()); } } } /** * Declare the symbol for a qualified name in the global scope. * * @param info The doc info for this property. * @param n A top-level GETPROP node (it should not be contained inside * another GETPROP). * @param parent The parent of {@code n}. * @param rhsValue The node that {@code n} is being initialized to, * or {@code null} if this is a stub declaration. */ void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info, Node n, Node parent, Node rhsValue) { Node ownerNode = n.getFirstChild(); String ownerName = ownerNode.getQualifiedName(); String qName = n.getQualifiedName(); String propName = n.getLastChild().getString(); Preconditions.checkArgument(qName != null && ownerName != null); // Function prototypes are special. // It's a common JS idiom to do: // F.prototype = { ... }; // So if F does not have an explicitly declared super type, // allow F.prototype to be redefined arbitrarily. if ("prototype".equals(propName)) { Var qVar = scope.getVar(qName); if (qVar != null) { if (!qVar.isTypeInferred()) { // Just ignore assigns to declared prototypes. return; } - scope.undeclare(qVar); + if (qVar.getScope() == scope) { + scope.undeclare(qVar); + } } } // Precedence of type information on GETPROPs: // 1) @type annotation / @enum annotation // 2) ASSIGN to FUNCTION literal // 3) @param/@return annotation (with no function literal) // 4) ASSIGN to anything else // // 1 and 3 are declarations, 4 is inferred, and 2 is a declaration iff // the function has not been declared before. // // FUNCTION literals are special because TypedScopeCreator is very smart // about getting as much type information as possible for them. // Determining type for #1 + #2 + #3 JSType valueType = getDeclaredGetPropType(t, info, n, rhsValue); if (valueType == null && rhsValue != null) { // Determining type for #4 valueType = rhsValue.getJSType(); } if (valueType == null) { if (parent.getType() == Token.EXPR_RESULT) { stubDeclarations.add(new StubDeclaration( n, t.getInput() != null && t.getInput().isExtern(), ownerName)); } return; } boolean inferred = true; if (info != null) { // Determining declaration for #1 + #3 inferred = !(info.hasType() || info.hasEnumParameterType() || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred) { // Determining declaration for #2 inferred = !(rhsValue != null && rhsValue.getType() == Token.FUNCTION && !scope.isDeclared(qName, false)); } if (!inferred) { ObjectType ownerType = getObjectSlot(ownerName); if (ownerType != null) { // Only declare this as an official property if it has not been // declared yet. boolean isExtern = t.getInput() != null && t.getInput().isExtern(); if ((!ownerType.hasOwnProperty(propName) || ownerType.isPropertyTypeInferred(propName)) && ((isExtern && !ownerType.isNativeObjectType()) || !ownerType.isInstanceType())) { // If the property is undeclared or inferred, declare it now. ownerType.defineDeclaredProperty(propName, valueType, isExtern); } } // If the property is already declared, the error will be // caught when we try to declare it in the current scope. defineSlot(n, parent, valueType, inferred); } else if (rhsValue != null && rhsValue.getType() == Token.TRUE) { // We declare these for delegate proxy method properties. ObjectType ownerType = getObjectSlot(ownerName); if (ownerType instanceof FunctionType) { JSType ownerTypeOfThis = ((FunctionType) ownerType).getTypeOfThis(); String delegateName = codingConvention.getDelegateSuperclassName(); JSType delegateType = delegateName == null ? null : typeRegistry.getType(delegateName); if (delegateType != null && ownerTypeOfThis.isSubtype(delegateType)) { defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true); } } } } /** * Find the ObjectType associated with the given slot. * @param slotName The name of the slot to find the type in. * @return An object type, or null if this slot does not contain an object. */ private ObjectType getObjectSlot(String slotName) { Var ownerVar = scope.getVar(slotName); if (ownerVar != null) { JSType ownerVarType = ownerVar.getType(); return ObjectType.cast(ownerVarType == null ? null : ownerVarType.restrictByNotNullOrUndefined()); } return null; } /** * Resolve any stub delcarations to unknown types if we could not * find types for them during traversal. */ void resolveStubDeclarations() { for (StubDeclaration stub : stubDeclarations) { Node n = stub.node; Node parent = n.getParent(); String qName = n.getQualifiedName(); String propName = n.getLastChild().getString(); String ownerName = stub.ownerName; boolean isExtern = stub.isExtern; if (scope.isDeclared(qName, false)) { continue; } // If we see a stub property, make sure to register this property // in the type registry. ObjectType ownerType = getObjectSlot(ownerName); ObjectType unknownType = typeRegistry.getNativeObjectType(UNKNOWN_TYPE); defineSlot(n, parent, unknownType, true); if (ownerType != null && (isExtern || ownerType.isFunctionPrototypeType())) { // If this is a stub for a prototype, just declare it // as an unknown type. These are seen often in externs. ownerType.defineInferredProperty( propName, unknownType, isExtern); } else { typeRegistry.registerPropertyOnType( propName, ownerType == null ? unknownType : ownerType); } } } /** * Collects all declared properties in a function, and * resolves them relative to the global scope. */ private final class CollectProperties extends AbstractShallowStatementCallback { private final ObjectType thisType; CollectProperties(ObjectType thisType) { this.thisType = thisType; } public void visit(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.EXPR_RESULT) { Node child = n.getFirstChild(); switch (child.getType()) { case Token.ASSIGN: maybeCollectMember(t, child.getFirstChild(), child); break; case Token.GETPROP: maybeCollectMember(t, child, child); break; } } } private void maybeCollectMember(NodeTraversal t, Node member, Node nodeWithJsDocInfo) { JSDocInfo info = nodeWithJsDocInfo.getJSDocInfo(); // Do nothing if there is no JSDoc type info, or // if the node is not a member expression, or // if the member expression is not of the form: this.someProperty. if (info == null || member.getType() != Token.GETPROP || member.getFirstChild().getType() != Token.THIS) { return; } member.getFirstChild().setJSType(thisType); JSType jsType = getDeclaredTypeInAnnotation(t, member, info); Node name = member.getLastChild(); if (jsType != null && (name.getType() == Token.NAME || name.getType() == Token.STRING)) { thisType.defineDeclaredProperty( name.getString(), jsType, false /* functions with implementations are not in externs */); } } } // end CollectProperties } /** * A stub declaration without any type information. */ private static final class StubDeclaration { private final Node node; private final boolean isExtern; private final String ownerName; private StubDeclaration(Node node, boolean isExtern, String ownerName) { this.node = node; this.isExtern = isExtern; this.ownerName = ownerName; } } /** * A shallow traversal of the global scope to build up all classes, * functions, and methods. */ private final class GlobalScopeBuilder extends AbstractScopeBuilder { private GlobalScopeBuilder(Scope scope) { super(scope); } /** * Visit a node in the global scope, and add anything it declares to the * global symbol table. * * @param t The current traversal. * @param n The node being visited. * @param parent The parent of n */ @Override public void visit(NodeTraversal t, Node n, Node parent) { super.visit(t, n, parent); switch (n.getType()) { case Token.ASSIGN: // Handle typedefs. checkForOldStyleTypedef(t, n); break; case Token.VAR: // Handle typedefs. if (n.hasOneChild()) { checkForOldStyleTypedef(t, n); checkForTypedef(t, n.getFirstChild(), n.getJSDocInfo()); } break; } } @Override void maybeDeclareQualifiedName( NodeTraversal t, JSDocInfo info, Node n, Node parent, Node rhsValue) { checkForTypedef(t, n, info); super.maybeDeclareQualifiedName(t, info, n, parent, rhsValue); } /** * Handle typedefs. * @param t The current traversal. * @param candidate A qualified name node. * @param info JSDoc comments. */ private void checkForTypedef( NodeTraversal t, Node candidate, JSDocInfo info) { if (info == null || !info.hasTypedefType()) { return; } String typedef = candidate.getQualifiedName(); if (typedef == null) { return; } // TODO(nicksantos|user): This is a terrible, terrible hack // to bail out on recusive typedefs. We'll eventually need // to handle these properly. typeRegistry.forwardDeclareType(typedef); JSType realType = info.getTypedefType().evaluate(scope, typeRegistry); if (realType == null) { compiler.report( JSError.make( t.getSourceName(), candidate, MALFORMED_TYPEDEF, typedef)); } typeRegistry.declareType(typedef, realType); if (candidate.getType() == Token.GETPROP) { defineSlot(candidate, candidate.getParent(), getNativeType(NO_TYPE), false); } } /** * Handle typedefs. * @param t The current traversal. * @param candidate An ASSIGN or VAR node. */ // TODO(nicksantos): Kill this. private void checkForOldStyleTypedef(NodeTraversal t, Node candidate) { // old-style typedefs String typedef = codingConvention.identifyTypeDefAssign(candidate); if (typedef != null) { // TODO(nicksantos|user): This is a terrible, terrible hack // to bail out on recusive typedefs. We'll eventually need // to handle these properly. typeRegistry.forwardDeclareType(typedef); JSDocInfo info = candidate.getJSDocInfo(); JSType realType = null; if (info != null && info.getType() != null) { realType = info.getType().evaluate(scope, typeRegistry); } if (realType == null) { compiler.report( JSError.make( t.getSourceName(), candidate, MALFORMED_TYPEDEF, typedef)); } typeRegistry.declareType(typedef, realType); // Duplicate typedefs get handled when we try to register // this typedef in the scope. } } } // end GlobalScopeBuilder /** * A shallow traversal of a local scope to find all arguments and * local variables. */ private final class LocalScopeBuilder extends AbstractScopeBuilder { /** * @param scope The scope that we're builidng. */ private LocalScopeBuilder(Scope scope) { super(scope); } /** * Traverse the scope root and build it. */ void build() { NodeTraversal.traverse(compiler, scope.getRootNode(), this); } /** * Visit a node in a local scope, and add any local variables or catch * parameters into the local symbol table. * * @param t The node traversal. * @param n The node being visited. * @param parent The parent of n */ @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n == scope.getRootNode()) return; if (n.getType() == Token.LP && parent == scope.getRootNode()) { handleFunctionInputs(parent); return; } super.visit(t, n, parent); } /** Handle bleeding functions and function parameters. */ private void handleFunctionInputs(Node fnNode) { // Handle bleeding functions. Node fnNameNode = fnNode.getFirstChild(); String fnName = fnNameNode.getString(); if (!fnName.isEmpty()) { Scope.Var fnVar = scope.getVar(fnName); if (fnVar == null || // Make sure we're not touching a native function. Native // functions aren't bleeding, but may not have a declaration // node. (fnVar.getNameNode() != null && // Make sure that the function is actually bleeding by checking // if has already been declared. fnVar.getInitialValue() != fnNode)) { defineSlot(fnNameNode, fnNode, fnNode.getJSType(), false); } } declareArguments(fnNode); } /** * Declares all of a function's arguments. */ private void declareArguments(Node functionNode) { Node astParameters = functionNode.getFirstChild().getNext(); Node body = astParameters.getNext(); FunctionType functionType = (FunctionType) functionNode.getJSType(); if (functionType != null) { Node jsDocParameters = functionType.getParametersNode(); if (jsDocParameters != null) { Node jsDocParameter = jsDocParameters.getFirstChild(); for (Node astParameter : astParameters.children()) { if (jsDocParameter != null) { defineSlot(astParameter, functionNode, jsDocParameter.getJSType(), true); jsDocParameter = jsDocParameter.getNext(); } else { defineSlot(astParameter, functionNode, null, true); } } } } } // end declareArguments } // end LocalScopeBuilder } diff --git a/test/com/google/javascript/jscomp/TypeCheckTest.java b/test/com/google/javascript/jscomp/TypeCheckTest.java index 102cdea3..507691f1 100644 --- a/test/com/google/javascript/jscomp/TypeCheckTest.java +++ b/test/com/google/javascript/jscomp/TypeCheckTest.java @@ -1,7497 +1,7511 @@ /* * Copyright 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, new DefaultCodingConvention()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ foo()--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck7() throws Exception { testTypes("function foo() {delete 'abc';}", TypeCheck.BAD_DELETE); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Parse error. variable length argument must be " + "last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return number */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return string */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return string */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return boolean */" + "function f(b) { if (u()) { b = null; } return b; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return string */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return number*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateLocalVarDecl() throws Exception { testTypes( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", "variable x redefined with type string, " + "original definition at [testcode]:2 with type number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (this:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { /** TODO(user): This is not exactly correct yet. The var itself is nullable. */ testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE). restrictByNotNullOrUndefined().toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (this:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (this:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testTypes("/** @enum */var a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum9() throws Exception { testTypes( "var goog = {};" + "/** @enum */goog.a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (this:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Parse error. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } + public void testDirectPrototypeAssignment3() throws Exception { + // This verifies that the compiler doesn't crash if the user + // overwrites the prototype of a global variable in a local scope. + testTypes( + "/** @constructor */ var MainWidgetCreator = function() {};" + + "/** @param {Function} ctor */" + + "function createMainWidget(ctor) {" + + " /** @constructor */ function tempCtor() {};" + + " tempCtor.prototype = ctor.prototype;" + + " MainWidgetCreator.superClass_ = ctor.prototype;" + + " MainWidgetCreator.prototype = new tempCtor();" + + "}"); + } + public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Parse error. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Parse error. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "goog.asserts = {};" + "/** @return {*} */ goog.asserts.assert = function(x) { return x; };" + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return number */goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return number */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return number*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return !Date */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return number */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return boolean*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) { " + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return number */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Parse error. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Parse error. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {boolean} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/* @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (this:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return Array */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return string */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return string */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Parse error. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes("/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n"); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface2() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testTypes( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", "Parse error. Cycle detected in inheritance chain of type T"); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Parse error. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { // To better support third-party code, we do not warn when // there are no braces around an unknown type name. testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return x; }", null); } public void testForwardTypeDeclaration2() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }" + "f(3);", null); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testMalformedOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testMalformedOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @typedef {boolean} */ goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testDuplicateOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @constructor */ goog.Bar = function() {};" + "/** @type {number} */ goog.Bar = goog.typedef", "variable goog.Bar redefined with type number, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testOldTypeDef1() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testOldTypeDef3() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ var Bar = goog.typedef;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number|Array.<goog.Bar>} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() {});", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format(), true); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format(), true); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format(), true); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)} fn\n" + " * @param {T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)} fn\n" + " * @param {T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (description == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals(1, compiler.getWarningCount()); assertEquals(description, compiler.getWarnings()[0].description); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput("[testcode]").getAstRoot(compiler); Node externsNode = compiler.getInput("[externs]").getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
false
false
null
null
diff --git a/src/com/android/exchange/SyncManager.java b/src/com/android/exchange/SyncManager.java index b038ece3..8b51834e 100644 --- a/src/com/android/exchange/SyncManager.java +++ b/src/com/android/exchange/SyncManager.java @@ -1,1798 +1,1801 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange; import com.android.email.mail.MessagingException; import com.android.email.mail.store.TrustManagerFactory; import com.android.email.provider.EmailContent; import com.android.email.provider.EmailContent.Account; import com.android.email.provider.EmailContent.Attachment; import com.android.email.provider.EmailContent.HostAuth; import com.android.email.provider.EmailContent.HostAuthColumns; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.MailboxColumns; import com.android.email.provider.EmailContent.Message; import com.android.email.provider.EmailContent.SyncColumns; import com.android.exchange.utility.FileLogger; import org.apache.harmony.xnet.provider.jsse.SSLContextImpl; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerPNames; import org.apache.http.conn.params.ConnPerRoute; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import android.accounts.AccountManager; import android.accounts.OnAccountsUpdatedListener; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncStatusObserver; import android.database.ContentObserver; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.NetworkInfo.State; import android.os.Bundle; import android.os.Debug; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.RemoteCallbackList; import android.os.RemoteException; import android.os.PowerManager.WakeLock; import android.provider.ContactsContract; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * The SyncManager handles all aspects of starting, maintaining, and stopping the various sync * adapters used by Exchange. However, it is capable of handing any kind of email sync, and it * would be appropriate to use for IMAP push, when that functionality is added to the Email * application. * * The Email application communicates with EAS sync adapters via SyncManager's binder interface, * which exposes UI-related functionality to the application (see the definitions below) * * SyncManager uses ContentObservers to detect changes to accounts, mailboxes, and messages in * order to maintain proper 2-way syncing of data. (More documentation to follow) * */ public class SyncManager extends Service implements Runnable { private static final String TAG = "EAS SyncManager"; // The SyncManager's mailbox "id" private static final int SYNC_MANAGER_ID = -1; private static final int SECONDS = 1000; private static final int MINUTES = 60*SECONDS; private static final int ONE_DAY_MINUTES = 1440; private static final int SYNC_MANAGER_HEARTBEAT_TIME = 15*MINUTES; private static final int CONNECTIVITY_WAIT_TIME = 10*MINUTES; // Sync hold constants for services with transient errors private static final int HOLD_DELAY_MAXIMUM = 4*MINUTES; // Reason codes when SyncManager.kick is called (mainly for debugging) // UI has changed data, requiring an upsync of changes public static final int SYNC_UPSYNC = 0; // A scheduled sync (when not using push) public static final int SYNC_SCHEDULED = 1; // Mailbox was marked push public static final int SYNC_PUSH = 2; // A ping (EAS push signal) was received public static final int SYNC_PING = 3; // startSync was requested of SyncManager public static final int SYNC_SERVICE_START_SYNC = 4; // A part request (attachment load, for now) was sent to SyncManager public static final int SYNC_SERVICE_PART_REQUEST = 5; // Misc. public static final int SYNC_KICK = 6; private static final String WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.TYPE + "!=" + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + " and " + MailboxColumns.SYNC_INTERVAL + " IN (" + Mailbox.CHECK_INTERVAL_PING + ',' + Mailbox.CHECK_INTERVAL_PUSH + ')'; protected static final String WHERE_IN_ACCOUNT_AND_PUSHABLE = MailboxColumns.ACCOUNT_KEY + "=? and type in (" + Mailbox.TYPE_INBOX + ',' /*+ Mailbox.TYPE_CALENDAR + ','*/ + Mailbox.TYPE_CONTACTS + ')'; private static final String WHERE_MAILBOX_KEY = EmailContent.RECORD_ID + "=?"; private static final String WHERE_PROTOCOL_EAS = HostAuthColumns.PROTOCOL + "=\"" + AbstractSyncService.EAS_PROTOCOL + "\""; private static final String WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN = "(" + MailboxColumns.TYPE + '=' + Mailbox.TYPE_OUTBOX + " or " + MailboxColumns.SYNC_INTERVAL + "!=" + Mailbox.CHECK_INTERVAL_NEVER + ')' + " and " + MailboxColumns.ACCOUNT_KEY + " in ("; private static final String ACCOUNT_KEY_IN = MailboxColumns.ACCOUNT_KEY + " in ("; // Offsets into the syncStatus data for EAS that indicate type, exit status, and change count // The format is S<type_char>:<exit_char>:<change_count> public static final int STATUS_TYPE_CHAR = 1; public static final int STATUS_EXIT_CHAR = 3; public static final int STATUS_CHANGE_COUNT_OFFSET = 5; // Ready for ping public static final int PING_STATUS_OK = 0; // Service already running (can't ping) public static final int PING_STATUS_RUNNING = 1; // Service waiting after I/O error (can't ping) public static final int PING_STATUS_WAITING = 2; // Service had a fatal error; can't run public static final int PING_STATUS_UNABLE = 3; // We synchronize on this for all actions affecting the service and error maps private static Object sSyncToken = new Object(); // All threads can use this lock to wait for connectivity public static Object sConnectivityLock = new Object(); public static boolean sConnectivityHold = false; // Keeps track of running services (by mailbox id) private HashMap<Long, AbstractSyncService> mServiceMap = new HashMap<Long, AbstractSyncService>(); // Keeps track of services whose last sync ended with an error (by mailbox id) private HashMap<Long, SyncError> mSyncErrorMap = new HashMap<Long, SyncError>(); // Keeps track of which services require a wake lock (by mailbox id) private HashMap<Long, Boolean> mWakeLocks = new HashMap<Long, Boolean>(); // Keeps track of PendingIntents for mailbox alarms (by mailbox id) private HashMap<Long, PendingIntent> mPendingIntents = new HashMap<Long, PendingIntent>(); // The actual WakeLock obtained by SyncManager private WakeLock mWakeLock = null; private static final AccountList EMPTY_ACCOUNT_LIST = new AccountList(); // Observers that we use to look for changed mail-related data private Handler mHandler = new Handler(); private AccountObserver mAccountObserver; private MailboxObserver mMailboxObserver; private SyncedMessageObserver mSyncedMessageObserver; private MessageObserver mMessageObserver; private EasSyncStatusObserver mSyncStatusObserver; private EasAccountsUpdatedListener mAccountsUpdatedListener; private ContentResolver mResolver; // The singleton SyncManager object, with its thread and stop flag protected static SyncManager INSTANCE; private static Thread sServiceThread = null; // Cached unique device id private static String sDeviceId = null; // ConnectionManager that all EAS threads can use private static ClientConnectionManager sClientConnectionManager = null; private boolean mStop = false; // The reason for SyncManager's next wakeup call private String mNextWaitReason; // Whether we have an unsatisfied "kick" pending private boolean mKicked = false; // Receiver of connectivity broadcasts private ConnectivityReceiver mConnectivityReceiver = null; // The callback sent in from the UI using setCallback private IEmailServiceCallback mCallback; private RemoteCallbackList<IEmailServiceCallback> mCallbackList = new RemoteCallbackList<IEmailServiceCallback>(); /** * Proxy that can be used by various sync adapters to tie into SyncManager's callback system. * Used this way: SyncManager.callback().callbackMethod(args...); * The proxy wraps checking for existence of a SyncManager instance and an active callback. * Failures of these callbacks can be safely ignored. */ static private final IEmailServiceCallback.Stub sCallbackProxy = new IEmailServiceCallback.Stub() { public void loadAttachmentStatus(long messageId, long attachmentId, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.loadAttachmentStatus(messageId, attachmentId, statusCode, progress); } } public void sendMessageStatus(long messageId, String subject, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.sendMessageStatus(messageId, subject, statusCode, progress); } } public void syncMailboxListStatus(long accountId, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.syncMailboxListStatus(accountId, statusCode, progress); } } public void syncMailboxStatus(long mailboxId, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.syncMailboxStatus(mailboxId, statusCode, progress); } else if (INSTANCE != null) { INSTANCE.log("orphan syncMailboxStatus, id=" + mailboxId + " status=" + statusCode); } } }; /** * Create our EmailService implementation here. */ private final IEmailService.Stub mBinder = new IEmailService.Stub() { public int validate(String protocol, String host, String userName, String password, int port, boolean ssl, boolean trustCertificates) throws RemoteException { try { AbstractSyncService.validate(EasSyncService.class, host, userName, password, port, ssl, trustCertificates, SyncManager.this); return MessagingException.NO_ERROR; } catch (MessagingException e) { return e.getExceptionType(); } } public void startSync(long mailboxId) throws RemoteException { checkSyncManagerServiceRunning(); Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); if (m.mType == Mailbox.TYPE_OUTBOX) { // We're using SERVER_ID to indicate an error condition (it has no other use for // sent mail) Upon request to sync the Outbox, we clear this so that all messages // are candidates for sending. ContentValues cv = new ContentValues(); cv.put(SyncColumns.SERVER_ID, 0); INSTANCE.getContentResolver().update(Message.CONTENT_URI, cv, WHERE_MAILBOX_KEY, new String[] {Long.toString(mailboxId)}); kick("start outbox"); } startManualSync(mailboxId, SyncManager.SYNC_SERVICE_START_SYNC, null); } public void stopSync(long mailboxId) throws RemoteException { stopManualSync(mailboxId); } public void loadAttachment(long attachmentId, String destinationFile, String contentUriString) throws RemoteException { Attachment att = Attachment.restoreAttachmentWithId(SyncManager.this, attachmentId); partRequest(new PartRequest(att, destinationFile, contentUriString)); } public void updateFolderList(long accountId) throws RemoteException { reloadFolderList(SyncManager.this, accountId, false); } public void setLogging(int on) throws RemoteException { Eas.setUserDebug(on); } public void loadMore(long messageId) throws RemoteException { // TODO Auto-generated method stub } // The following three methods are not implemented in this version public boolean createFolder(long accountId, String name) throws RemoteException { return false; } public boolean deleteFolder(long accountId, String name) throws RemoteException { return false; } public boolean renameFolder(long accountId, String oldName, String newName) throws RemoteException { return false; } public void setCallback(IEmailServiceCallback cb) throws RemoteException { if (mCallback != null) { mCallbackList.unregister(mCallback); } mCallback = cb; mCallbackList.register(cb); } }; static class AccountList extends ArrayList<Account> { private static final long serialVersionUID = 1L; public boolean contains(long id) { for (Account account: this) { if (account.mId == id) { return true; } } return false; } public Account getById(long id) { for (Account account: this) { if (account.mId == id) { return account; } } return null; } } class AccountObserver extends ContentObserver { // mAccounts keeps track of Accounts that we care about (EAS for now) AccountList mAccounts = new AccountList(); String mSyncableEasMailboxSelector = null; String mEasAccountSelector = null; public AccountObserver(Handler handler) { super(handler); // At startup, we want to see what EAS accounts exist and cache them Cursor c = getContentResolver().query(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null, null, null); try { collectEasAccounts(c, mAccounts); } finally { c.close(); } // Create the account mailbox for any account that doesn't have one Context context = getContext(); for (Account account: mAccounts) { int cnt = Mailbox.count(context, Mailbox.CONTENT_URI, "accountKey=" + account.mId, null); if (cnt == 0) { addAccountMailbox(account.mId); } } } /** * Returns a String suitable for appending to a where clause that selects for all syncable * mailboxes in all eas accounts * @return a complex selection string that is not to be cached */ public String getSyncableEasMailboxWhere() { if (mSyncableEasMailboxSelector == null) { StringBuilder sb = new StringBuilder(WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN); boolean first = true; for (Account account: mAccounts) { if (!first) { sb.append(','); } else { first = false; } sb.append(account.mId); } sb.append(')'); mSyncableEasMailboxSelector = sb.toString(); } return mSyncableEasMailboxSelector; } /** * Returns a String suitable for appending to a where clause that selects for all eas * accounts. * @return a String in the form "accountKey in (a, b, c...)" that is not to be cached */ public String getAccountKeyWhere() { if (mEasAccountSelector == null) { StringBuilder sb = new StringBuilder(ACCOUNT_KEY_IN); boolean first = true; for (Account account: mAccounts) { if (!first) { sb.append(','); } else { first = false; } sb.append(account.mId); } sb.append(')'); mEasAccountSelector = sb.toString(); } return mEasAccountSelector; } private boolean syncParametersChanged(Account account) { long accountId = account.mId; // Reload account from database to get its current state account = Account.restoreAccountWithId(getContext(), accountId); for (Account oldAccount: mAccounts) { if (oldAccount.mId == accountId) { return oldAccount.mSyncInterval != account.mSyncInterval || oldAccount.mSyncLookback != account.mSyncLookback; } } // Really, we can't get here, but we don't want the compiler to complain return false; } @Override public void onChange(boolean selfChange) { maybeStartSyncManagerThread(); // A change to the list requires us to scan for deletions (to stop running syncs) // At startup, we want to see what accounts exist and cache them AccountList currentAccounts = new AccountList(); Cursor c = getContentResolver().query(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null, null, null); try { collectEasAccounts(c, currentAccounts); for (Account account : mAccounts) { if (!currentAccounts.contains(account.mId)) { // This is a deletion; shut down any account-related syncs stopAccountSyncs(account.mId, true); // Delete this from AccountManager... android.accounts.Account acct = new android.accounts.Account(account.mEmailAddress, Eas.ACCOUNT_MANAGER_TYPE); AccountManager.get(SyncManager.this).removeAccount(acct, null, null); mSyncableEasMailboxSelector = null; mEasAccountSelector = null; } else { // See whether any of our accounts has changed sync interval or window if (syncParametersChanged(account)) { // Set pushable boxes' sync interval to the sync interval of the Account Account updatedAccount = Account.restoreAccountWithId(getContext(), account.mId); ContentValues cv = new ContentValues(); cv.put(MailboxColumns.SYNC_INTERVAL, updatedAccount.mSyncInterval); getContentResolver().update(Mailbox.CONTENT_URI, cv, WHERE_IN_ACCOUNT_AND_PUSHABLE, new String[] {Long.toString(account.mId)}); // Stop all current syncs; the appropriate ones will restart INSTANCE.log("Account " + account.mDisplayName + " changed; stop running syncs..."); stopAccountSyncs(account.mId, true); } } } // Look for new accounts for (Account account: currentAccounts) { if (!mAccounts.contains(account.mId)) { // This is an addition; create our magic hidden mailbox... addAccountMailbox(account.mId); // Don't forget to cache the HostAuth HostAuth ha = HostAuth.restoreHostAuthWithId(getContext(), account.mHostAuthKeyRecv); account.mHostAuthRecv = ha; mAccounts.add(account); mSyncableEasMailboxSelector = null; mEasAccountSelector = null; } } // Finally, make sure mAccounts is up to date mAccounts = currentAccounts; } finally { c.close(); } // See if there's anything to do... kick("account changed"); } private void collectEasAccounts(Cursor c, ArrayList<Account> accounts) { Context context = getContext(); while (c.moveToNext()) { long hostAuthId = c.getLong(Account.CONTENT_HOST_AUTH_KEY_RECV_COLUMN); if (hostAuthId > 0) { HostAuth ha = HostAuth.restoreHostAuthWithId(context, hostAuthId); if (ha != null && ha.mProtocol.equals("eas")) { Account account = new Account().restore(c); // Cache the HostAuth account.mHostAuthRecv = ha; accounts.add(account); } } } } private void addAccountMailbox(long acctId) { Account acct = Account.restoreAccountWithId(getContext(), acctId); Mailbox main = new Mailbox(); main.mDisplayName = Eas.ACCOUNT_MAILBOX; main.mServerId = Eas.ACCOUNT_MAILBOX + System.nanoTime(); main.mAccountKey = acct.mId; main.mType = Mailbox.TYPE_EAS_ACCOUNT_MAILBOX; main.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; main.mFlagVisible = false; main.save(getContext()); INSTANCE.log("Initializing account: " + acct.mDisplayName); } private void stopAccountSyncs(long acctId, boolean includeAccountMailbox) { synchronized (sSyncToken) { List<Long> deletedBoxes = new ArrayList<Long>(); for (Long mid : INSTANCE.mServiceMap.keySet()) { Mailbox box = Mailbox.restoreMailboxWithId(INSTANCE, mid); if (box != null) { if (box.mAccountKey == acctId) { if (!includeAccountMailbox && box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { AbstractSyncService svc = INSTANCE.mServiceMap.get(mid); if (svc != null) { svc.stop(); } continue; } AbstractSyncService svc = INSTANCE.mServiceMap.get(mid); if (svc != null) { svc.stop(); - svc.mThread.interrupt(); + Thread t = svc.mThread; + if (t != null) { + t.interrupt(); + } } deletedBoxes.add(mid); } } } for (Long mid : deletedBoxes) { releaseMailbox(mid); } } } } class MailboxObserver extends ContentObserver { public MailboxObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { // See if there's anything to do... if (!selfChange) { kick("mailbox changed"); } } } class SyncedMessageObserver extends ContentObserver { Intent syncAlarmIntent = new Intent(INSTANCE, EmailSyncAlarmReceiver.class); PendingIntent syncAlarmPendingIntent = PendingIntent.getBroadcast(INSTANCE, 0, syncAlarmIntent, 0); AlarmManager alarmManager = (AlarmManager)INSTANCE.getSystemService(Context.ALARM_SERVICE); public SyncedMessageObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { INSTANCE.log("SyncedMessage changed: (re)setting alarm for 10s"); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10*SECONDS, syncAlarmPendingIntent); } } class MessageObserver extends ContentObserver { public MessageObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { // A rather blunt instrument here. But we don't have information about the URI that // triggered this, though it must have been an insert if (!selfChange) { kick(null); } } } static public IEmailServiceCallback callback() { return sCallbackProxy; } static public AccountList getAccountList() { if (INSTANCE != null) { return INSTANCE.mAccountObserver.mAccounts; } else { return EMPTY_ACCOUNT_LIST; } } static public String getEasAccountSelector() { if (INSTANCE != null) { return INSTANCE.mAccountObserver.getAccountKeyWhere(); } else { return null; } } private Account getAccountById(long accountId) { return mAccountObserver.mAccounts.getById(accountId); } public class SyncStatus { static public final int NOT_RUNNING = 0; static public final int DIED = 1; static public final int SYNC = 2; static public final int IDLE = 3; } class SyncError { int reason; boolean fatal = false; long holdDelay = 15*SECONDS; long holdEndTime = System.currentTimeMillis() + holdDelay; SyncError(int _reason, boolean _fatal) { reason = _reason; fatal = _fatal; } /** * We double the holdDelay from 15 seconds through 4 mins */ void escalate() { if (holdDelay < HOLD_DELAY_MAXIMUM) { holdDelay *= 2; } holdEndTime = System.currentTimeMillis() + holdDelay; } } public class EasSyncStatusObserver implements SyncStatusObserver { public void onStatusChanged(int which) { // We ignore the argument (we can only get called in one case - when settings change) // TODO Go through each account and see if sync is enabled and/or automatic for // the Contacts authority, and set syncInterval accordingly. Then kick ourselves. if (INSTANCE != null) { checkPIMSyncSettings(); } } } public class EasAccountsUpdatedListener implements OnAccountsUpdatedListener { public void onAccountsUpdated(android.accounts.Account[] accounts) { checkWithAccountManager(); } } static public void smLog(String str) { if (INSTANCE != null) { INSTANCE.log(str); } } protected void log(String str) { if (Eas.USER_LOG) { Log.d(TAG, str); if (Eas.FILE_LOG) { FileLogger.log(TAG, str); } } } protected void alwaysLog(String str) { if (!Eas.USER_LOG) { Log.d(TAG, str); } else { log(str); } } /** * EAS requires a unique device id, so that sync is possible from a variety of different * devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other * device that doesn't provide one, we can create it as droid<n> where <n> is system time. * This would work on a real device as well, but it would be better to use the "real" id if * it's available */ static public String getDeviceId() throws IOException { return getDeviceId(null); } static public synchronized String getDeviceId(Context context) throws IOException { if (sDeviceId != null) { return sDeviceId; } else if (INSTANCE == null && context == null) { throw new IOException("No context for getDeviceId"); } else if (context == null) { context = INSTANCE; } // Otherwise, we'll read the id file or create one if it's not found try { File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists() && f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); return id; } else if (f.createNewFile()) { BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); id = "droid" + System.currentTimeMillis(); w.write(id); w.close(); sDeviceId = id; return id; } } catch (IOException e) { } throw new IOException("Can't get device name"); } @Override public IBinder onBind(Intent arg0) { return mBinder; } /** * Note that there are two ways the EAS SyncManager service can be created: * * 1) as a background service instantiated via startService (which happens on boot, when the * first EAS account is created, etc), in which case the service thread is spun up, mailboxes * sync, etc. and * 2) to execute an RPC call from the UI, in which case the background service will already be * running most of the time (unless we're creating a first EAS account) * * If the running background service detects that there are no EAS accounts (on boot, if none * were created, or afterward if the last remaining EAS account is deleted), it will call * stopSelf() to terminate operation. * * The goal is to ensure that the background service is running at all times when there is at * least one EAS account in existence * * Because there are edge cases in which our process can crash (typically, this has been seen * in UI crashes, ANR's, etc.), it's possible for the UI to start up again without the * background service having been started. We explicitly try to start the service in Welcome * (to handle the case of the app having been reloaded). We also start the service on any * startSync call (if it isn't already running) */ @Override public void onCreate() { alwaysLog("!!! EAS SyncManager, onCreate"); if (INSTANCE == null) { INSTANCE = this; mResolver = getContentResolver(); mAccountObserver = new AccountObserver(mHandler); mResolver.registerContentObserver(Account.CONTENT_URI, true, mAccountObserver); mMailboxObserver = new MailboxObserver(mHandler); mSyncedMessageObserver = new SyncedMessageObserver(mHandler); mMessageObserver = new MessageObserver(mHandler); mSyncStatusObserver = new EasSyncStatusObserver(); } else { alwaysLog("!!! EAS SyncManager onCreated, but INSTANCE not null??"); } if (sDeviceId == null) { try { getDeviceId(this); } catch (IOException e) { // We can't run in this situation throw new RuntimeException(); } } } @Override public int onStartCommand(Intent intent, int flags, int startId) { alwaysLog("!!! EAS SyncManager, onStartCommand"); maybeStartSyncManagerThread(); if (sServiceThread == null) { alwaysLog("!!! EAS SyncManager, stopping self"); stopSelf(); } return Service.START_STICKY; } @Override public void onDestroy() { alwaysLog("!!! EAS SyncManager, onDestroy"); if (INSTANCE != null) { INSTANCE = null; mResolver.unregisterContentObserver(mAccountObserver); mResolver = null; mAccountObserver = null; mMailboxObserver = null; mSyncedMessageObserver = null; mMessageObserver = null; mSyncStatusObserver = null; } } void maybeStartSyncManagerThread() { // Start our thread... // See if there are any EAS accounts; otherwise, just go away if (EmailContent.count(this, HostAuth.CONTENT_URI, WHERE_PROTOCOL_EAS, null) > 0) { if (sServiceThread == null || !sServiceThread.isAlive()) { log(sServiceThread == null ? "Starting thread..." : "Restarting thread..."); sServiceThread = new Thread(this, "SyncManager"); sServiceThread.start(); } } } static void checkSyncManagerServiceRunning() { // Get the service thread running if it isn't // This is a stopgap for cases in which SyncManager died (due to a crash somewhere in // com.android.email) and hasn't been restarted // See the comment for onCreate for details if (INSTANCE == null) return; if (sServiceThread == null) { INSTANCE.alwaysLog("!!! checkSyncManagerServiceRunning; starting service..."); INSTANCE.startService(new Intent(INSTANCE, SyncManager.class)); } } static public ConnPerRoute sConnPerRoute = new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return 8; } }; static public synchronized ClientConnectionManager getClientConnectionManager() { if (sClientConnectionManager == null) { // Create a registry for our three schemes; http and https will use built-in factories SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Create a new SSLSocketFactory for our "trusted ssl" // Get the unsecure trust manager from the factory X509TrustManager trustManager = TrustManagerFactory.get(null, false); TrustManager[] trustManagers = new TrustManager[] {trustManager}; SSLContext sslcontext; try { sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, trustManagers, null); SSLContextImpl sslContext = new SSLContextImpl(); try { sslContext.engineInit(null, trustManagers, null, null, null); } catch (KeyManagementException e) { throw new AssertionError(e); } // Ok, now make our factory SSLSocketFactory sf = new SSLSocketFactory(sslContext.engineGetSocketFactory()); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Register the httpts scheme with our factory registry.register(new Scheme("httpts", sf, 443)); // And create a ccm with our registry HttpParams params = new BasicHttpParams(); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute); sClientConnectionManager = new ThreadSafeClientConnManager(params, registry); } catch (NoSuchAlgorithmException e2) { } catch (KeyManagementException e1) { } } // Null is a valid return result if we get an exception return sClientConnectionManager; } static public void reloadFolderList(Context context, long accountId, boolean force) { if (INSTANCE == null) return; Cursor c = context.getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + "=? AND " + MailboxColumns.TYPE + "=?", new String[] {Long.toString(accountId), Long.toString(Mailbox.TYPE_EAS_ACCOUNT_MAILBOX)}, null); try { if (c.moveToFirst()) { synchronized(sSyncToken) { Mailbox m = new Mailbox().restore(c); Account acct = Account.restoreAccountWithId(context, accountId); if (acct == null) { return; } String syncKey = acct.mSyncKey; // No need to reload the list if we don't have one if (!force && (syncKey == null || syncKey.equals("0"))) { return; } // Change all ping/push boxes to push/hold ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH_HOLD); context.getContentResolver().update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX, new String[] {Long.toString(accountId)}); INSTANCE.log("Set push/ping boxes to push/hold"); long id = m.mId; AbstractSyncService svc = INSTANCE.mServiceMap.get(id); // Tell the service we're done if (svc != null) { synchronized (svc.getSynchronizer()) { svc.stop(); } // Interrupt the thread so that it can stop Thread thread = svc.mThread; thread.setName(thread.getName() + " (Stopped)"); thread.interrupt(); // Abandon the service INSTANCE.releaseMailbox(id); // And have it start naturally kick("reload folder list"); } } } } finally { c.close(); } } /** * Informs SyncManager that an account has a new folder list; as a result, any existing folder * might have become invalid. Therefore, we act as if the account has been deleted, and then * we reinitialize it. * * @param acctId */ static public void folderListReloaded(long acctId) { if (INSTANCE != null) { AccountObserver obs = INSTANCE.mAccountObserver; obs.stopAccountSyncs(acctId, false); kick("reload folder list"); } } // private void logLocks(String str) { // StringBuilder sb = new StringBuilder(str); // boolean first = true; // for (long id: mWakeLocks.keySet()) { // if (!first) { // sb.append(", "); // } else { // first = false; // } // sb.append(id); // } // log(sb.toString()); // } private void acquireWakeLock(long id) { synchronized (mWakeLocks) { Boolean lock = mWakeLocks.get(id); if (lock == null) { if (id > 0) { //log("+WakeLock requested for " + alarmOwner(id)); } if (mWakeLock == null) { PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE"); mWakeLock.acquire(); log("+WAKE LOCK ACQUIRED"); } mWakeLocks.put(id, true); //logLocks("Post-acquire of WakeLock for " + alarmOwner(id) + ": "); } } } private void releaseWakeLock(long id) { synchronized (mWakeLocks) { Boolean lock = mWakeLocks.get(id); if (lock != null) { if (id > 0) { //log("+WakeLock not needed for " + alarmOwner(id)); } mWakeLocks.remove(id); if (mWakeLocks.isEmpty()) { if (mWakeLock != null) { mWakeLock.release(); } mWakeLock = null; log("+WAKE LOCK RELEASED"); } else { //logLocks("Post-release of WakeLock for " + alarmOwner(id) + ": "); } } } } static public String alarmOwner(long id) { if (id == SYNC_MANAGER_ID) { return "SyncManager"; } else return "Mailbox " + Long.toString(id); } private void clearAlarm(long id) { synchronized (mPendingIntents) { PendingIntent pi = mPendingIntents.get(id); if (pi != null) { AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pi); //log("+Alarm cleared for " + alarmOwner(id)); mPendingIntents.remove(id); } } } private void setAlarm(long id, long millis) { synchronized (mPendingIntents) { PendingIntent pi = mPendingIntents.get(id); if (pi == null) { Intent i = new Intent(this, MailboxAlarmReceiver.class); i.putExtra("mailbox", id); i.setData(Uri.parse("Box" + id)); pi = PendingIntent.getBroadcast(this, 0, i, 0); mPendingIntents.put(id, pi); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pi); //log("+Alarm set for " + alarmOwner(id) + ", " + millis/1000 + "s"); } } } private void clearAlarms() { AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); synchronized (mPendingIntents) { for (PendingIntent pi : mPendingIntents.values()) { alarmManager.cancel(pi); } mPendingIntents.clear(); } } static public void runAwake(long id) { if (INSTANCE == null) return; INSTANCE.acquireWakeLock(id); INSTANCE.clearAlarm(id); } static public void runAsleep(long id, long millis) { if (INSTANCE == null) return; INSTANCE.setAlarm(id, millis); INSTANCE.releaseWakeLock(id); } static public void ping(Context context, long id) { checkSyncManagerServiceRunning(); if (id < 0) { kick("ping SyncManager"); } else if (INSTANCE == null) { context.startService(new Intent(context, SyncManager.class)); } else { AbstractSyncService service = INSTANCE.mServiceMap.get(id); if (service != null) { Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id); if (m != null) { service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey); service.mMailbox = m; service.ping(); } } } } /** * See if we need to change the syncInterval for any of our PIM mailboxes based on changes * to settings in the AccountManager (sync settings). * This code is called 1) when SyncManager starts, and 2) when SyncManager is running and there * are changes made (this is detected via a SyncStatusObserver) */ private void checkPIMSyncSettings() { ContentValues cv = new ContentValues(); // For now, just Contacts // First, walk through our list of accounts List<Account> easAccounts = getAccountList(); for (Account easAccount: easAccounts) { // Find the contacts mailbox long contactsId = Mailbox.findMailboxOfType(this, easAccount.mId, Mailbox.TYPE_CONTACTS); // Presumably there is one, but if not, it's ok. Just move on... if (contactsId != Mailbox.NO_MAILBOX) { // Create an AccountManager style Account android.accounts.Account acct = new android.accounts.Account(easAccount.mEmailAddress, Eas.ACCOUNT_MANAGER_TYPE); // Get the Contacts mailbox; this happens rarely so it's ok to get it all Mailbox contacts = Mailbox.restoreMailboxWithId(this, contactsId); int syncInterval = contacts.mSyncInterval; // If we're syncable, look further... if (ContentResolver.getIsSyncable(acct, ContactsContract.AUTHORITY) > 0) { // If we're supposed to sync automatically (push), set to push if it's not if (ContentResolver.getSyncAutomatically(acct, ContactsContract.AUTHORITY)) { if (syncInterval == Mailbox.CHECK_INTERVAL_NEVER || syncInterval > 0) { log("Sync setting: Contacts for " + acct.name + " changed to push"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); } // If we're NOT supposed to push, and we're not set up that way, change it } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) { log("Sync setting: Contacts for " + acct.name + " changed to manual"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER); } // If not, set it to never check } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) { log("Sync setting: Contacts for " + acct.name + " changed to manual"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER); } // If we've made a change, update the Mailbox, and kick if (cv.containsKey(MailboxColumns.SYNC_INTERVAL)) { mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, contactsId), cv,null, null); kick("sync settings change"); } } } } private void checkWithAccountManager() { android.accounts.Account[] accts = AccountManager.get(this).getAccountsByType(Eas.ACCOUNT_MANAGER_TYPE); List<Account> easAccounts = getAccountList(); for (Account easAccount: easAccounts) { String accountName = easAccount.mEmailAddress; boolean found = false; for (android.accounts.Account acct: accts) { if (acct.name.equalsIgnoreCase(accountName)) { found = true; break; } } if (!found) { // This account has been deleted in the AccountManager! log("Account deleted in AccountManager; deleting from provider: " + accountName); // TODO This will orphan downloaded attachments; need to handle this mResolver.delete(ContentUris.withAppendedId(Account.CONTENT_URI, easAccount.mId), null, null); } } } private void releaseConnectivityLock(String reason) { // Clear our sync error map when we get connected mSyncErrorMap.clear(); synchronized (sConnectivityLock) { sConnectivityLock.notifyAll(); } kick(reason); } public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); if (b != null) { NetworkInfo a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_NETWORK_INFO); String info = "Connectivity alert for " + a.getTypeName(); State state = a.getState(); if (state == State.CONNECTED) { info += " CONNECTED"; log(info); releaseConnectivityLock("connected"); } else if (state == State.DISCONNECTED) { info += " DISCONNECTED"; a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); if (a != null && a.getState() == State.CONNECTED) { info += " (OTHER CONNECTED)"; releaseConnectivityLock("disconnect/other"); ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo i = cm.getActiveNetworkInfo(); if (i == null || i.getState() != State.CONNECTED) { log("CM says we're connected, but no active info?"); } } } else { log(info); kick("disconnected"); } } } } } private void startService(AbstractSyncService service, Mailbox m) { synchronized (sSyncToken) { String mailboxName = m.mDisplayName; String accountName = service.mAccount.mDisplayName; Thread thread = new Thread(service, mailboxName + "(" + accountName + ")"); log("Starting thread for " + mailboxName + " in account " + accountName); thread.start(); mServiceMap.put(m.mId, service); runAwake(m.mId); } } private void startService(Mailbox m, int reason, PartRequest req) { // Don't sync if there's no connectivity if (sConnectivityHold) return; synchronized (sSyncToken) { Account acct = Account.restoreAccountWithId(this, m.mAccountKey); if (acct != null) { AbstractSyncService service; service = new EasSyncService(this, m); service.mSyncReason = reason; if (req != null) { service.addPartRequest(req); } startService(service, m); } } } private void stopServices() { synchronized (sSyncToken) { ArrayList<Long> toStop = new ArrayList<Long>(); // Keep track of which services to stop for (Long mailboxId : mServiceMap.keySet()) { toStop.add(mailboxId); } // Shut down all of those running services for (Long mailboxId : toStop) { AbstractSyncService svc = mServiceMap.get(mailboxId); if (svc != null) { log("Stopping " + svc.mAccount.mDisplayName + '/' + svc.mMailbox.mDisplayName); svc.stop(); if (svc.mThread != null) { svc.mThread.interrupt(); } } releaseWakeLock(mailboxId); } } } private void waitForConnectivity() { int cnt = 0; while (!mStop) { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null) { //log("NetworkInfo: " + info.getTypeName() + ", " + info.getState().name()); return; } else { // If we're waiting for the long haul, shut down running service threads if (++cnt > 1) { stopServices(); } // Wait until a network is connected, but let the device sleep // We'll set an alarm just in case we don't get notified (bugs happen) synchronized (sConnectivityLock) { runAsleep(SYNC_MANAGER_ID, CONNECTIVITY_WAIT_TIME+5*SECONDS); try { log("Connectivity lock..."); sConnectivityHold = true; sConnectivityLock.wait(CONNECTIVITY_WAIT_TIME); log("Connectivity lock released..."); } catch (InterruptedException e) { } finally { sConnectivityHold = false; } runAwake(SYNC_MANAGER_ID); } } } } public void run() { mStop = false; // If we're really debugging, turn on all logging if (Eas.DEBUG) { Eas.USER_LOG = true; Eas.PARSER_LOG = true; Eas.FILE_LOG = true; } // If we need to wait for the debugger, do so if (Eas.WAIT_DEBUG) { Debug.waitForDebugger(); } // Set up our observers; we need them to know when to start/stop various syncs based // on the insert/delete/update of mailboxes and accounts // We also observe synced messages to trigger upsyncs at the appropriate time mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver); mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver); mResolver.registerContentObserver(Message.CONTENT_URI, true, mMessageObserver); ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); mAccountsUpdatedListener = new EasAccountsUpdatedListener(); AccountManager.get(getApplication()) .addOnAccountsUpdatedListener(mAccountsUpdatedListener, mHandler, true); mConnectivityReceiver = new ConnectivityReceiver(); registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); // See if any settings have changed while we weren't running... checkPIMSyncSettings(); try { while (!mStop) { runAwake(SYNC_MANAGER_ID); waitForConnectivity(); mNextWaitReason = "Heartbeat"; long nextWait = checkMailboxes(); try { synchronized (this) { if (!mKicked) { if (nextWait < 0) { log("Negative wait? Setting to 1s"); nextWait = 1*SECONDS; } if (nextWait > 30*SECONDS) { runAsleep(SYNC_MANAGER_ID, nextWait - 1000); } if (nextWait != SYNC_MANAGER_HEARTBEAT_TIME) { log("Next awake in " + nextWait / 1000 + "s: " + mNextWaitReason); } wait(nextWait); } } } catch (InterruptedException e) { // Needs to be caught, but causes no problem } finally { synchronized (this) { if (mKicked) { //log("Wait deferred due to kick"); mKicked = false; } } } } stopServices(); log("Shutdown requested"); } finally { // Lots of cleanup here // Stop our running syncs stopServices(); // Stop receivers and content observers if (mConnectivityReceiver != null) { unregisterReceiver(mConnectivityReceiver); } ContentResolver resolver = getContentResolver(); resolver.unregisterContentObserver(mAccountObserver); resolver.unregisterContentObserver(mMailboxObserver); resolver.unregisterContentObserver(mSyncedMessageObserver); resolver.unregisterContentObserver(mMessageObserver); // Don't leak the Intent associated with this listener if (mAccountsUpdatedListener != null) { AccountManager.get(this).removeOnAccountsUpdatedListener(mAccountsUpdatedListener); mAccountsUpdatedListener = null; } // Clear pending alarms and associated Intents clearAlarms(); // Release our wake lock, if we have one synchronized (mWakeLocks) { if (mWakeLock != null) { mWakeLock.release(); mWakeLock = null; } } log("Goodbye"); } if (!mStop) { // If this wasn't intentional, try to restart the service throw new RuntimeException("EAS SyncManager crash; please restart me..."); } } private void releaseMailbox(long mailboxId) { mServiceMap.remove(mailboxId); releaseWakeLock(mailboxId); } private long checkMailboxes () { // First, see if any running mailboxes have been deleted ArrayList<Long> deletedMailboxes = new ArrayList<Long>(); synchronized (sSyncToken) { for (long mailboxId: mServiceMap.keySet()) { Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId); if (m == null) { deletedMailboxes.add(mailboxId); } } } // If so, stop them or remove them from the map for (Long mailboxId: deletedMailboxes) { AbstractSyncService svc = mServiceMap.get(mailboxId); if (svc != null) { boolean alive = svc.mThread.isAlive(); log("Deleted mailbox: " + svc.mMailboxName); if (alive) { stopManualSync(mailboxId); } else { log("Removing from serviceMap"); releaseMailbox(mailboxId); } } } long nextWait = SYNC_MANAGER_HEARTBEAT_TIME; long now = System.currentTimeMillis(); // Start up threads that need it; use a query which finds eas mailboxes where the // the sync interval is not "never". This is the set of mailboxes that we control Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, mAccountObserver.getSyncableEasMailboxWhere(), null, null); try { while (c.moveToNext()) { long mid = c.getLong(Mailbox.CONTENT_ID_COLUMN); AbstractSyncService service = mServiceMap.get(mid); if (service == null) { // Check whether we're in a hold (temporary or permanent) SyncError syncError = mSyncErrorMap.get(mid); if (syncError != null) { // Nothing we can do about fatal errors if (syncError.fatal) continue; if (now < syncError.holdEndTime) { // If release time is earlier than next wait time, // move next wait time up to the release time if (syncError.holdEndTime < now + nextWait) { nextWait = syncError.holdEndTime - now; mNextWaitReason = "Release hold"; } continue; } else { // Keep the error around, but clear the end time syncError.holdEndTime = 0; } } // We handle a few types of mailboxes specially int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); if (type == Mailbox.TYPE_CONTACTS) { // See if "sync automatically" is set Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN)); if (account != null) { android.accounts.Account a = new android.accounts.Account(account.mEmailAddress, Eas.ACCOUNT_MANAGER_TYPE); if (!ContentResolver.getSyncAutomatically(a, ContactsContract.AUTHORITY)) { continue; } } } else if (type == Mailbox.TYPE_TRASH) { continue; } // Otherwise, we use the sync interval long interval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN); if (interval == Mailbox.CHECK_INTERVAL_PUSH) { Mailbox m = EmailContent.getContent(c, Mailbox.class); startService(m, SYNC_PUSH, null); } else if (type == Mailbox.TYPE_OUTBOX) { int cnt = EmailContent.count(this, Message.CONTENT_URI, EasOutboxService.MAILBOX_KEY_AND_NOT_SEND_FAILED, new String[] {Long.toString(mid)}); if (cnt > 0) { Mailbox m = EmailContent.getContent(c, Mailbox.class); startService(new EasOutboxService(this, m), m); } } else if (interval > 0 && interval <= ONE_DAY_MINUTES) { long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN); long toNextSync = interval*MINUTES - (now - lastSync); if (toNextSync <= 0) { Mailbox m = EmailContent.getContent(c, Mailbox.class); startService(m, SYNC_SCHEDULED, null); } else if (toNextSync < nextWait) { nextWait = toNextSync; mNextWaitReason = "Scheduled sync, " + c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); } } } else { Thread thread = service.mThread; // Look for threads that have died but aren't in an error state if (thread != null && !thread.isAlive() && !mSyncErrorMap.containsKey(mid)) { releaseMailbox(mid); // Restart this if necessary if (nextWait > 3*SECONDS) { nextWait = 3*SECONDS; mNextWaitReason = "Clean up dead thread(s)"; } } else { long requestTime = service.mRequestTime; if (requestTime > 0) { long timeToRequest = requestTime - now; if (service instanceof AbstractSyncService && timeToRequest <= 0) { service.mRequestTime = 0; service.ping(); } else if (requestTime > 0 && timeToRequest < nextWait) { if (timeToRequest < 11*MINUTES) { nextWait = timeToRequest < 250 ? 250 : timeToRequest; mNextWaitReason = "Sync data change"; } else { log("Illegal timeToRequest: " + timeToRequest); } } } } } } } finally { c.close(); } return nextWait; } static public void serviceRequest(long mailboxId, int reason) { serviceRequest(mailboxId, 5*SECONDS, reason); } static public void serviceRequest(long mailboxId, long ms, int reason) { if (INSTANCE == null) return; try { AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { service.mRequestTime = System.currentTimeMillis() + ms; kick("service request"); } else { startManualSync(mailboxId, reason, null); } } catch (Exception e) { e.printStackTrace(); } } static public void serviceRequestImmediate(long mailboxId) { if (INSTANCE == null) return; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { service.mRequestTime = System.currentTimeMillis(); Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); if (m != null) { service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey); service.mMailbox = m; kick("service request immediate"); } } } static public void partRequest(PartRequest req) { if (INSTANCE == null) return; Message msg = Message.restoreMessageWithId(INSTANCE, req.emailId); if (msg == null) { return; } long mailboxId = msg.mMailboxKey; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service == null) { service = startManualSync(mailboxId, SYNC_SERVICE_PART_REQUEST, req); kick("part request"); } else { service.addPartRequest(req); } } static public PartRequest hasPartRequest(long emailId, String part) { if (INSTANCE == null) return null; Message msg = Message.restoreMessageWithId(INSTANCE, emailId); if (msg == null) { return null; } long mailboxId = msg.mMailboxKey; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { return service.hasPartRequest(emailId, part); } return null; } static public void cancelPartRequest(long emailId, String part) { Message msg = Message.restoreMessageWithId(INSTANCE, emailId); if (msg == null) { return; } long mailboxId = msg.mMailboxKey; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { service.cancelPartRequest(emailId, part); } } /** * Determine whether a given Mailbox can be synced, i.e. is not already syncing and is not in * an error state * * @param mailboxId * @return whether or not the Mailbox is available for syncing (i.e. is a valid push target) */ static public int pingStatus(long mailboxId) { // Already syncing... if (INSTANCE.mServiceMap.get(mailboxId) != null) { return PING_STATUS_RUNNING; } // No errors or a transient error, don't ping... SyncError error = INSTANCE.mSyncErrorMap.get(mailboxId); if (error != null) { if (error.fatal) { return PING_STATUS_UNABLE; } else { return PING_STATUS_WAITING; } } return PING_STATUS_OK; } static public AbstractSyncService startManualSync(long mailboxId, int reason, PartRequest req) { if (INSTANCE == null || INSTANCE.mServiceMap == null) return null; synchronized (sSyncToken) { if (INSTANCE.mServiceMap.get(mailboxId) == null) { INSTANCE.mSyncErrorMap.remove(mailboxId); Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); if (m != null) { INSTANCE.log("Starting sync for " + m.mDisplayName); INSTANCE.startService(m, reason, req); } } } return INSTANCE.mServiceMap.get(mailboxId); } // DO NOT CALL THIS IN A LOOP ON THE SERVICEMAP static private void stopManualSync(long mailboxId) { if (INSTANCE == null || INSTANCE.mServiceMap == null) return; synchronized (sSyncToken) { AbstractSyncService svc = INSTANCE.mServiceMap.get(mailboxId); if (svc != null) { INSTANCE.log("Stopping sync for " + svc.mMailboxName); svc.stop(); svc.mThread.interrupt(); INSTANCE.releaseWakeLock(mailboxId); } } } /** * Wake up SyncManager to check for mailboxes needing service */ static public void kick(String reason) { if (INSTANCE != null) { synchronized (INSTANCE) { INSTANCE.mKicked = true; INSTANCE.notify(); } } if (sConnectivityLock != null) { synchronized (sConnectivityLock) { sConnectivityLock.notify(); } } } static public void accountUpdated(long acctId) { if (INSTANCE == null) return; synchronized (sSyncToken) { for (AbstractSyncService svc : INSTANCE.mServiceMap.values()) { if (svc.mAccount.mId == acctId) { svc.mAccount = Account.restoreAccountWithId(INSTANCE, acctId); } } } } /** * Sent by services indicating that their thread is finished; action depends on the exitStatus * of the service. * * @param svc the service that is finished */ static public void done(AbstractSyncService svc) { if (INSTANCE == null) return; synchronized(sSyncToken) { long mailboxId = svc.mMailboxId; HashMap<Long, SyncError> errorMap = INSTANCE.mSyncErrorMap; SyncError syncError = errorMap.get(mailboxId); INSTANCE.releaseMailbox(mailboxId); int exitStatus = svc.mExitStatus; switch (exitStatus) { case AbstractSyncService.EXIT_DONE: if (!svc.mPartRequests.isEmpty()) { // TODO Handle this case } errorMap.remove(mailboxId); break; case AbstractSyncService.EXIT_IO_ERROR: if (syncError != null) { syncError.escalate(); INSTANCE.log("Mailbox " + mailboxId + " now held for " + syncError.holdDelay + "s"); } else { errorMap.put(mailboxId, INSTANCE.new SyncError(exitStatus, false)); INSTANCE.log("Mailbox " + mailboxId + " added to syncErrorMap"); } break; case AbstractSyncService.EXIT_LOGIN_FAILURE: case AbstractSyncService.EXIT_EXCEPTION: errorMap.put(mailboxId, INSTANCE.new SyncError(exitStatus, true)); break; } kick("sync completed"); } } /** * Given the status string from a Mailbox, return the type code for the last sync * @param status the syncStatus column of a Mailbox * @return */ static public int getStatusType(String status) { if (status == null) { return -1; } else { return status.charAt(STATUS_TYPE_CHAR) - '0'; } } /** * Given the status string from a Mailbox, return the change count for the last sync * The change count is the number of adds + deletes + changes in the last sync * @param status the syncStatus column of a Mailbox * @return */ static public int getStatusChangeCount(String status) { try { String s = status.substring(STATUS_CHANGE_COUNT_OFFSET); return Integer.parseInt(s); } catch (RuntimeException e) { return -1; } } static public Context getContext() { return INSTANCE; } }
true
false
null
null
diff --git a/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedIconOverlay.java b/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedIconOverlay.java index dd0a61f..eb94014 100644 --- a/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedIconOverlay.java +++ b/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedIconOverlay.java @@ -1,198 +1,215 @@ package org.osmdroid.views.overlay; import java.util.List; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.ResourceProxy; import org.osmdroid.ResourceProxy.bitmap; import org.osmdroid.views.MapView; import org.osmdroid.views.MapView.Projection; import android.content.Context; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.view.MotionEvent; public class ItemizedIconOverlay<Item extends OverlayItem> extends ItemizedOverlay<Item> { protected final List<Item> mItemList; protected OnItemGestureListener<Item> mOnItemGestureListener; private int mDrawnItemsLimit = Integer.MAX_VALUE; private final Point mTouchScreenPoint = new Point(); private final Point mItemPoint = new Point(); public ItemizedIconOverlay( List<Item> pList, Drawable pDefaultMarker, org.osmdroid.views.overlay.ItemizedIconOverlay.OnItemGestureListener<Item> pOnItemGestureListener, ResourceProxy pResourceProxy) { super(pDefaultMarker, pResourceProxy); this.mItemList = pList; this.mOnItemGestureListener = pOnItemGestureListener; populate(); } public ItemizedIconOverlay( List<Item> pList, org.osmdroid.views.overlay.ItemizedIconOverlay.OnItemGestureListener<Item> pOnItemGestureListener, ResourceProxy pResourceProxy) { this(pList, pResourceProxy.getDrawable(bitmap.marker_default), pOnItemGestureListener, pResourceProxy); } public ItemizedIconOverlay( Context pContext, List<Item> pList, org.osmdroid.views.overlay.ItemizedIconOverlay.OnItemGestureListener<Item> pOnItemGestureListener) { this(pList, new DefaultResourceProxyImpl(pContext).getDrawable(bitmap.marker_default), pOnItemGestureListener, new DefaultResourceProxyImpl(pContext)); } @Override public boolean onSnapToItem(int pX, int pY, Point pSnapPoint, MapView pMapView) { // TODO Implement this! return false; } @Override protected Item createItem(int index) { return mItemList.get(index); } @Override public int size() { return Math.min(mItemList.size(), mDrawnItemsLimit); } public boolean addItem(Item item) { boolean result = mItemList.add(item); populate(); return result; } public void addItem(int location, Item item) { mItemList.add(location, item); } + public boolean addItems(List<Item> items) { + boolean result = mItemList.addAll(items); + populate(); + return result; + } + + public void removeAllItems() { + removeAllItems(true); + } + + public void removeAllItems(boolean withPopulate) { + mItemList.clear(); + if (withPopulate) { + populate(); + } + } + public boolean removeItem(Item item) { boolean result = mItemList.remove(item); populate(); return result; } public Item removeItem(int position) { Item result = mItemList.remove(position); populate(); return result; } /** * Each of these methods performs a item sensitive check. If the item is located its * corresponding method is called. The result of the call is returned. * * Helper methods are provided so that child classes may more easily override behavior without * resorting to overriding the ItemGestureListener methods. */ @Override public boolean onSingleTapUp(final MotionEvent event, final MapView mapView) { return (activateSelectedItems(event, mapView, new ActiveItem() { @Override public boolean run(final int index) { final ItemizedIconOverlay<Item> that = ItemizedIconOverlay.this; if (that.mOnItemGestureListener == null) { return false; } return onSingleTapUpHelper(index, that.mItemList.get(index), mapView); } })) ? true : super.onSingleTapUp(event, mapView); } protected boolean onSingleTapUpHelper(final int index, final Item item, final MapView mapView) { return this.mOnItemGestureListener.onItemSingleTapUp(index, item); } @Override public boolean onLongPress(final MotionEvent event, final MapView mapView) { return (activateSelectedItems(event, mapView, new ActiveItem() { @Override public boolean run(final int index) { final ItemizedIconOverlay<Item> that = ItemizedIconOverlay.this; if (that.mOnItemGestureListener == null) { return false; } return onLongPressHelper(index, getItem(index)); } })) ? true : super.onLongPress(event, mapView); } protected boolean onLongPressHelper(final int index, final Item item) { return this.mOnItemGestureListener.onItemLongPress(index, item); } /** * When a content sensitive action is performed the content item needs to be identified. This * method does that and then performs the assigned task on that item. * * @param event * @param mapView * @param task * @return true if event is handled false otherwise */ private boolean activateSelectedItems(final MotionEvent event, final MapView mapView, final ActiveItem task) { final Projection pj = mapView.getProjection(); final int eventX = (int) event.getX(); final int eventY = (int) event.getY(); /* These objects are created to avoid construct new ones every cycle. */ pj.fromMapPixels(eventX, eventY, mTouchScreenPoint); for (int i = 0; i < this.mItemList.size(); ++i) { final Item item = getItem(i); final Drawable marker = (item.getMarker(0) == null) ? this.mDefaultMarker : item .getMarker(0); pj.toPixels(item.getPoint(), mItemPoint); if (hitTest(item, marker, mTouchScreenPoint.x - mItemPoint.x, mTouchScreenPoint.y - mItemPoint.y)) { if (task.run(i)) { return true; } } } return false; } // =========================================================== // Getter & Setter // =========================================================== public int getDrawnItemsLimit() { return this.mDrawnItemsLimit; } public void setDrawnItemsLimit(final int aLimit) { this.mDrawnItemsLimit = aLimit; } // =========================================================== // Inner and Anonymous Classes // =========================================================== /** * When the item is touched one of these methods may be invoked depending on the type of touch. * * Each of them returns true if the event was completely handled. */ public static interface OnItemGestureListener<T> { public boolean onItemSingleTapUp(final int index, final T item); public boolean onItemLongPress(final int index, final T item); } public static interface ActiveItem { public boolean run(final int aIndex); } }
true
false
null
null
diff --git a/src/java/org/jdesktop/swingx/DefaultDateSelectionModel.java b/src/java/org/jdesktop/swingx/DefaultDateSelectionModel.java index a60af5e3..f9013f59 100644 --- a/src/java/org/jdesktop/swingx/DefaultDateSelectionModel.java +++ b/src/java/org/jdesktop/swingx/DefaultDateSelectionModel.java @@ -1,299 +1,300 @@ /** * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.ArrayList; import org.jdesktop.swingx.event.DateSelectionEvent; import static org.jdesktop.swingx.event.DateSelectionEvent.EventType; import org.jdesktop.swingx.event.EventListenerMap; /** * @author Joshua Outwater */ public class DefaultDateSelectionModel implements DateSelectionModel { private EventListenerMap listenerMap; private SelectionMode selectionMode; private SortedSet<Date> selectedDates; private SortedSet<Date> unselectableDates; private Calendar cal; private int firstDayOfWeek; private Date upperBound; private Date lowerBound; public DefaultDateSelectionModel() { this.listenerMap = new EventListenerMap(); this.selectionMode = SelectionMode.SINGLE_SELECTION; this.selectedDates = new TreeSet<Date>(); + this.unselectableDates = new TreeSet<Date>(); this.firstDayOfWeek = Calendar.SUNDAY; cal = Calendar.getInstance(); } /** * {@inheritDoc} */ public SelectionMode getSelectionMode() { return selectionMode; } /** * {@inheritDoc} */ public void setSelectionMode(final SelectionMode selectionMode) { this.selectionMode = selectionMode; clearSelection(); } public int getFirstDayOfWeek() { return firstDayOfWeek; } public void setFirstDayOfWeek(final int firstDayOfWeek) { this.firstDayOfWeek = firstDayOfWeek; } /** * {@inheritDoc} */ public void addSelectionInterval(Date startDate, Date endDate) { if (startDate.after(endDate)) { return; } switch (selectionMode) { case SINGLE_SELECTION: clearSelectionImpl(); selectedDates.add(startDate); break; case SINGLE_INTERVAL_SELECTION: clearSelectionImpl(); addSelectionImpl(startDate, endDate); break; case MULTIPLE_INTERVAL_SELECTION: addSelectionImpl(startDate, endDate); break; default: break; } fireValueChanged(EventType.DATES_ADDED); } /** * {@inheritDoc} */ public void setSelectionInterval(final Date startDate, final Date endDate) { switch (selectionMode) { case SINGLE_SELECTION: clearSelectionImpl(); selectedDates.add(startDate); break; case SINGLE_INTERVAL_SELECTION: clearSelectionImpl(); addSelectionImpl(startDate, endDate); break; case MULTIPLE_INTERVAL_SELECTION: clearSelectionImpl(); addSelectionImpl(startDate, endDate); break; default: break; } fireValueChanged(EventType.DATES_SET); } /** * {@inheritDoc} */ public void removeSelectionInterval(final Date startDate, final Date endDate) { if (startDate.after(endDate)) { return; } long startDateMs = startDate.getTime(); long endDateMs = endDate.getTime(); ArrayList<Date> datesToRemove = new ArrayList<Date>(); for (Date selectedDate : selectedDates) { long selectedDateMs = selectedDate.getTime(); if (selectedDateMs >= startDateMs && selectedDateMs <= endDateMs) { datesToRemove.add(selectedDate); } } if (!datesToRemove.isEmpty()) { selectedDates.removeAll(datesToRemove); fireValueChanged(EventType.DATES_REMOVED); } } /** * {@inheritDoc} */ public void clearSelection() { clearSelectionImpl(); fireValueChanged(EventType.SELECTION_CLEARED); } private void clearSelectionImpl() { selectedDates.clear(); } /** * {@inheritDoc} */ public SortedSet<Date> getSelection() { return new TreeSet<Date>(selectedDates); } /** * {@inheritDoc} */ public boolean isSelected(final Date date) { return selectedDates.contains(date); } /** * {@inheritDoc} */ public boolean isSelectionEmpty() { return selectedDates.size() == 0; } /** * {@inheritDoc} */ public void addDateSelectionListener(DateSelectionListener l) { listenerMap.add(DateSelectionListener.class, l); } /** * {@inheritDoc} */ public void removeDateSelectionListener(DateSelectionListener l) { listenerMap.remove(DateSelectionListener.class, l); } /** * {@inheritDoc} */ public SortedSet<Date> getUnselectableDates() { return new TreeSet<Date>(unselectableDates); } /** * {@inheritDoc} */ public void setUnselectableDates(SortedSet<Date> unselectableDates) { this.unselectableDates = unselectableDates; for (Date unselectableDate : this.unselectableDates) { removeSelectionInterval(unselectableDate, unselectableDate); } fireValueChanged(EventType.UNSELECTED_DATES_CHANGED); } /** * {@inheritDoc} */ public boolean isUnselectableDate(Date date) { return upperBound != null && upperBound.getTime() < date.getTime() || lowerBound != null && lowerBound.getTime() > date.getTime() || unselectableDates != null && unselectableDates.contains(date); } /** * {@inheritDoc} */ public Date getUpperBound() { return upperBound; } /** * {@inheritDoc} */ public void setUpperBound(Date upperBound) { if ((upperBound != null && !upperBound.equals(this.upperBound)) || (upperBound == null && upperBound != this.upperBound)) { this.upperBound = upperBound; if (!selectedDates.isEmpty() && selectedDates.last().after(this.upperBound)) { if (this.upperBound != null) { // Remove anything above the upper bound long justAboveUpperBoundMs = this.upperBound.getTime() + 1; if (!selectedDates.isEmpty() && selectedDates.last().before(this.upperBound)) removeSelectionInterval(this.upperBound, new Date(justAboveUpperBoundMs)); } } fireValueChanged(EventType.UPPER_BOUND_CHANGED); } } /** * {@inheritDoc} */ public Date getLowerBound() { return lowerBound; } /** * {@inheritDoc} */ public void setLowerBound(Date lowerBound) { if ((lowerBound != null && !lowerBound.equals(this.lowerBound)) || (lowerBound == null && lowerBound != this.lowerBound)) { this.lowerBound = lowerBound; if (this.lowerBound != null) { // Remove anything below the lower bound long justBelowLowerBoundMs = this.lowerBound.getTime() - 1; if (!selectedDates.isEmpty() && selectedDates.first().before(this.lowerBound)) { removeSelectionInterval(selectedDates.first(), new Date(justBelowLowerBoundMs)); } } fireValueChanged(EventType.LOWER_BOUND_CHANGED); } } public List<DateSelectionListener> getDateSelectionListeners() { return listenerMap.getListeners(DateSelectionListener.class); } protected void fireValueChanged(DateSelectionEvent.EventType eventType) { List<DateSelectionListener> listeners = getDateSelectionListeners(); DateSelectionEvent e = null; for (DateSelectionListener listener : listeners) { if (e == null) { e = new DateSelectionEvent(this, eventType); } listener.valueChanged(e); } } private void addSelectionImpl(final Date startDate, final Date endDate) { cal.setTime(startDate); Date date = cal.getTime(); while (date.before(endDate) || date.equals(endDate)) { selectedDates.add(date); cal.add(Calendar.DATE, 1); date = cal.getTime(); } } } \ No newline at end of file diff --git a/src/test/org/jdesktop/swingx/DefaultDateSelectionModelTest.java b/src/test/org/jdesktop/swingx/DefaultDateSelectionModelTest.java index a3727de4..3fd8d13e 100644 --- a/src/test/org/jdesktop/swingx/DefaultDateSelectionModelTest.java +++ b/src/test/org/jdesktop/swingx/DefaultDateSelectionModelTest.java @@ -1,131 +1,136 @@ /** * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.util.Calendar; import java.util.Date; import java.util.SortedSet; import java.util.TreeSet; import junit.framework.TestCase; /** * Tests for the DefaultDateSelectionModel */ public class DefaultDateSelectionModelTest extends TestCase { private DefaultDateSelectionModel model; @Override public void setUp() { model = new DefaultDateSelectionModel(); } @Override public void tearDown() { } public void testSingleSelection() { model.setSelectionMode(DateSelectionModel.SelectionMode.SINGLE_SELECTION); Date today = new Date(); model.setSelectionInterval(today, today); SortedSet<Date> selection = model.getSelection(); assertTrue(!selection.isEmpty()); assertTrue(1 == selection.size()); assertTrue(today.equals(selection.first())); Calendar cal = Calendar.getInstance(); cal.setTime(today); cal.roll(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); model.setSelectionInterval(today, tomorrow); selection = model.getSelection(); assertTrue(!selection.isEmpty()); assertTrue(1 == selection.size()); assertTrue(today.equals(selection.first())); model.addSelectionInterval(tomorrow, tomorrow); selection = model.getSelection(); assertTrue(!selection.isEmpty()); assertTrue(1 == selection.size()); assertTrue(tomorrow.equals(selection.first())); } public void testSingleIntervalSelection() { model.setSelectionMode(DateSelectionModel.SelectionMode.SINGLE_INTERVAL_SELECTION); Date startDate = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); cal.add(Calendar.DAY_OF_MONTH, 5); Date endDate = cal.getTime(); model.setSelectionInterval(startDate, endDate); SortedSet<Date> selection = model.getSelection(); assertTrue(startDate.equals(selection.first())); assertTrue(endDate.equals(selection.last())); cal.setTime(startDate); cal.roll(Calendar.MONTH, 1); Date startDateNextMonth = cal.getTime(); model.addSelectionInterval(startDateNextMonth, startDateNextMonth); selection = model.getSelection(); assertTrue(startDateNextMonth.equals(selection.first())); assertTrue(startDateNextMonth.equals(selection.last())); } public void testUnselctableDates() { + // Make sure the unselectable dates returns an empty set if it hasn't been + // used. + SortedSet<Date> unselectableDates = model.getUnselectableDates(); + assert(unselectableDates.isEmpty()); + model.setSelectionMode(DateSelectionModel.SelectionMode.MULTIPLE_INTERVAL_SELECTION); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); Date today = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tPlus1 = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tPlus2 = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tPlus3 = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tPlus4 = cal.getTime(); model.setSelectionInterval(today, tPlus4); SortedSet<Date> selection = model.getSelection(); assertTrue(!selection.isEmpty()); assertTrue(5 == selection.size()); assertTrue(today.equals(selection.first())); assertTrue(tPlus4.equals(selection.last())); - SortedSet<Date> unselectableDates = new TreeSet<Date>(); + unselectableDates = new TreeSet<Date>(); unselectableDates.add(tPlus1); unselectableDates.add(tPlus3); model.setUnselectableDates(unselectableDates); // Make sure setting the unselectable dates to include a selected date removes // it from the selected set. selection = model.getSelection(); assertTrue(!selection.isEmpty()); assertTrue(3 == selection.size()); assertTrue(selection.contains(today)); assertTrue(selection.contains(tPlus2)); assertTrue(selection.contains(tPlus4)); // Make sure the unselectable dates is the same as what we set. SortedSet<Date> result = model.getUnselectableDates(); assertTrue(unselectableDates.equals(result)); } } \ No newline at end of file
false
false
null
null
diff --git a/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassAdmin.java b/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassAdmin.java index 9a9a18e..c8464e8 100644 --- a/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassAdmin.java +++ b/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassAdmin.java @@ -1,300 +1,307 @@ /** * Created on 1.2.2003 * * This class does something very clever. */ package se.idega.idegaweb.commune.school.presentation; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import se.idega.idegaweb.commune.school.business.SchoolChoiceComparator; import se.idega.idegaweb.commune.school.business.SchoolClassMemberComparator; import se.idega.idegaweb.commune.school.data.SchoolChoice; import se.idega.idegaweb.commune.school.event.SchoolEventListener; import se.idega.util.PIDChecker; import com.idega.block.school.data.SchoolClass; import com.idega.block.school.data.SchoolClassMember; import com.idega.block.school.data.SchoolYear; import com.idega.business.IBOLookup; import com.idega.core.data.Address; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.GenericButton; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.SubmitButton; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.util.PersonalIDFormatter; /** * @author laddi * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class SchoolClassAdmin extends SchoolCommuneBlock { private final String PARAMETER_ACTION = "sch_action"; private final String PARAMETER_METHOD = "sch_method"; private final String PARAMETER_STUDENT_ID = "sch_student_id"; private final String PARAMETER_SORT = "sch_student_sort"; private final int ACTION_MANAGE = 1; private final int ACTION_SAVE = 2; private final int ACTION_DELETE = 4; private int action = 0; private int method = 0; private int sortStudentsBy = SchoolChoiceComparator.NAME_SORT; /** * @see se.idega.idegaweb.commune.school.presentation.SchoolCommuneBlock#init(com.idega.presentation.IWContext) */ public void init(IWContext iwc) throws RemoteException { if (iwc.isLoggedOn()) { parseAction(iwc); switch (method) { case ACTION_SAVE : //saveClass(iwc); break; case ACTION_DELETE : delete(iwc); break; } switch (action) { case ACTION_MANAGE : drawForm(iwc); break; } } else { add(super.getSmallHeader(localize("not_logged_on", "Not logged on"))); } } private void parseAction(IWContext iwc) throws RemoteException { if (iwc.isParameterSet(PARAMETER_ACTION)) action = Integer.parseInt(iwc.getParameter(PARAMETER_ACTION)); else action = ACTION_MANAGE; if (iwc.isParameterSet(PARAMETER_METHOD)) method = Integer.parseInt(iwc.getParameter(PARAMETER_METHOD)); else method = 0; if (iwc.isParameterSet(PARAMETER_SORT)) sortStudentsBy = Integer.parseInt(iwc.getParameter(PARAMETER_SORT)); else sortStudentsBy = SchoolChoiceComparator.NAME_SORT; } private void drawForm(IWContext iwc) throws RemoteException { Form form = new Form(); form.setEventListener(SchoolEventListener.class); form.add(new HiddenInput(PARAMETER_ACTION, String.valueOf(action))); Table table = new Table(1, 3); table.setCellpadding(0); table.setCellspacing(0); table.setWidth(getWidth()); table.setHeight(2, "12"); form.add(table); Table headerTable = new Table(2, 1); headerTable.setWidth(Table.HUNDRED_PERCENT); headerTable.setCellpaddingAndCellspacing(0); headerTable.setAlignment(2, 1, Table.HORIZONTAL_ALIGN_RIGHT); table.add(headerTable, 1, 1); headerTable.add(getNavigationTable(true, false), 1, 1); headerTable.add(getSortTable(), 2, 1); headerTable.setVerticalAlignment(2, 1, Table.VERTICAL_ALIGN_BOTTOM); if (getSchoolClassID() != -1) table.add(getStudentTable(iwc), 1, 3); add(form); } private Table getStudentTable(IWContext iwc) throws RemoteException { Table table = new Table(); table.setWidth(getWidth()); table.setCellpadding(getCellpadding()); table.setCellspacing(getCellspacing()); table.setColumns(7); table.setWidth(6, "12"); table.setWidth(7, "12"); int row = 1; Table addTable = new Table(3,1); addTable.setCellpadding(0); addTable.setCellspacing(0); addTable.setWidth(2, "4"); table.add(addTable, 1, row++); Link addLink = new Link(getEditIcon(localize("school.add_student", "Add student"))); addLink.setWindowToOpen(SchoolAdminWindow.class); addLink.addParameter(SchoolAdminOverview.PARAMETER_METHOD, SchoolAdminOverview.METHOD_ADD_STUDENT); addLink.addParameter(SchoolAdminOverview.PARAMETER_PAGE_ID, getParentPage().getPageID()); addTable.add(addLink, 1, 1); Link addLinkText = getSmallLink(localize("school.add_student", "Add student")); addLinkText.setWindowToOpen(SchoolAdminWindow.class); addLinkText.addParameter(SchoolAdminOverview.PARAMETER_METHOD, SchoolAdminOverview.METHOD_ADD_STUDENT); addLinkText.addParameter(SchoolAdminOverview.PARAMETER_PAGE_ID, getParentPage().getPageID()); addTable.add(addLinkText, 3, 1); table.add(getSmallHeader(localize("school.name", "Name")), 1, row); table.add(getSmallHeader(localize("school.personal_id", "Personal ID")), 2, row); table.add(getSmallHeader(localize("school.gender", "Gender")), 3, row); table.add(getSmallHeader(localize("school.address", "Address")), 4, row); table.add(getSmallHeader(localize("school.class", "Class")), 5, row); table.add(new HiddenInput(PARAMETER_STUDENT_ID, "-1"), 6, row); table.add(new HiddenInput(PARAMETER_METHOD, "0"), 7, row++); User student; Address address; SchoolClassMember studentMember; SchoolClass schoolClass = null; SubmitButton delete; Link move; Link link; int numberOfStudents = 0; + boolean hasChoice = false; + boolean hasMoveChoice = false; List students = new ArrayList(getBusiness().getSchoolBusiness().findStudentsInClass(getSchoolClassID())); if (!students.isEmpty()) { numberOfStudents = students.size(); Map studentMap = getBusiness().getStudentList(students); Collections.sort(students, new SchoolClassMemberComparator(sortStudentsBy, iwc.getCurrentLocale(), getUserBusiness(iwc), studentMap)); Iterator iter = students.iterator(); while (iter.hasNext()) { studentMember = (SchoolClassMember) iter.next(); student = (User) studentMap.get(new Integer(studentMember.getClassMemberId())); schoolClass = getBusiness().getSchoolBusiness().findSchoolClass(new Integer(studentMember.getSchoolClassId())); address = getUserBusiness(iwc).getUserAddress1(((Integer) student.getPrimaryKey()).intValue()); + hasChoice = getBusiness().hasChoiceToThisSchool(studentMember.getClassMemberId(), getSchoolID(), getSchoolSeasonID()); + hasMoveChoice = getBusiness().hasMoveChoiceToOtherSchool(studentMember.getClassMemberId(), getSchoolID(), getSchoolSeasonID()); delete = new SubmitButton(getDeleteIcon(localize("school.delete_from_group", "Click to remove student from group")),"delete_student_"+String.valueOf(new Integer(studentMember.getClassMemberId()))); delete.setDescription(localize("school.delete_from_group", "Click to remove student from group")); delete.setValueOnClick(PARAMETER_STUDENT_ID, String.valueOf(studentMember.getClassMemberId())); delete.setValueOnClick(PARAMETER_METHOD, String.valueOf(ACTION_DELETE)); delete.setSubmitConfirm(localize("school.confirm_student_delete","Are you sure you want to remove the student from this class?")); move = new Link(getEditIcon(localize("school.move_to_another_group", "Move this student to another group"))); move.setWindowToOpen(SchoolAdminWindow.class); move.setParameter(SchoolAdminOverview.PARAMETER_METHOD, String.valueOf(SchoolAdminOverview.METHOD_MOVE_GROUP)); move.setParameter(SchoolAdminOverview.PARAMETER_USER_ID, String.valueOf(studentMember.getClassMemberId())); move.setParameter(SchoolAdminOverview.PARAMETER_SHOW_NO_CHOICES, "true"); move.addParameter(SchoolAdminOverview.PARAMETER_PAGE_ID, getParentPage().getPageID()); String name = student.getNameLastFirst(true); if (iwc.getCurrentLocale().getLanguage().equalsIgnoreCase("is")) name = student.getName(); - if (getBusiness().hasMoveChoiceToOtherSchool(studentMember.getClassMemberId(), getSchoolID(), getSchoolSeasonID())) { - table.setRowColor(row, "#FFEAEA"); + if (hasChoice || hasMoveChoice) { + if (hasChoice) + table.setRowColor(row, "#EAFFEE"); + if (hasMoveChoice) + table.setRowColor(row, "#FFEAEA"); } else { if (row % 2 == 0) table.setRowColor(row, getZebraColor1()); else table.setRowColor(row, getZebraColor2()); } link = (Link) this.getSmallLink(name); link.setWindowToOpen(SchoolAdminWindow.class); link.setParameter(SchoolAdminOverview.PARAMETER_METHOD, String.valueOf(SchoolAdminOverview.METHOD_OVERVIEW)); link.setParameter(SchoolAdminOverview.PARAMETER_USER_ID, String.valueOf(studentMember.getClassMemberId())); link.setParameter(SchoolAdminOverview.PARAMETER_SHOW_ONLY_OVERVIEW, "true"); link.setParameter(SchoolAdminOverview.PARAMETER_SHOW_NO_CHOICES, "true"); link.addParameter(SchoolAdminOverview.PARAMETER_PAGE_ID, getParentPage().getPageID()); table.add(link, 1, row); table.add(getSmallText(PersonalIDFormatter.format(student.getPersonalID(), iwc.getCurrentLocale())), 2, row); if (PIDChecker.getInstance().isFemale(student.getPersonalID())) table.add(getSmallText(localize("school.girl", "Girl")), 3, row); else table.add(getSmallText(localize("school.boy", "Boy")), 3, row); if (address != null && address.getStreetAddress() != null) table.add(getSmallText(address.getStreetAddress()), 4, row); if (schoolClass != null) table.add(getSmallText(schoolClass.getName()), 5, row); table.add(move, 6, row); table.add(delete, 7, row++); } } if (numberOfStudents > 0) { table.mergeCells(1, row, table.getColumns(), row); table.add(getSmallHeader(localize("school.number_of_students", "Number of students") + ": " + String.valueOf(numberOfStudents)), 1, row++); } table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER); table.setColumnAlignment(5, Table.HORIZONTAL_ALIGN_CENTER); table.setRowColor(2, getHeaderColor()); table.setRowColor(row, "#FFFFFF"); return table; } protected Table getSortTable() throws RemoteException { Table table = new Table(2, 3); table.setCellpadding(0); table.setCellspacing(0); SchoolYear schoolYear = getBusiness().getSchoolBusiness().getSchoolYear(new Integer(getSchoolYearID())); int yearAge = -1; if (schoolYear != null) yearAge = schoolYear.getSchoolYearAge(); table.add(getSmallHeader(localize("school.sort_by", "Sort by") + ":" + Text.NON_BREAKING_SPACE), 1, 3); DropdownMenu menu = (DropdownMenu) getStyledInterface(new DropdownMenu(PARAMETER_SORT)); menu.addMenuElement(SchoolChoiceComparator.NAME_SORT, localize("school.sort_name", "Name")); menu.addMenuElement(SchoolChoiceComparator.PERSONAL_ID_SORT, localize("school.sort_personal_id", "Personal ID")); menu.addMenuElement(SchoolChoiceComparator.ADDRESS_SORT, localize("school.sort_address", "Address")); menu.addMenuElement(SchoolChoiceComparator.GENDER_SORT, localize("school.sort_gender", "Gender")); if (action != ACTION_SAVE && yearAge >= 12) menu.addMenuElement(SchoolChoiceComparator.LANGUAGE_SORT, localize("school.sort_language", "Language")); menu.setSelectedElement(sortStudentsBy); menu.setToSubmit(); table.add(menu, 2, 3); table.setColumnAlignment(2, Table.HORIZONTAL_ALIGN_RIGHT); return table; } private void delete(IWContext iwc) throws RemoteException { String student = iwc.getParameter(PARAMETER_STUDENT_ID); if (student != null && student.length() > 0) { getBusiness().getSchoolBusiness().removeSchoolClassMemberFromClass(Integer.parseInt(student),getSchoolClassID()); SchoolChoice choice = getBusiness().getSchoolChoiceBusiness().findByStudentAndSchoolAndSeason(Integer.parseInt(student), getSchoolID(), getSchoolSeasonID()); getBusiness().setNeedsSpecialAttention(Integer.parseInt(student), getBusiness().getPreviousSchoolSeasonID(getSchoolSeasonID()),false); if (choice != null) { if (choice.getCaseStatus().equals("PLAC")) getBusiness().getSchoolChoiceBusiness().setAsPreliminary(choice, iwc.getCurrentUser()); } } } private UserBusiness getUserBusiness(IWContext iwc) throws RemoteException { return (UserBusiness) IBOLookup.getServiceInstance(iwc, UserBusiness.class); } } \ No newline at end of file diff --git a/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassEditor.java b/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassEditor.java index 28a1c10..c7ef0cf 100644 --- a/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassEditor.java +++ b/src/java/se/idega/idegaweb/commune/school/presentation/SchoolClassEditor.java @@ -1,945 +1,953 @@ package se.idega.idegaweb.commune.school.presentation; import java.rmi.RemoteException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.ejb.FinderException; import se.idega.idegaweb.commune.school.business.SchoolClassWriter; import se.idega.idegaweb.commune.school.business.SchoolChoiceComparator; import se.idega.idegaweb.commune.school.business.SchoolClassMemberComparator; import se.idega.idegaweb.commune.school.data.SchoolChoice; import se.idega.idegaweb.commune.school.data.SchoolChoiceBMPBean; import se.idega.idegaweb.commune.school.data.SchoolChoiceHome; import se.idega.idegaweb.commune.school.event.SchoolEventListener; import se.idega.util.PIDChecker; import com.idega.block.school.data.School; import com.idega.block.school.data.SchoolClass; import com.idega.block.school.data.SchoolClassMember; import com.idega.block.school.data.SchoolHome; import com.idega.block.school.data.SchoolSeason; import com.idega.block.school.data.SchoolYear; import com.idega.business.IBOLookup; import com.idega.core.data.Address; import com.idega.data.IDOException; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Table; import com.idega.presentation.text.Break; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.CheckBox; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.GenericButton; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Parameter; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.presentation.ui.Window; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.util.GenericUserComparator; import com.idega.util.IWCalendar; import com.idega.util.IWTimestamp; import com.idega.util.PersonalIDFormatter; import com.idega.util.text.TextSoap; /** * @author Laddi */ public class SchoolClassEditor extends SchoolCommuneBlock { public static final String PARAMETER_ACTION = "sch_action"; private final String PARAMETER_METHOD = "sch_method"; private final String PARAMETER_APPLICANT_ID = "sch_applicant_id"; private final String PARAMETER_PREVIOUS_CLASS_ID = "sch_prev_class_id"; private final String PARAMETER_SORT = "sch_choice_sort"; private final String PARAMETER_SEARCH = "scH_choise_search"; private final String PARAMETER_CURRENT_APPLICATION_PAGE = "sch_crrap_pg"; private final int ACTION_MANAGE = 1; public static final int ACTION_SAVE = 2; private final int ACTION_FINALIZE_GROUP = 3; private final int ACTION_DELETE = 4; private int action = 0; private int method = 0; private int sortStudentsBy = SchoolChoiceComparator.NAME_SORT; private int sortChoicesBy = SchoolClassMemberComparator.NAME_SORT; private String searchString = ""; private int _previousSchoolClassID = -1; private int _previousSchoolSeasonID = -1; private int _previousSchoolYearID = -1; private boolean multibleSchools = false; private boolean showStudentTable = true; private boolean searchEnabled = true; private int applicationsPerPage = 10; private boolean showStatistics = true; public void init(IWContext iwc) throws RemoteException { if (iwc.isLoggedOn()) { parseAction(iwc); switch (method) { case ACTION_SAVE : saveClass(iwc); break; case ACTION_DELETE : delete(iwc); break; case ACTION_FINALIZE_GROUP : finalize(iwc); break; } switch (action) { case ACTION_MANAGE : drawForm(iwc); break; case ACTION_SAVE : drawNewGroupForm(iwc); break; } } else { add(super.getSmallHeader(localize("not_logged_on", "Not logged on"))); } } private void parseAction(IWContext iwc) throws RemoteException { if (iwc.isParameterSet(PARAMETER_PREVIOUS_CLASS_ID)) _previousSchoolClassID = Integer.parseInt(iwc.getParameter(PARAMETER_PREVIOUS_CLASS_ID)); _previousSchoolSeasonID = getBusiness().getPreviousSchoolSeasonID(getSchoolSeasonID()); _previousSchoolYearID = getBusiness().getPreviousSchoolYear(getSchoolYearID()); if (iwc.isParameterSet(PARAMETER_ACTION)) action = Integer.parseInt(iwc.getParameter(PARAMETER_ACTION)); else action = ACTION_MANAGE; if (iwc.isParameterSet(PARAMETER_METHOD)) method = Integer.parseInt(iwc.getParameter(PARAMETER_METHOD)); else method = 0; if (iwc.isParameterSet(PARAMETER_SORT)) sortChoicesBy = Integer.parseInt(iwc.getParameter(PARAMETER_SORT)); else sortChoicesBy = SchoolChoiceComparator.NAME_SORT; sortStudentsBy = sortChoicesBy; if (iwc.isParameterSet(PARAMETER_SEARCH)) searchString = iwc.getParameter(PARAMETER_SEARCH); /** Fixing String */ if (searchString != null && searchString.length() > 0) { try { String temp = searchString; temp = TextSoap.findAndCut(temp, "-"); Long.parseLong(temp); if (temp.length() == 10 ) { int firstTwo = Integer.parseInt(temp.substring(0, 2)); if (firstTwo < 85) { temp = "20"+temp; } else { temp = "19"+temp; } } searchString = temp; }catch (NumberFormatException nfe) {} } } private void drawForm(IWContext iwc) throws RemoteException { Form form = new Form(); form.setEventListener(SchoolEventListener.class); form.add(new HiddenInput(PARAMETER_ACTION, String.valueOf(action))); Table table = new Table(1, 11); table.setCellpadding(0); table.setCellspacing(0); table.setWidth(getWidth()); table.setHeight(2, "12"); table.setHeight(4, "6"); table.setHeight(6, "12"); table.setHeight(8, "6"); table.setHeight(10, "12"); form.add(table); Table headerTable = new Table(2, 1); headerTable.setWidth(Table.HUNDRED_PERCENT); headerTable.setCellpaddingAndCellspacing(0); headerTable.setAlignment(2, 1, Table.HORIZONTAL_ALIGN_RIGHT); table.add(headerTable, 1, 1); headerTable.add(getNavigationTable(true, multibleSchools), 1, 1); headerTable.add(getSearchAndSortTable(), 2, 1); headerTable.setVerticalAlignment(2, 1, Table.VERTICAL_ALIGN_BOTTOM); table.add(getApplicationTable(iwc), 1, 5); table.add(getChoiceHeader(), 1, 3); if (this.showStudentTable) { if (_previousSchoolYearID != -1) { try { Collection previousClasses = getBusiness().getPreviousSchoolClasses(getBusiness().getSchoolBusiness().getSchool(new Integer(getSchoolID())), getBusiness().getSchoolBusiness().getSchoolSeason(new Integer(getSchoolSeasonID())), getBusiness().getSchoolBusiness().getSchoolYear(new Integer(getSchoolYearID()))); validateSchoolClass(previousClasses); table.add(getPreviousHeader(previousClasses), 1, 7); table.add(getStudentTable(iwc), 1, 9); } catch (NullPointerException ne) { } } if (getSchoolClassID() != -1) { HiddenInput method = new HiddenInput(PARAMETER_METHOD, "0"); SubmitButton submit = (SubmitButton) getStyledInterface(new SubmitButton(localize("save", "Save"))); submit.setValueOnClick(PARAMETER_METHOD, String.valueOf(ACTION_SAVE)); submit.setValueOnClick(PARAMETER_ACTION, String.valueOf(ACTION_SAVE)); form.setToDisableOnSubmit(submit, true); SubmitButton view = (SubmitButton) getStyledInterface(new SubmitButton(localize("school.view_group", "View group"))); view.setValueOnClick(PARAMETER_ACTION, String.valueOf(ACTION_SAVE)); table.add(method, 1, 11); table.add(submit, 1, 11); table.add(Text.NON_BREAKING_SPACE, 1, 11); table.add(view, 1, 11); } } add(form); } private void drawNewGroupForm(IWContext iwc) throws RemoteException { Form form = new Form(); form.setEventListener(SchoolEventListener.class); form.add(new HiddenInput(PARAMETER_ACTION, String.valueOf(action))); Table table = new Table(); table.setCellpadding(0); table.setCellspacing(0); table.setWidth(getWidth()); form.add(table); int row = 1; Table headerTable = new Table(2, 1); headerTable.setWidth(Table.HUNDRED_PERCENT); headerTable.setCellpaddingAndCellspacing(0); headerTable.setAlignment(2, 1, Table.HORIZONTAL_ALIGN_RIGHT); table.add(headerTable, 1, row++); table.setHeight(row++, "12"); headerTable.add(getNavigationTable(true, multibleSchools), 1, 1); headerTable.add(getSearchAndSortTable(), 2, 1); if (getSchoolClassID() != -1) { table.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT); Link pdfLink = getPDFLink(SchoolClassWriter.class,getBundle().getImage("shared/pdf.gif")); pdfLink.addParameter(SchoolClassWriter.prmClassId, getSchoolClassID()); table.add(pdfLink, 1, row); Link excelLink = getXLSLink(SchoolClassWriter.class,getBundle().getImage("shared/xls.gif")); excelLink.addParameter(SchoolClassWriter.prmClassId, getSchoolClassID()); table.add(Text.NON_BREAKING_SPACE, 1, row); table.add(excelLink, 1, row++); } table.add(getNewStudentTable(iwc), 1, row); add(form); } private Table getApplicationTable(IWContext iwc) throws RemoteException { Table table = new Table(); table.setWidth(getWidth()); table.setCellpadding(getCellpadding()); table.setCellspacing(getCellspacing()); boolean showLanguage = false; SchoolYear year = getBusiness().getSchoolBusiness().getSchoolYear(new Integer(getSchoolYearID())); int schoolYearAge = getBusiness().getGradeForYear(getSchoolYearID()) - 1; if (year != null && schoolYearAge >= 12) showLanguage = true; if (!showStudentTable) { table.setColumns(table.getColumns() - 1); } String[] validStatuses = null; //if (choice.getStatus().equalsIgnoreCase("PREL") || choice.getStatus().equalsIgnoreCase("FLYT")) { if (showStatistics) { validStatuses = new String[] { SchoolChoiceBMPBean.CASE_STATUS_PLACED, SchoolChoiceBMPBean.CASE_STATUS_PRELIMINARY, SchoolChoiceBMPBean.CASE_STATUS_MOVED }; } else validStatuses = new String[] { SchoolChoiceBMPBean.CASE_STATUS_PRELIMINARY, SchoolChoiceBMPBean.CASE_STATUS_MOVED }; int applicantsSize = 0; try { applicantsSize = getBusiness().getSchoolChoiceBusiness().getNumberOfApplicantsForSchool(getSchoolID(), getSchoolSeasonID(), schoolYearAge, null, validStatuses, searchString); } catch (Exception e) { applicantsSize = 0; } int currPage = 0; int maxPage = (int) Math.ceil(applicantsSize / applicationsPerPage); if (iwc.isParameterSet(PARAMETER_CURRENT_APPLICATION_PAGE)) { currPage = Integer.parseInt(iwc.getParameter(PARAMETER_CURRENT_APPLICATION_PAGE)); } int start = currPage * applicationsPerPage; Collection applicants = getBusiness().getSchoolChoiceBusiness().getApplicantsForSchool(getSchoolID(), getSchoolSeasonID(), schoolYearAge, validStatuses, searchString, sortChoicesBy, applicationsPerPage, start); int row = 1; int column = 1; int headerRow = -1; Table navigationTable = new Table(3, 1); navigationTable.setCellpadding(0); navigationTable.setCellspacing(0); navigationTable.setWidth(Table.HUNDRED_PERCENT); navigationTable.setWidth(1, "33%"); navigationTable.setWidth(2, "33%"); navigationTable.setWidth(3, "33%"); navigationTable.setAlignment(2, 1, Table.HORIZONTAL_ALIGN_CENTER); navigationTable.setAlignment(3, 1, Table.HORIZONTAL_ALIGN_RIGHT); table.add(navigationTable, 1, row++); Text prev = getSmallText(localize("previous", "Previous")); Text next = getSmallText(localize("next", "Next")); Text info = getSmallText(localize("page", "Page") + " " + (currPage + 1) + " " + localize("of", "of") + " " + (maxPage + 1)); if (currPage > 0) { Link lPrev = getSmallLink(localize("previous", "Previous")); lPrev.addParameter(PARAMETER_CURRENT_APPLICATION_PAGE, Integer.toString(currPage - 1)); lPrev.addParameter(PARAMETER_SEARCH, iwc.getParameter(PARAMETER_SEARCH)); lPrev.addParameter(PARAMETER_SORT, iwc.getParameter(PARAMETER_SORT)); navigationTable.add(lPrev, 1, 1); } else { navigationTable.add(prev, 1, 1); } navigationTable.add(info, 2, 1); if (currPage < maxPage) { Link lNext = getSmallLink(localize("next", "Next")); lNext.addParameter(PARAMETER_CURRENT_APPLICATION_PAGE, Integer.toString(currPage + 1)); lNext.addParameter(PARAMETER_SEARCH, iwc.getParameter(PARAMETER_SEARCH)); lNext.addParameter(PARAMETER_SORT, iwc.getParameter(PARAMETER_SORT)); navigationTable.add(lNext, 3, 1); } else { navigationTable.add(next, 3, 1); } headerRow = row; table.add(getSmallHeader(localize("school.name", "Name")), column++, row); table.add(getSmallHeader(localize("school.personal_id", "Personal ID")), column++, row); table.add(getSmallHeader(localize("school.address", "Address")), column++, row); table.add(getSmallHeader(localize("school.gender", "Gender")), column++, row); table.add(getSmallHeader(localize("school.from_school", "From School")), column++, row); if (showLanguage) table.add(getSmallHeader(localize("school.language", "Language")), column, row); row++; CheckBox checkBox = new CheckBox(); Link link; if (!applicants.isEmpty()) { //Map studentMap = getBusiness().getUserMapFromChoices(applicants); //Map addressMap = getBusiness().getUserAddressesMapFromChoices(applicants); //if (sortChoicesBy == SchoolChoiceComparator.ADDRESS_SORT) // addressMap = getBusiness().getUserAddressesMapFromChoices(getBusiness().getSchoolChoiceBusiness().getApplicantsForSchoolQuery(getSchoolID(), getSchoolSeasonID(), schoolYearAge, validStatuses, searchString, sortChoicesBy)); //System.out.println("Sorting: "+(System.currentTimeMillis() - currentTime)+"ms"); //Collections.sort(applicants, new SchoolChoiceComparator(sortChoicesBy, iwc.getCurrentLocale(), getUserBusiness(iwc), studentMap, addressMap)); SchoolChoice choice; School school; User applicant; Address address; //IWCalendar calendar; Iterator iter = applicants.iterator(); while (iter.hasNext()) { column = 1; choice = (SchoolChoice) iter.next(); //applicant = (User) studentMap.get(new Integer(choice.getChildId())); applicant = getUserBusiness(iwc).getUser(choice.getChildId()); school = getBusiness().getSchoolBusiness().getSchool(new Integer(choice.getCurrentSchoolId())); checkBox = getCheckBox(PARAMETER_APPLICANT_ID, String.valueOf(choice.getChildId()) + "," + choice.getPrimaryKey().toString()); //calendar = new IWCalendar(iwc.getCurrentLocale(), choice.getCreated()); //address = (Address) addressMap.get(new Integer(choice.getChildId())); address = getUserBusiness(iwc).getUsersMainAddress(applicant); if (getBusiness().isAlreadyInSchool(choice.getChildId(),getSession().getSchoolID(), getSession().getSchoolSeasonID())) checkBox.setDisabled(true); String name = applicant.getNameLastFirst(true); if (iwc.getCurrentLocale().getLanguage().equalsIgnoreCase("is")) name = applicant.getName(); if (choice.getChoiceOrder() > 1 || choice.getStatus().equalsIgnoreCase(SchoolChoiceBMPBean.CASE_STATUS_MOVED)) table.setRowColor(row, "#FFEAEA"); else { if (row % 2 == 0) table.setRowColor(row, getZebraColor1()); else table.setRowColor(row, getZebraColor2()); } link = (Link) this.getSmallLink(name); link.setWindowToOpen(SchoolAdminWindow.class); link.setParameter(SchoolAdminOverview.PARAMETER_METHOD, String.valueOf(SchoolAdminOverview.METHOD_OVERVIEW)); link.setParameter(SchoolAdminOverview.PARAMETER_USER_ID, String.valueOf(choice.getChildId())); link.setParameter(SchoolAdminOverview.PARAMETER_CHOICE_ID, choice.getPrimaryKey().toString()); table.add(link, column++, row); table.add(getSmallText(PersonalIDFormatter.format(applicant.getPersonalID(), iwc.getCurrentLocale())), column++, row); if (address != null && address.getStreetAddress() != null) { table.add(getSmallText(address.getStreetAddress()), column, row); } column++; if (PIDChecker.getInstance().isFemale(applicant.getPersonalID())) table.add(getSmallText(localize("school.girl", "Girl")), column++, row); else table.add(getSmallText(localize("school.boy", "Boy")), column++, row); if (school != null) { String schoolName = school.getName(); if (schoolName.length() > 20) schoolName = schoolName.substring(0, 20) + "..."; table.add(getSmallText(schoolName), column, row); if (choice.getStatus().equalsIgnoreCase(SchoolChoiceBMPBean.CASE_STATUS_MOVED)) table.add(getSmallText(" (" + localize("school.moved", "Moved") + ")"), column, row); } column++; if (showLanguage) { if (choice.getLanguageChoice() != null) table.add(getSmallText(localize(choice.getLanguageChoice(),"")), column, row); column++; } //table.add(getSmallText(calendar.getLocaleDate(IWCalendar.SHORT)), column++, row); if (showStudentTable && getSchoolClassID() != -1) { table.setWidth(column, "12"); table.add(checkBox, column, row); } row++; } } if (showStatistics) { try { int firstApplSize = getSchoolChoiceHome().getCount(getSchoolID(), getSchoolSeasonID(), -1, new int[] { 1 }, validStatuses, ""); int secondApplSize = getSchoolChoiceHome().getCount(getSchoolID(), getSchoolSeasonID(), -1, new int[] { 2 }, validStatuses, ""); int thirdApplSize = getSchoolChoiceHome().getCount(getSchoolID(), getSchoolSeasonID(), -1, new int[] { 3 }, validStatuses, ""); String[] allStatuses = new String[] { SchoolChoiceBMPBean.CASE_STATUS_PRELIMINARY, SchoolChoiceBMPBean.CASE_STATUS_MOVED, SchoolChoiceBMPBean.CASE_STATUS_PLACED }; String[] handledStatuses = new String[] { SchoolChoiceBMPBean.CASE_STATUS_PLACED }; String[] unhandledStatuses = new String[] { SchoolChoiceBMPBean.CASE_STATUS_PRELIMINARY, SchoolChoiceBMPBean.CASE_STATUS_MOVED }; int allApplSize = getSchoolChoiceHome().getCount(getSchoolID(), getSchoolSeasonID(), -1, new int[] {}, allStatuses, ""); int handledApplSize = getSchoolChoiceHome().getCount(getSchoolID(), getSchoolSeasonID(), -1, new int[] {}, handledStatuses, ""); int unhandledApplSize = getSchoolChoiceHome().getCount(getSchoolID(), getSchoolSeasonID(), -1, new int[] {}, unhandledStatuses, ""); Table statTable = new Table(); int sRow = 1; statTable.setCellpadding(1); statTable.setCellspacing(0); statTable.add(getSmallText(localize("applications_all", "All applications") + ":"), 1, sRow); statTable.add(getSmallText("" + allApplSize), 2, sRow); ++sRow; statTable.add(getSmallText(localize("applications_handled", "Handled applications") + ":"), 1, sRow); statTable.add(getSmallText("" + handledApplSize), 2, sRow); ++sRow; statTable.add(getSmallText(localize("applications_unhandled", "Unhandled applications") + ":"), 1, sRow); statTable.add(getSmallText("" + unhandledApplSize), 2, sRow); ++sRow; statTable.add(getSmallText(localize("applications_on_first_choice", "Applcations on first choice") + ":"), 1, sRow); statTable.add(getSmallText("" + firstApplSize), 2, sRow); ++sRow; statTable.add(getSmallText(localize("applications_on_second_choice", "Applcations on second choice") + ":"), 1, sRow); statTable.add(getSmallText("" + secondApplSize), 2, sRow); ++sRow; statTable.add(getSmallText(localize("applications_on_third_choice", "Applcations on third choice") + ":"), 1, sRow); statTable.add(getSmallText("" + thirdApplSize), 2, sRow); table.mergeCells(1, row, table.getColumns(), row); table.add(statTable, 1, row); ++row; }catch (Exception e) { table.add(getSmallText(localize("error_in_statistics","Error in statistics")), 1, row); ++row; e.printStackTrace(System.err); } } if (showStudentTable && getSchoolClassID() != -1) { GenericButton selectAll = (GenericButton) getStyledInterface(new GenericButton()); selectAll.setValue(localize("school.select_all", "Select all")); selectAll.setToCheckOnClick(checkBox, true, false); GenericButton deselectAll = (GenericButton) getStyledInterface(new GenericButton()); deselectAll.setValue(localize("school.deselect_all", "Deselect all")); deselectAll.setToCheckOnClick(checkBox, false); table.add(selectAll, 1, row); table.add(Text.NON_BREAKING_SPACE, 1, row); table.add(deselectAll, 1, row); table.mergeCells(1, row, table.getColumns(), row); table.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT); table.setRowColor(row, "#FFFFFF"); } table.setColumnAlignment(4, Table.HORIZONTAL_ALIGN_CENTER); table.setRowColor(headerRow, getHeaderColor()); table.mergeCells(1, 1, table.getColumns(), 1); return table; } private Table getStudentTable(IWContext iwc) throws RemoteException { Table table = new Table(); table.setWidth(getWidth()); table.setCellpadding(getCellpadding()); table.setCellspacing(getCellspacing()); SchoolYear schoolYear = getBusiness().getSchoolBusiness().getSchoolYear(new Integer(_previousSchoolYearID)); int schoolAge = -1; if (schoolYear != null) schoolAge = schoolYear.getSchoolYearAge(); int row = 1; table.add(getSmallHeader(localize("school.name", "Name")), 1, row); table.add(getSmallHeader(localize("school.personal_id", "Personal ID")), 2, row); table.add(getSmallHeader(localize("school.gender", "Gender")), 3, row); table.add(getSmallHeader(localize("school.address", "Address")), 4, row); if (schoolAge >= 12) table.add(getSmallHeader(localize("school.language", "Language")), 5, row); row++; User student; Address address; Link link; SchoolClassMember studentMember; CheckBox checkBox = new CheckBox(); int numberOfStudents = 0; List formerStudents = new ArrayList(); if (_previousSchoolClassID != -1) formerStudents = new ArrayList(getBusiness().getSchoolBusiness().findStudentsInClass(_previousSchoolClassID)); else formerStudents = new ArrayList(getBusiness().getSchoolBusiness().findStudentsBySchoolAndSeasonAndYear(getSchoolID(), _previousSchoolSeasonID, _previousSchoolYearID)); if (!formerStudents.isEmpty()) { numberOfStudents = formerStudents.size(); Map studentMap = getBusiness().getStudentList(formerStudents); Map studentChoices = getBusiness().getStudentChoices(formerStudents, getSchoolSeasonID()); Collections.sort(formerStudents, new SchoolClassMemberComparator(sortStudentsBy, iwc.getCurrentLocale(), getUserBusiness(iwc), studentMap)); Iterator iter = formerStudents.iterator(); int column = 1; while (iter.hasNext()) { column = 1; studentMember = (SchoolClassMember) iter.next(); student = (User) studentMap.get(new Integer(studentMember.getClassMemberId())); address = getUserBusiness(iwc).getUserAddress1(((Integer) student.getPrimaryKey()).intValue()); checkBox = getCheckBox(getSession().getParameterStudentID(), String.valueOf(((Integer) student.getPrimaryKey()).intValue())); if (getBusiness().isAlreadyInSchool(studentMember.getClassMemberId(),getSession().getSchoolID(), getSession().getSchoolSeasonID())) checkBox.setDisabled(true); String name = student.getNameLastFirst(true); if (iwc.getCurrentLocale().getLanguage().equalsIgnoreCase("is")) name = student.getName(); link = (Link) this.getSmallLink(name); link.setWindowToOpen(SchoolAdminWindow.class); link.setParameter(SchoolAdminOverview.PARAMETER_METHOD, String.valueOf(SchoolAdminOverview.METHOD_OVERVIEW)); link.setParameter(SchoolAdminOverview.PARAMETER_USER_ID, String.valueOf(studentMember.getClassMemberId())); if (studentMember.getNeedsSpecialAttention()) { checkBox.setDisabled(true); boolean[] hasChoices = getBusiness().hasSchoolChoices(studentMember.getClassMemberId(), getSchoolSeasonID()); if (hasChoices[0] && hasChoices[1]) table.setRowColor(row, "#FFEAEA"); else if (hasChoices[0] && !hasChoices[1]) table.setRowColor(row, "#EAFFEE"); else { if (studentMember.getSpeciallyPlaced()) table.setRowColor(row, "#EAF1FF"); } link.setParameter(SchoolAdminOverview.PARAMETER_CHOICE_ID, String.valueOf(getBusiness().getChosenSchoolID((Collection) studentChoices.get(new Integer(studentMember.getClassMemberId()))))); } else { if (row % 2 == 0) table.setRowColor(row, getZebraColor1()); else table.setRowColor(row, getZebraColor2()); } table.add(link, column++, row); table.add(getSmallText(PersonalIDFormatter.format(student.getPersonalID(), iwc.getCurrentLocale())), column++, row); if (PIDChecker.getInstance().isFemale(student.getPersonalID())) table.add(getSmallText(localize("school.girl", "Girl")), column++, row); else table.add(getSmallText(localize("school.boy", "Boy")), column++, row); if (address != null && address.getStreetAddress() != null) table.add(getSmallText(address.getStreetAddress()), column, row); column++; if (schoolAge >= 12) { if (studentMember.getLanguage() != null) table.add(getSmallText(localize(studentMember.getLanguage(),"")), 5, row); column++; } if (getSchoolClassID() != -1) { table.setWidth(column, "12"); table.add(checkBox, column, row); } row++; } } if (numberOfStudents > 0) { table.mergeCells(1, row, table.getColumns(), row); table.add(getSmallHeader(localize("school.number_of_students", "Number of students") + ": " + String.valueOf(numberOfStudents)), 1, row++); } if (getSchoolClassID() != -1) { GenericButton selectAll = (GenericButton) getStyledInterface(new GenericButton()); selectAll.setValue(localize("school.select_all", "Select all")); selectAll.setToCheckOnClick(checkBox, true, false); GenericButton deselectAll = (GenericButton) getStyledInterface(new GenericButton()); deselectAll.setValue(localize("school.deselect_all", "Deselect all")); deselectAll.setToCheckOnClick(checkBox, false); table.add(selectAll, 1, row); table.add(Text.NON_BREAKING_SPACE, 1, row); table.add(deselectAll, 1, row); table.mergeCells(1, row, 6, row); table.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT); table.setRowColor(row, "#FFFFFF"); } table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER); table.setRowColor(1, getHeaderColor()); return table; } private Table getNewStudentTable(IWContext iwc) throws RemoteException { boolean isReady = false; SchoolClass newSchoolClass = getBusiness().getSchoolBusiness().findSchoolClass(new Integer(getSchoolClassID())); if (newSchoolClass != null) isReady = newSchoolClass.getReady(); Table table = new Table(); table.setWidth(getWidth()); table.setCellpadding(getCellpadding()); table.setCellspacing(getCellspacing()); table.setColumns(7); table.setWidth(6, "12"); table.setWidth(7, "12"); int row = 1; table.add(getSmallHeader(localize("school.name", "Name")), 1, row); table.add(getSmallHeader(localize("school.personal_id", "Personal ID")), 2, row); table.add(getSmallHeader(localize("school.gender", "Gender")), 3, row); table.add(getSmallHeader(localize("school.address", "Address")), 4, row); table.add(getSmallHeader(localize("school.class", "Class")), 5, row); table.add(new HiddenInput(PARAMETER_APPLICANT_ID, "-1"), 6, row); table.add(new HiddenInput(PARAMETER_METHOD, "0"), 7, row++); User student; Address address; SchoolClassMember studentMember; SchoolClass schoolClass = null; SubmitButton delete; Link move; Link link; int numberOfStudents = 0; + boolean hasChoice = false; + boolean hasMoveChoice = false; List formerStudents = new ArrayList(getBusiness().getSchoolBusiness().findStudentsInClass(getSchoolClassID())); if (!formerStudents.isEmpty()) { numberOfStudents = formerStudents.size(); Map studentMap = getBusiness().getStudentList(formerStudents); Collections.sort(formerStudents, new SchoolClassMemberComparator(sortStudentsBy, iwc.getCurrentLocale(), getUserBusiness(iwc), studentMap)); Iterator iter = formerStudents.iterator(); while (iter.hasNext()) { studentMember = (SchoolClassMember) iter.next(); student = (User) studentMap.get(new Integer(studentMember.getClassMemberId())); schoolClass = getBusiness().getSchoolBusiness().findSchoolClass(new Integer(studentMember.getSchoolClassId())); address = getUserBusiness(iwc).getUserAddress1(((Integer) student.getPrimaryKey()).intValue()); + hasChoice = getBusiness().hasChoiceToThisSchool(studentMember.getClassMemberId(), getSchoolID(), getSchoolSeasonID()); + hasMoveChoice = getBusiness().hasMoveChoiceToOtherSchool(studentMember.getClassMemberId(), getSchoolID(), getSchoolSeasonID()); + delete = new SubmitButton(getDeleteIcon(localize("school.delete_from_group", "Click to remove student from group")),"delete_student_"+String.valueOf(new Integer(studentMember.getClassMemberId()))); delete.setDescription(localize("school.delete_from_group", "Click to remove student from group")); delete.setValueOnClick(PARAMETER_APPLICANT_ID, String.valueOf(studentMember.getClassMemberId())); delete.setValueOnClick(PARAMETER_METHOD, String.valueOf(ACTION_DELETE)); delete.setSubmitConfirm(localize("school.confirm_student_delete","Are you sure you want to remove the student from this class?")); move = new Link(getEditIcon(localize("school.move_to_another_group", "Move this student to another group"))); move.setWindowToOpen(SchoolAdminWindow.class); move.setParameter(SchoolAdminOverview.PARAMETER_METHOD, String.valueOf(SchoolAdminOverview.METHOD_MOVE_GROUP)); move.setParameter(SchoolAdminOverview.PARAMETER_USER_ID, String.valueOf(studentMember.getClassMemberId())); move.setParameter(SchoolAdminOverview.PARAMETER_PAGE_ID, String.valueOf(getParentPage().getPageID())); String name = student.getNameLastFirst(true); if (iwc.getCurrentLocale().getLanguage().equalsIgnoreCase("is")) name = student.getName(); - if (getBusiness().hasMoveChoiceToOtherSchool(studentMember.getClassMemberId(), getSchoolID(), getSchoolSeasonID())) { - table.setRowColor(row, "#FFEAEA"); + if (hasChoice || hasMoveChoice) { + if (hasChoice) + table.setRowColor(row, "#EAFFEE"); + if (hasMoveChoice) + table.setRowColor(row, "#FFEAEA"); } else { if (row % 2 == 0) table.setRowColor(row, getZebraColor1()); else table.setRowColor(row, getZebraColor2()); } link = (Link) this.getSmallLink(name); link.setWindowToOpen(SchoolAdminWindow.class); link.setParameter(SchoolAdminOverview.PARAMETER_METHOD, String.valueOf(SchoolAdminOverview.METHOD_OVERVIEW)); link.setParameter(SchoolAdminOverview.PARAMETER_USER_ID, String.valueOf(studentMember.getClassMemberId())); link.setParameter(SchoolAdminOverview.PARAMETER_SHOW_ONLY_OVERVIEW, "true"); table.add(link, 1, row); table.add(getSmallText(PersonalIDFormatter.format(student.getPersonalID(), iwc.getCurrentLocale())), 2, row); if (PIDChecker.getInstance().isFemale(student.getPersonalID())) table.add(getSmallText(localize("school.girl", "Girl")), 3, row); else table.add(getSmallText(localize("school.boy", "Boy")), 3, row); if (address != null && address.getStreetAddress() != null) table.add(getSmallText(address.getStreetAddress()), 4, row); if (schoolClass != null) table.add(getSmallText(schoolClass.getName()), 5, row); table.add(move, 6, row); table.add(delete, 7, row++); } } if (numberOfStudents > 0) { table.mergeCells(1, row, table.getColumns(), row); table.add(getSmallHeader(localize("school.number_of_students", "Number of students") + ": " + String.valueOf(numberOfStudents)), 1, row++); } SubmitButton back = (SubmitButton) getStyledInterface(new SubmitButton(localize("school.back", "Back"))); back.setValueOnClick(PARAMETER_ACTION, String.valueOf(ACTION_MANAGE)); String buttonLabel = ""; if (isReady) buttonLabel = localize("school.class_locked", "Class locked"); else buttonLabel = localize("school.class_ready", "Class ready"); table.add(back, 1, row); table.add(Text.NON_BREAKING_SPACE, 1, row); GenericButton groupReady = (GenericButton) getStyledInterface(new GenericButton("finalize", buttonLabel)); groupReady.setWindowToOpen(SchoolAdminWindow.class); groupReady.addParameterToWindow(SchoolAdminOverview.PARAMETER_METHOD, String.valueOf(SchoolAdminOverview.METHOD_FINALIZE_GROUP)); groupReady.addParameterToWindow(SchoolAdminOverview.PARAMETER_PAGE_ID, String.valueOf(getParentPage().getPageID())); //Link groupReadyLink = new Link(groupReady); //groupReadyLink.setWindowToOpen(SchoolAdminWindow.class); //groupReadyLink.addParameter(SchoolAdminOverview.PARAMETER_METHOD, SchoolAdminOverview.METHOD_FINALIZE_GROUP); //groupReady.setValueOnClick(PARAMETER_ACTION, String.valueOf(ACTION_MANAGE)); //groupReady.setValueOnClick(PARAMETER_METHOD, String.valueOf(ACTION_FINALIZE_GROUP)); if (isReady) { //groupReady.setSubmitConfirm(localize("school.confirm_group_locked", "Are you sure you want to set the group as locked and send out e-mails to all parents?")); if (!getBusiness().canMarkSchoolClass(newSchoolClass, "mark_locked_date")) { groupReady.setDisabled(true); } } else { //groupReady.setSubmitConfirm(localize("school.confirm_group_ready", "Are you sure you want to set the group as ready and send out e-mails to all parents?")); if (!getBusiness().canMarkSchoolClass(newSchoolClass, "mark_ready_date")) { groupReady.setDisabled(true); } } table.add(groupReady, 1, row); table.mergeCells(1, row, table.getColumns(), row); table.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT); table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER); table.setRowColor(1, getHeaderColor()); table.setRowColor(row, "#FFFFFF"); return table; } protected Table getPreviousHeader(Collection classes) throws RemoteException { Table table = new Table(2, 1); table.setCellpadding(0); table.setCellspacing(0); table.setWidth(Table.HUNDRED_PERCENT); table.setAlignment(2, 1, Table.HORIZONTAL_ALIGN_RIGHT); table.add(getSmallHeader(localize("school.previous_year_class", "Previous year class")), 1, 1); table.add(getSmallHeader(localize("school.class", "Class") + ":" + Text.NON_BREAKING_SPACE), 2, 1); table.add(getPreviousSchoolClasses(classes), 2, 1); return table; } protected Table getChoiceHeader() throws RemoteException { Table table = new Table(2, 1); table.setCellpadding(0); table.setCellspacing(0); table.setWidth(Table.HUNDRED_PERCENT); table.setAlignment(2, 1, Table.HORIZONTAL_ALIGN_RIGHT); table.add(getSmallHeader(localize("school.school_choices_for_year", "School choices for selected year")), 1, 1); table.add(getSmallHeader(String.valueOf(getBusiness().getSchoolChoiceBusiness().getNumberOfApplications(getSchoolID(), getSchoolSeasonID(), getBusiness().getGradeForYear(getSchoolYearID()) - 1))), 2, 1); table.add(getSmallHeader(" / "), 2, 1); table.add(getSmallHeader(String.valueOf(getBusiness().getSchoolChoiceBusiness().getNumberOfApplications(getSchoolID(), getSchoolSeasonID()))), 2, 1); return table; } protected DropdownMenu getPreviousSchoolClasses(Collection classes) throws RemoteException { DropdownMenu menu = new DropdownMenu(PARAMETER_PREVIOUS_CLASS_ID); menu.setToSubmit(); if (!classes.isEmpty()) { Iterator iter = classes.iterator(); menu.addMenuElementFirst("-1", localize("school.all", "All")); while (iter.hasNext()) { SchoolClass element = (SchoolClass) iter.next(); menu.addMenuElement(element.getPrimaryKey().toString(), element.getName()); } } else { menu.addMenuElement(-1, ""); } if (_previousSchoolClassID != -1) menu.setSelectedElement(_previousSchoolClassID); return (DropdownMenu) getStyledInterface(menu); } protected Table getSearchAndSortTable() throws RemoteException { Table table = new Table(2, 3); table.setCellpadding(0); table.setCellspacing(0); SchoolYear schoolYear = getBusiness().getSchoolBusiness().getSchoolYear(new Integer(getSchoolYearID())); int yearAge = -1; if (schoolYear != null) yearAge = schoolYear.getSchoolYearAge(); if (searchEnabled) { table.add(getSmallHeader(localize("school.search_for", "Search for") + ":" + Text.NON_BREAKING_SPACE), 1, 1); TextInput tiSearch = (TextInput) getStyledInterface(new TextInput(PARAMETER_SEARCH, searchString)); table.add(tiSearch, 2, 1); table.setHeight(2, "2"); } table.add(getSmallHeader(localize("school.sort_by", "Sort by") + ":" + Text.NON_BREAKING_SPACE), 1, 3); DropdownMenu menu = (DropdownMenu) getStyledInterface(new DropdownMenu(PARAMETER_SORT)); menu.addMenuElement(SchoolChoiceComparator.NAME_SORT, localize("school.sort_name", "Name")); menu.addMenuElement(SchoolChoiceComparator.PERSONAL_ID_SORT, localize("school.sort_personal_id", "Personal ID")); menu.addMenuElement(SchoolChoiceComparator.ADDRESS_SORT, localize("school.sort_address", "Address")); menu.addMenuElement(SchoolChoiceComparator.GENDER_SORT, localize("school.sort_gender", "Gender")); if (action != ACTION_SAVE && yearAge >= 12) menu.addMenuElement(SchoolChoiceComparator.LANGUAGE_SORT, localize("school.sort_language", "Language")); menu.setSelectedElement(sortChoicesBy); menu.setToSubmit(); table.add(menu, 2, 3); table.setColumnAlignment(2, Table.HORIZONTAL_ALIGN_RIGHT); return table; } private void saveClass(IWContext iwc) throws RemoteException { String[] applications = iwc.getParameterValues(PARAMETER_APPLICANT_ID); String[] students = iwc.getParameterValues(getSession().getParameterStudentID()); IWTimestamp stamp = new IWTimestamp(); int userID = ((Integer) iwc.getCurrentUser().getPrimaryKey()).intValue(); SchoolClassMember member; SchoolSeason previousSeason = getBusiness().getPreviousSchoolSeason(getSchoolSeasonID()); getBusiness().resetSchoolClassStatus(getSchoolClassID()); if (applications != null && applications.length > 0) { for (int a = 0; a < applications.length; a++) { StringTokenizer tokens = new StringTokenizer(applications[a], ","); member = getBusiness().getSchoolBusiness().storeSchoolClassMember(Integer.parseInt(tokens.nextToken()), getSchoolClassID(), stamp.getTimestamp(), userID); getBusiness().getSchoolChoiceBusiness().groupPlaceAction(new Integer(tokens.nextToken()), iwc.getCurrentUser()); if (member != null) getBusiness().importStudentInformationToNewClass(member, previousSeason); } } if (students != null && students.length > 0) { for (int a = 0; a < students.length; a++) { member = getBusiness().getSchoolBusiness().storeSchoolClassMember(Integer.parseInt(students[a]), getSchoolClassID(), stamp.getTimestamp(), userID); if (member != null) getBusiness().importStudentInformationToNewClass(member, previousSeason); } } } private void delete(IWContext iwc) throws RemoteException { String student = iwc.getParameter(PARAMETER_APPLICANT_ID); if (student != null && student.length() > 0) { getBusiness().getSchoolBusiness().removeSchoolClassMemberFromClass(Integer.parseInt(student),getSchoolClassID()); SchoolChoice choice = getBusiness().getSchoolChoiceBusiness().findByStudentAndSchoolAndSeason(Integer.parseInt(student), getSchoolID(), getSchoolSeasonID()); getBusiness().setNeedsSpecialAttention(Integer.parseInt(student), getBusiness().getPreviousSchoolSeasonID(getSchoolSeasonID()),false); if (choice != null) getBusiness().getSchoolChoiceBusiness().setAsPreliminary(choice, iwc.getCurrentUser()); } } private void finalize(IWContext iwc) throws RemoteException { int schoolClassID = getSchoolClassID(); SchoolClass schoolClass = getBusiness().getSchoolBusiness().findSchoolClass(new Integer(schoolClassID)); if (schoolClass != null) { if (schoolClass.getReady()) { getBusiness().markSchoolClassLocked(schoolClass); getBusiness().finalizeGroup(schoolClass, localize("school.finalize_subject", ""), localize("school.finalize_body", ""), true); } else { getBusiness().markSchoolClassReady(schoolClass); getBusiness().finalizeGroup(schoolClass, localize("school.students_put_in_class_subject", ""), localize("school.students_put_in_class_body", ""), false); } } } private void validateSchoolClass(Collection previousClasses) throws RemoteException { SchoolClass previousClass = getBusiness().getSchoolBusiness().findSchoolClass(new Integer(_previousSchoolClassID)); if (previousClass != null && !previousClasses.contains(previousClass)) _previousSchoolClassID = -1; } private UserBusiness getUserBusiness(IWContext iwc) throws RemoteException { return (UserBusiness) IBOLookup.getServiceInstance(iwc, UserBusiness.class); } private SchoolChoiceHome getSchoolChoiceHome() throws RemoteException { return (SchoolChoiceHome) com.idega.data.IDOLookup.getHome(SchoolChoice.class); } /** setters */ public void setMultipleSchools(boolean multiple) { this.multibleSchools = multiple; } public void setShowStudentTable(boolean show) { this.showStudentTable = show; } public void setSearchEnabled(boolean searchEnabled) { this.searchEnabled = searchEnabled; } public void setShowStatistics(boolean show) { this.showStatistics = show; } } \ No newline at end of file
false
false
null
null
diff --git a/package/tecla/addon/TeclaAccessibilityService.java b/package/tecla/addon/TeclaAccessibilityService.java index 46c472a..8758a59 100644 --- a/package/tecla/addon/TeclaAccessibilityService.java +++ b/package/tecla/addon/TeclaAccessibilityService.java @@ -1,561 +1,559 @@ package com.android.tecla.addon; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.locks.ReentrantLock; import com.android.tecla.addon.SwitchEventProvider.LocalBinder; import ca.idi.tecla.sdk.SwitchEvent; import ca.idi.tecla.sdk.SEPManager; import ca.idrc.tecla.framework.TeclaStatic; import ca.idrc.tecla.highlighter.TeclaHighlighter; import android.accessibilityservice.AccessibilityService; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.graphics.Rect; import android.os.Bundle; import android.os.IBinder; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; public class TeclaAccessibilityService extends AccessibilityService { private final static String CLASS_TAG = "TeclaA11yService"; public final static int DIRECTION_UP = 0; public final static int DIRECTION_LEFT = 1; public final static int DIRECTION_RIGHT = 2; public final static int DIRECTION_DOWN = 3; private final static int DIRECTION_UP_NORATIOCONSTRAINT = 4; private final static int DIRECTION_LEFT_NORATIOCONSTRAINT = 5; private final static int DIRECTION_RIGHT_NORATIOCONSTRAINT = 6; private final static int DIRECTION_DOWN_NORATIOCONSTRAINT = 7; private final static int DIRECTION_ANY = 8; private static TeclaAccessibilityService sInstance; private Boolean register_receiver_called; private AccessibilityNodeInfo mOriginalNode, mPreviousOriginalNode; protected AccessibilityNodeInfo mSelectedNode; private ArrayList<AccessibilityNodeInfo> mActiveNodes; private int mNodeIndex; private TeclaVisualOverlay mVisualOverlay; private SingleSwitchTouchInterface mFullscreenSwitch; protected static ReentrantLock mActionLock; @Override protected void onServiceConnected() { super.onServiceConnected(); TeclaStatic.logD(CLASS_TAG, "Service " + TeclaAccessibilityService.class.getName() + " connected"); init(); } private void init() { register_receiver_called = false; mOriginalNode = null; mActiveNodes = new ArrayList<AccessibilityNodeInfo>(); mActionLock = new ReentrantLock(); if(mVisualOverlay == null) { mVisualOverlay = new TeclaVisualOverlay(this); TeclaApp.setVisualOverlay(mVisualOverlay); } if (mFullscreenSwitch == null) { mFullscreenSwitch = new SingleSwitchTouchInterface(this); TeclaApp.setFullscreenSwitch(mFullscreenSwitch); } // Bind to SwitchEventProvider Intent intent = new Intent(this, SwitchEventProvider.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); registerReceiver(mReceiver, new IntentFilter(SwitchEvent.ACTION_SWITCH_EVENT_RECEIVED)); register_receiver_called = true; SEPManager.start(this); sInstance = this; TeclaApp.setA11yserviceInstance(this); } public void hideFullscreenSwitch() { if (mFullscreenSwitch != null) { if (mFullscreenSwitch.isVisible()) { mFullscreenSwitch.hide(); } } } public void showFullscreenSwitch() { if (mFullscreenSwitch != null) { if (!mFullscreenSwitch.isVisible()) { mFullscreenSwitch.show(); } } } @Override public void onAccessibilityEvent(AccessibilityEvent event) { if (TeclaApp.getInstance().isSupportedIMERunning()) { if (mVisualOverlay.isVisible()) { int event_type = event.getEventType(); TeclaStatic.logD(CLASS_TAG, AccessibilityEvent.eventTypeToString(event_type) + ": " + event.getText()); AccessibilityNodeInfo node = event.getSource(); if (node != null) { if (event_type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { mPreviousOriginalNode = mOriginalNode; mOriginalNode = node; mNodeIndex = 0; searchAndUpdateNodes(); } else if (event_type == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) { mPreviousOriginalNode = mOriginalNode; mOriginalNode = node; mNodeIndex = 0; searchAndUpdateNodes(); } else if (event_type == AccessibilityEvent.TYPE_VIEW_FOCUSED) { if(mSelectedNode.getClassName().toString().contains("EditText")) TeclaApp.ime.showWindow(true); //searchAndUpdateNodes(); } else if (event_type == AccessibilityEvent.TYPE_VIEW_SELECTED) { //searchAndUpdateNodes(); } else if(event_type == AccessibilityEvent.TYPE_VIEW_SCROLLED) { mPreviousOriginalNode = mOriginalNode; mOriginalNode = node; mNodeIndex = 0; searchAndUpdateNodes(); } else if (event_type == AccessibilityEvent.TYPE_VIEW_CLICKED) { //searchAndUpdateNodes(); } } else { TeclaStatic.logD(CLASS_TAG, "Node is null!"); } } } } private void searchAndUpdateNodes() { // TeclaHighlighter.clearHighlight(); searchActiveNodesBFS(mOriginalNode); if (mActiveNodes.size() > 0 ) { mSelectedNode = findNeighbourNode(mSelectedNode, DIRECTION_ANY); if(mSelectedNode == null) mSelectedNode = mActiveNodes.get(0); TeclaApp.overlay.highlightNode(mSelectedNode); if(mPreviousOriginalNode != null) mPreviousOriginalNode.recycle(); } // TeclaHighlighter.highlightNode(mActiveNodes.get(0)); } private void searchActiveNodesBFS(AccessibilityNodeInfo node) { mActiveNodes.clear(); Queue<AccessibilityNodeInfo> q = new LinkedList<AccessibilityNodeInfo>(); q.add(node); while (!q.isEmpty()) { AccessibilityNodeInfo thisnode = q.poll(); if(thisnode == null) continue; if(thisnode.isVisibleToUser() && thisnode.isClickable() && !thisnode.isScrollable()) { //if(thisnode.isFocused() || thisnode.isSelected()) { mActiveNodes.add(thisnode); //} } for (int i=0; i<thisnode.getChildCount(); ++i) q.add(thisnode.getChild(i)); } } private void sortAccessibilityNodes(ArrayList<AccessibilityNodeInfo> nodes) { ArrayList<AccessibilityNodeInfo> sorted = new ArrayList<AccessibilityNodeInfo>(); Rect bounds_unsorted_node = new Rect(); Rect bounds_sorted_node = new Rect(); boolean inserted = false; for(AccessibilityNodeInfo node: nodes) { if(sorted.size() == 0) sorted.add(node); else { node.getBoundsInScreen(bounds_unsorted_node); inserted = false; for (int i=0; i<sorted.size() && !inserted; ++i) { sorted.get(i).getBoundsInScreen(bounds_sorted_node); if(bounds_sorted_node.centerY() > bounds_unsorted_node.centerY()) { sorted.add(i, node); inserted = true; } else if (bounds_sorted_node.centerY() == bounds_unsorted_node.centerY()) { if(bounds_sorted_node.centerX() > bounds_unsorted_node.centerX()) { sorted.add(i, node); inserted = true; } } } if(!inserted) sorted.add(node); } } nodes.clear(); nodes = sorted; } public static void selectNode(int direction ) { selectNode(sInstance.mSelectedNode, direction ); } public static void selectNode(AccessibilityNodeInfo refnode, int direction ) { NodeSelectionThread thread = new NodeSelectionThread(refnode, direction); thread.start(); } private static AccessibilityNodeInfo findNeighbourNode(AccessibilityNodeInfo refnode, int direction) { int r2_min = Integer.MAX_VALUE; int r2; double ratio; Rect refOutBounds = new Rect(); if(refnode == null) return null; refnode.getBoundsInScreen(refOutBounds); int x = refOutBounds.centerX(); int y = refOutBounds.centerY(); Rect outBounds = new Rect(); AccessibilityNodeInfo result = null; for (AccessibilityNodeInfo node: sInstance.mActiveNodes ) { if(refnode.equals(node) && direction != DIRECTION_ANY) continue; node.getBoundsInScreen(outBounds); r2 = (x - outBounds.centerX())*(x - outBounds.centerX()) + (y - outBounds.centerY())*(y - outBounds.centerY()); switch (direction ) { case DIRECTION_UP: ratio =(y - outBounds.centerY())/Math.sqrt(r2); if(ratio < Math.PI/4) continue; break; case DIRECTION_DOWN: ratio =(outBounds.centerY() - y)/Math.sqrt(r2); if(ratio < Math.PI/4) continue; break; case DIRECTION_LEFT: ratio =(x - outBounds.centerX())/Math.sqrt(r2); if(ratio <= Math.PI/4) continue; break; case DIRECTION_RIGHT: ratio =(outBounds.centerX() - x)/Math.sqrt(r2); if(ratio <= Math.PI/4) continue; break; case DIRECTION_UP_NORATIOCONSTRAINT: if(y - outBounds.centerY() <= 0) continue; break; case DIRECTION_DOWN_NORATIOCONSTRAINT: if(outBounds.centerY() - y <= 0) continue; break; case DIRECTION_LEFT_NORATIOCONSTRAINT: if(x - outBounds.centerX() <= 0) continue; break; case DIRECTION_RIGHT_NORATIOCONSTRAINT: if(outBounds.centerX() - x <= 0) continue; break; case DIRECTION_ANY: break; default: break; } if(r2 < r2_min) { r2_min = r2; result = node; } } return result; } public static void clickActiveNode() { if(sInstance.mActiveNodes.size() == 0) return; if(sInstance.mSelectedNode == null) sInstance.mSelectedNode = sInstance.mActiveNodes.get(0); sInstance.mSelectedNode.performAction(AccessibilityNodeInfo.ACTION_CLICK); if(sInstance.mVisualOverlay.isVisible()) TeclaApp.overlay.clearHighlight(); } // public static void selectActiveNode(int index) { // if(sInstance.mActiveNodes.size()==0) return; // sInstance.mNodeIndex = index; // sInstance.mNodeIndex = Math.min(sInstance.mActiveNodes.size() - 1, sInstance.mNodeIndex + 1); // sInstance.mNodeIndex = Math.max(0, sInstance.mNodeIndex - 1); // TeclaHighlighter.updateNodes(sInstance.mActiveNodes.get(sInstance.mNodeIndex)); // } // // public static void selectPreviousActiveNode() { // if(sInstance.mActiveNodes.size()==0) return; // sInstance.mNodeIndex = Math.max(0, sInstance.mNodeIndex - 1); // TeclaHighlighter.updateNodes(sInstance.mOriginalNode, sInstance.mActiveNodes.get(sInstance.mNodeIndex)); // // } // // public static void selectNextActiveNode() { // if(sInstance.mActiveNodes.size()==0) return; // sInstance.mNodeIndex = Math.min(sInstance.mActiveNodes.size() - 1, sInstance.mNodeIndex + 1); // TeclaHighlighter.updateNodes(sInstance.mOriginalNode, sInstance.mActiveNodes.get(sInstance.mNodeIndex)); // } // private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(SwitchEvent.ACTION_SWITCH_EVENT_RECEIVED)) { handleSwitchEvent(intent.getExtras()); } } }; private boolean isSwitchPressed = false; + private String[] actions = null; private void handleSwitchEvent(Bundle extras) { TeclaStatic.logD(CLASS_TAG, "Received switch event."); SwitchEvent event = new SwitchEvent(extras); if (event.isAnyPressed()) { isSwitchPressed = true; if(TeclaApp.persistence.isInverseScanningEnabled()) { AutomaticScan.startAutoScan(); } } else if(isSwitchPressed) { // on switch released isSwitchPressed = false; if(TeclaApp.persistence.isInverseScanningEnabled()) { if(IMEAdapter.isShowingKeyboard()) IMEAdapter.selectScanHighlighted(); else TeclaHUDOverlay.selectScanHighlighted(); AutomaticScan.stopAutoScan(); } else { - String[] actions = (String[]) extras.get(SwitchEvent.EXTRA_SWITCH_ACTIONS); String action_tecla = actions[0]; int max_node_index = mActiveNodes.size() - 1; switch(Integer.parseInt(action_tecla)) { case SwitchEvent.ACTION_NEXT: if(IMEAdapter.isShowingKeyboard()) IMEAdapter.scanNext(); else mVisualOverlay.scanNext(); break; case SwitchEvent.ACTION_PREV: if(IMEAdapter.isShowingKeyboard()) IMEAdapter.scanPrevious(); else mVisualOverlay.scanPrevious(); break; case SwitchEvent.ACTION_SELECT: if(IMEAdapter.isShowingKeyboard()) IMEAdapter.selectScanHighlighted(); else TeclaHUDOverlay.selectScanHighlighted(); break; case SwitchEvent.ACTION_CANCEL: //TODO: Programmatic back key? default: break; } if(TeclaApp.persistence.isSelfScanningEnabled()) AutomaticScan.setExtendedTimer(); } } } @Override public void onInterrupt() { } @Override public void onDestroy() { super.onDestroy(); shutdownInfrastructure(); } /** * Shuts down the infrastructure in case it has been initialized. */ public void shutdownInfrastructure() { TeclaStatic.logD(CLASS_TAG, "Shutting down infrastructure..."); if (mBound) unbindService(mConnection); SEPManager.stop(getApplicationContext()); if (mVisualOverlay != null) { mVisualOverlay.hide(); } - if (mVisualOverlay != null) { - mVisualOverlay.hide(); - } + if (mFullscreenSwitch != null) { if(mFullscreenSwitch.isVisible()) { mFullscreenSwitch.hide(); } } if (register_receiver_called) { unregisterReceiver(mReceiver); register_receiver_called = false; } } protected static class NodeSelectionThread extends Thread { AccessibilityNodeInfo current_node; int direction; public NodeSelectionThread(AccessibilityNodeInfo node, int dir) { current_node = node; direction = dir; } public void run() { AccessibilityNodeInfo node; if(direction == DIRECTION_UP && isFirstScrollNode(current_node) && !isInsideParent(current_node)) { current_node.getParent().performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); return; } if(direction == DIRECTION_DOWN && isLastScrollNode(current_node) && !isInsideParent(current_node)) { current_node.getParent().performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); return; } mActionLock.lock(); node = findNeighbourNode(current_node, direction ); if(node == null) { switch (direction ) { case DIRECTION_UP: node = findNeighbourNode(current_node, DIRECTION_UP_NORATIOCONSTRAINT); break; case DIRECTION_DOWN: node = findNeighbourNode(current_node, DIRECTION_DOWN_NORATIOCONSTRAINT); break; case DIRECTION_LEFT: node = findNeighbourNode(current_node, DIRECTION_LEFT_NORATIOCONSTRAINT); break; case DIRECTION_RIGHT: node = findNeighbourNode(current_node, DIRECTION_RIGHT_NORATIOCONSTRAINT); break; default: break; } } if(node != null) { sInstance.mSelectedNode = node; if(node.getClassName().toString().contains("EditText")) { node.performAction(AccessibilityNodeInfo.ACTION_FOCUS); } } mActionLock.unlock(); TeclaApp.overlay.highlightNode(sInstance.mSelectedNode); } } public static boolean hasScrollableParent(AccessibilityNodeInfo node) { if(node == null) return false; AccessibilityNodeInfo parent = node.getParent(); if (parent != null) { if(!parent.isScrollable()) return false; } return true; } public static boolean isFirstScrollNode(AccessibilityNodeInfo node) { if(!hasScrollableParent(node)) return false; AccessibilityNodeInfo parent = node.getParent(); AccessibilityNodeInfo firstScrollNode = null; for(int i=0; i<parent.getChildCount(); ++i) { AccessibilityNodeInfo aNode = parent.getChild(i); if(aNode.isVisibleToUser() && aNode.isClickable()) { firstScrollNode = aNode; break; } } return isSameNode(node, firstScrollNode); } public static boolean isLastScrollNode(AccessibilityNodeInfo node) { if(!hasScrollableParent(node)) return false; AccessibilityNodeInfo parent = node.getParent(); AccessibilityNodeInfo lastScrollNode = null; for(int i=parent.getChildCount()-1; i>=0; --i) { AccessibilityNodeInfo aNode = parent.getChild(i); if(aNode.isVisibleToUser() && aNode.isClickable()) { lastScrollNode = aNode; break; } } return isSameNode(node, lastScrollNode); } public static boolean isSameNode(AccessibilityNodeInfo node1, AccessibilityNodeInfo node2) { if(node1 == null || node2 == null) return false; Rect node1_rect = new Rect(); node1.getBoundsInScreen(node1_rect); Rect node2_rect = new Rect(); node1.getBoundsInScreen(node2_rect); if(node1_rect.left == node2_rect.left && node1_rect.right == node2_rect.right && node1_rect.top == node2_rect.top && node1_rect.bottom == node2_rect.bottom) return true; return false; } public static boolean isInsideParent(AccessibilityNodeInfo node) { if(node == null) return false; AccessibilityNodeInfo parent = node.getParent(); if(parent == null) return false; Rect node_rect = new Rect(); Rect parent_rect = new Rect(); node.getBoundsInScreen(node_rect); parent.getBoundsInScreen(parent_rect); if(node_rect.top >= parent_rect.top && node_rect.bottom <= parent_rect.bottom && node_rect.left >= parent_rect.left && node_rect.right <= parent_rect.right) return true; return false; } public void sendGlobalBackAction() { sInstance.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK); } public void sendGlobalHomeAction() { sInstance.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME); } public void sendGlobalNotificationAction() { sInstance.performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS); } public void injectSwitchEvent(SwitchEvent event) { switch_event_provider.injectSwitchEvent(event); } public void injectSwitchEvent(int switchChanges, int switchStates) { switch_event_provider.injectSwitchEvent(switchChanges, switchStates); } SwitchEventProvider switch_event_provider; boolean mBound = false; /** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; switch_event_provider = binder.getService(); mBound = true; TeclaStatic.logD(CLASS_TAG, "IME bound to SEP"); } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; }
false
false
null
null
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/Main.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/Main.java index 141521a1..4980776f 100644 --- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/Main.java +++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/Main.java @@ -1,356 +1,356 @@ /** * Copyright 2007-2011 Zuse Institute Berlin * * 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 de.zib.scalaris.examples.wikipedia.data.xml; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel; import de.zib.scalaris.examples.wikipedia.data.Revision; import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler.ReportAtShutDown; /** * Provides abilities to read an xml wiki dump file and write Wiki pages to * Scalaris. * * @author Nico Kruber, [email protected] */ public class Main { /** * Default blacklist - pages with these names are not imported */ public final static Set<String> blacklist = new HashSet<String>(); /** * The main function of the application. Some articles are blacklisted and * will not be processed (see implementation for a list of them). * * @param args * first argument should be the xml file to convert. */ public static void main(String[] args) { try { String filename = args[0]; if (args.length > 1) { if (args[1].equals("filter")) { doFilter(filename, Arrays.copyOfRange(args, 2, args.length)); } else if (args[1].equals("import")) { doImport(filename, Arrays.copyOfRange(args, 2, args.length), false); } else if (args[1].equals("prepare")) { doImport(filename, Arrays.copyOfRange(args, 2, args.length), true); } } } catch (SAXException e) { System.err.println(e.getMessage()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Imports all pages in the Wikipedia XML dump from the given file to Scalaris. * * @param filename * @param args * @param prepare * * @throws RuntimeException * @throws IOException * @throws SAXException * @throws FileNotFoundException */ private static void doImport(String filename, String[] args, boolean prepare) throws RuntimeException, IOException, SAXException, FileNotFoundException { int maxRevisions = -1; if (args.length >= 1) { try { maxRevisions = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("no number: " + args[0]); System.exit(-1); } } // a timestamp in ISO8601 format Calendar maxTime = null; if (args.length >= 2 && !args[1].isEmpty()) { try { maxTime = Revision.stringToCalendar(args[1]); } catch (IllegalArgumentException e) { System.err.println("no date in ISO8601: " + args[1]); System.exit(-1); } } Set<String> whitelist = null; if (args.length >= 3 && !args[2].isEmpty()) { FileReader inFile = new FileReader(args[2]); BufferedReader br = new BufferedReader(inFile); whitelist = new HashSet<String>(); String line; while ((line = br.readLine()) != null) { if (!line.isEmpty()) { whitelist.add(MyWikiModel.normalisePageTitle(line)); } } if (whitelist.isEmpty()) { whitelist = null; } } if (prepare) { // only prepare the import to Scalaris, i.e. pre-process K/V pairs? String dbFileName = ""; if (args.length >= 4 && !args[3].isEmpty()) { dbFileName = args[3]; } else { System.err.println("need a DB file name for prepare; arguments given: " + Arrays.toString(args)); System.exit(-1); } WikiDumpHandler handler = new WikiDumpPrepareSQLiteForScalarisHandler(blacklist, whitelist, maxRevisions, maxTime, dbFileName); InputSource file = getFileReader(filename); runXmlHandler(handler, file); } else { if (filename.endsWith(".db")) { WikiDumpPreparedSQLiteToScalaris handler = new WikiDumpPreparedSQLiteToScalaris(filename); handler.setUp(); WikiDumpPreparedSQLiteToScalaris.ReportAtShutDown shutdownHook = handler.new ReportAtShutDown(); Runtime.getRuntime().addShutdownHook(shutdownHook); handler.writeToScalaris(); handler.tearDown(); shutdownHook.run(); Runtime.getRuntime().removeShutdownHook(shutdownHook); } else { WikiDumpHandler handler = new WikiDumpToScalarisHandler(blacklist, whitelist, maxRevisions, maxTime); InputSource file = getFileReader(filename); runXmlHandler(handler, file); } } } /** * @param handler * @param file * @throws SAXException * @throws IOException */ static void runXmlHandler(WikiDumpHandler handler, InputSource file) throws SAXException, IOException { XMLReader reader = XMLReaderFactory.createXMLReader(); handler.setUp(); ReportAtShutDown shutdownHook = handler.new ReportAtShutDown(); Runtime.getRuntime().addShutdownHook(shutdownHook); reader.setContentHandler(handler); reader.parse(file); handler.tearDown(); shutdownHook.run(); Runtime.getRuntime().removeShutdownHook(shutdownHook); } /** * Filters all pages in the Wikipedia XML dump from the given file and * creates a list of page names belonging to certain categories. * * @param filename * @param args * * @throws RuntimeException * @throws IOException * @throws SAXException * @throws FileNotFoundException */ private static void doFilter(String filename, String[] args) throws RuntimeException, IOException, SAXException, FileNotFoundException { int recursionLvl = 1; if (args.length >= 1) { try { recursionLvl = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("no number: " + args[0]); System.exit(-1); } } // a timestamp in ISO8601 format Calendar maxTime = null; if (args.length >= 2 && !args[1].isEmpty()) { try { maxTime = Revision.stringToCalendar(args[1]); } catch (IllegalArgumentException e) { System.err.println("no date in ISO8601: " + args[1]); System.exit(-1); } } String pageListFileName = ""; if (args.length >= 3 && !args[2].isEmpty()) { pageListFileName = args[2]; } else { System.err.println("need a pagelist file name for filter; arguments given: " + Arrays.toString(args)); System.exit(-1); } Set<String> allowedPages = new HashSet<String>(); allowedPages.add("Main Page"); allowedPages.add("MediaWiki:Noarticletext"); if (args.length >= 4 && !args[3].isEmpty()) { FileReader inFile = new FileReader(args[3]); BufferedReader br = new BufferedReader(inFile); String line; while ((line = br.readLine()) != null) { if (!line.isEmpty()) { allowedPages.add(MyWikiModel.normalisePageTitle(line)); } } } LinkedList<String> rootCategories = new LinkedList<String>(); if (args.length >= 5) { for (String rCat : Arrays.asList(args).subList(4, args.length)) { if (!rCat.isEmpty()) { rootCategories.add(MyWikiModel.normalisePageTitle(rCat)); } } } System.out.println("filtering by categories " + rootCategories.toString() + " ..."); TreeSet<String> pages = new TreeSet<String>( getPageList(filename, maxTime, allowedPages, rootCategories, recursionLvl)); do { FileWriter outFile = new FileWriter(pageListFileName); PrintWriter out = new PrintWriter(outFile); for (String page : pages) { out.println(page); } out.close(); } while(false); } /** * Extracts all allowed pages in the given root categories as well as those * pages explicitly mentioned in a list of allowed pages. * * Gets the category and template trees from a file, i.e. * <tt>filename + "-trees.db"</tt>, or if this does not exist, builds the * trees and stores them to this file. * * @param filename * the name of the xml wiki dump file * @param maxTime * the maximum time of a revision to use for category parsing * @param categoryTree * the (preferably empty) category tree object * @param templateTree * the (preferably empty) template tree object * * @throws RuntimeException * @throws FileNotFoundException * @throws IOException * @throws SAXException */ protected static Set<String> getPageList(String filename, Calendar maxTime, Set<String> allowedPages, LinkedList<String> rootCategories, int recursionLvl) throws RuntimeException, FileNotFoundException, IOException, SAXException { Map<String, Set<String>> templateTree = new HashMap<String, Set<String>>(); Map<String, Set<String>> includeTree = new HashMap<String, Set<String>>(); Map<String, Set<String>> referenceTree = new HashMap<String, Set<String>>(); File trees = new File(filename + "-trees.db"); if (trees.exists()) { // read trees from tree file System.out.println("reading category tree from " + trees.getName() + " ..."); WikiDumpGetCategoryTreeHandler.readTrees(trees.getName(), templateTree, includeTree, referenceTree); } else { // build trees from xml file // need to get all subcategories recursively, as they must be // included as well System.out.println("building category tree from " + filename + " ..."); WikiDumpGetCategoryTreeHandler handler = new WikiDumpGetCategoryTreeHandler( - blacklist, maxTime, trees.getName()); + blacklist, maxTime, trees.getPath()); InputSource file = getFileReader(filename); runXmlHandler(handler, file); WikiDumpGetCategoryTreeHandler.readTrees(trees.getName(), templateTree, includeTree, referenceTree); } System.out.println("creating list of pages to import (recursion level: " + recursionLvl + ") ..."); Set<String> allowedCats = new HashSet<String>(rootCategories); return WikiDumpGetCategoryTreeHandler.getPagesInCategories( trees.getName(), allowedCats, allowedPages, recursionLvl, templateTree, includeTree, referenceTree); } /** * Gets an appropriate file reader for the given file. * * @param filename * the name of the file * * @return a file reader * * @throws FileNotFoundException * @throws IOException */ public static InputSource getFileReader(String filename) throws FileNotFoundException, IOException { InputStream is; if (filename.endsWith(".xml.gz")) { is = new GZIPInputStream(new FileInputStream(filename)); } else if (filename.endsWith(".xml.bz2")) { is = new BZip2CompressorInputStream(new FileInputStream(filename)); } else if (filename.endsWith(".xml")) { is = new FileInputStream(filename); } else { System.err.println("Unsupported file: " + filename + ". Supported: *.xml.gz, *.xml.bz2, *.xml"); System.exit(-1); return null; // will never be reached but is necessary to keep javac happy } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); return new InputSource(br); } }
true
false
null
null
diff --git a/src/org/mozilla/javascript/Node.java b/src/org/mozilla/javascript/Node.java index bdef8dec..75bc75b5 100644 --- a/src/org/mozilla/javascript/Node.java +++ b/src/org/mozilla/javascript/Node.java @@ -1,1393 +1,1393 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Roshan James * Roger Lawrence * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.util.Map; import java.util.LinkedHashMap; import java.util.Iterator; import java.util.Collections; /** * This class implements the root of the intermediate representation. * * @author Norris Boyd * @author Mike McCabe */ public class Node { public static final int FUNCTION_PROP = 1, LOCAL_PROP = 2, LOCAL_BLOCK_PROP = 3, REGEXP_PROP = 4, CASEARRAY_PROP = 5, /* the following properties are defined and manipulated by the optimizer - TARGETBLOCK_PROP - the block referenced by a branch node VARIABLE_PROP - the variable referenced by a BIND or NAME node ISNUMBER_PROP - this node generates code on Number children and delivers a Number result (as opposed to Objects) DIRECTCALL_PROP - this call node should emit code to test the function - object against the known class and call diret if it + object against the known class and call direct if it matches. */ TARGETBLOCK_PROP = 6, VARIABLE_PROP = 7, ISNUMBER_PROP = 8, DIRECTCALL_PROP = 9, SPECIALCALL_PROP = 10, SKIP_INDEXES_PROP = 11, // array of skipped indexes of array literal OBJECT_IDS_PROP = 12, // array of properties for object literal - INCRDECR_PROP = 13, // pre or post type of increment/decerement + INCRDECR_PROP = 13, // pre or post type of increment/decrement CATCH_SCOPE_PROP = 14, // index of catch scope block in catch LABEL_ID_PROP = 15, // label id: code generation uses it MEMBER_TYPE_PROP = 16, // type of element access operation NAME_PROP = 17, // property name CONTROL_BLOCK_PROP = 18, // flags a control block that can drop off PARENTHESIZED_PROP = 19, // expression is parenthesized GENERATOR_END_PROP = 20, DESTRUCTURING_ARRAY_LENGTH = 21, DESTRUCTURING_NAMES= 22, LAST_PROP = 22; // values of ISNUMBER_PROP to specify // which of the children are Number types public static final int BOTH = 0, LEFT = 1, RIGHT = 2; public static final int // values for SPECIALCALL_PROP NON_SPECIALCALL = 0, SPECIALCALL_EVAL = 1, SPECIALCALL_WITH = 2; public static final int // flags for INCRDECR_PROP DECR_FLAG = 0x1, POST_FLAG = 0x2; public static final int // flags for MEMBER_TYPE_PROP PROPERTY_FLAG = 0x1, // property access: element is valid name ATTRIBUTE_FLAG = 0x2, // x.@y or x..@y DESCENDANTS_FLAG = 0x4; // x..y or x..@i private static class NumberNode extends Node { NumberNode(double number) { super(Token.NUMBER); this.number = number; } double number; } private static class StringNode extends Node { StringNode(int type, String str) { super(type); this.str = str; } String str; Node.Scope scope; } public static class Jump extends Node { public Jump(int type) { super(type); } Jump(int type, int lineno) { super(type, lineno); } Jump(int type, Node child) { super(type, child); } Jump(int type, Node child, int lineno) { super(type, child, lineno); } public final Jump getJumpStatement() { if (!(type == Token.BREAK || type == Token.CONTINUE)) Kit.codeBug(); return jumpNode; } public final void setJumpStatement(Jump jumpStatement) { if (!(type == Token.BREAK || type == Token.CONTINUE)) Kit.codeBug(); if (jumpStatement == null) Kit.codeBug(); if (this.jumpNode != null) Kit.codeBug(); //only once this.jumpNode = jumpStatement; } public final Node getDefault() { if (!(type == Token.SWITCH)) Kit.codeBug(); return target2; } public final void setDefault(Node defaultTarget) { if (!(type == Token.SWITCH)) Kit.codeBug(); if (defaultTarget.type != Token.TARGET) Kit.codeBug(); if (target2 != null) Kit.codeBug(); //only once target2 = defaultTarget; } public final Node getFinally() { if (!(type == Token.TRY)) Kit.codeBug(); return target2; } public final void setFinally(Node finallyTarget) { if (!(type == Token.TRY)) Kit.codeBug(); if (finallyTarget.type != Token.TARGET) Kit.codeBug(); if (target2 != null) Kit.codeBug(); //only once target2 = finallyTarget; } public final Jump getLoop() { if (!(type == Token.LABEL)) Kit.codeBug(); return jumpNode; } public final void setLoop(Jump loop) { if (!(type == Token.LABEL)) Kit.codeBug(); if (loop == null) Kit.codeBug(); if (jumpNode != null) Kit.codeBug(); //only once jumpNode = loop; } public final Node getContinue() { if (type != Token.LOOP) Kit.codeBug(); return target2; } public final void setContinue(Node continueTarget) { if (type != Token.LOOP) Kit.codeBug(); if (continueTarget.type != Token.TARGET) Kit.codeBug(); if (target2 != null) Kit.codeBug(); //only once target2 = continueTarget; } public Node target; private Node target2; private Jump jumpNode; } static class Symbol { Symbol(int declType, String name) { this.declType = declType; this.name = name; this.index = -1; } /** * One of Token.FUNCTION, Token.LP (for parameters), Token.VAR, * Token.LET, or Token.CONST */ int declType; int index; String name; Node.Scope containingTable; } static class Scope extends Jump { public Scope(int nodeType) { super(nodeType); } public Scope(int nodeType, int lineno) { super(nodeType, lineno); } public Scope(int nodeType, Node n, int lineno) { super(nodeType, n, lineno); } /* * Creates a new scope node, moving symbol table information * from "scope" to the new node, and making "scope" a nested * scope contained by the new node. * Useful for injecting a new scope in a scope chain. */ public static Scope splitScope(Scope scope) { Scope result = new Scope(scope.getType()); result.symbolTable = scope.symbolTable; scope.symbolTable = null; result.parent = scope.parent; scope.parent = result; result.top = scope.top; return result; } public static void joinScopes(Scope source, Scope dest) { source.ensureSymbolTable(); dest.ensureSymbolTable(); if (!Collections.disjoint(source.symbolTable.keySet(), dest.symbolTable.keySet())) { throw Kit.codeBug(); } dest.symbolTable.putAll(source.symbolTable); } public void setParent(Scope parent) { this.parent = parent; this.top = parent == null ? (ScriptOrFnNode)this : parent.top; } public Scope getParentScope() { return parent; } public Scope getDefiningScope(String name) { for (Scope sn=this; sn != null; sn = sn.parent) { if (sn.symbolTable == null) continue; if (sn.symbolTable.containsKey(name)) return sn; } return null; } public Symbol getSymbol(String name) { return symbolTable == null ? null : symbolTable.get(name); } public void putSymbol(String name, Symbol symbol) { ensureSymbolTable(); symbolTable.put(name, symbol); symbol.containingTable = this; top.addSymbol(symbol); } public Map<String,Symbol> getSymbolTable() { return symbolTable; } private void ensureSymbolTable() { if (symbolTable == null) { symbolTable = new LinkedHashMap<String,Symbol>(5); } } // Use LinkedHashMap so that the iteration order is the insertion order protected LinkedHashMap<String,Symbol> symbolTable; private Scope parent; private ScriptOrFnNode top; } private static class PropListItem { PropListItem next; int type; int intValue; Object objectValue; } public Node(int nodeType) { type = nodeType; } public Node(int nodeType, Node child) { type = nodeType; first = last = child; child.next = null; } public Node(int nodeType, Node left, Node right) { type = nodeType; first = left; last = right; left.next = right; right.next = null; } public Node(int nodeType, Node left, Node mid, Node right) { type = nodeType; first = left; last = right; left.next = mid; mid.next = right; right.next = null; } public Node(int nodeType, int line) { type = nodeType; lineno = line; } public Node(int nodeType, Node child, int line) { this(nodeType, child); lineno = line; } public Node(int nodeType, Node left, Node right, int line) { this(nodeType, left, right); lineno = line; } public Node(int nodeType, Node left, Node mid, Node right, int line) { this(nodeType, left, mid, right); lineno = line; } public static Node newNumber(double number) { return new NumberNode(number); } public static Node newString(String str) { return new StringNode(Token.STRING, str); } public static Node newString(int type, String str) { return new StringNode(type, str); } public int getType() { return type; } public void setType(int type) { this.type = type; } public boolean hasChildren() { return first != null; } public Node getFirstChild() { return first; } public Node getLastChild() { return last; } public Node getNext() { return next; } public Node getChildBefore(Node child) { if (child == first) return null; Node n = first; while (n.next != child) { n = n.next; if (n == null) throw new RuntimeException("node is not a child"); } return n; } public Node getLastSibling() { Node n = this; while (n.next != null) { n = n.next; } return n; } public void addChildToFront(Node child) { child.next = first; first = child; if (last == null) { last = child; } } public void addChildToBack(Node child) { child.next = null; if (last == null) { first = last = child; return; } last.next = child; last = child; } public void addChildrenToFront(Node children) { Node lastSib = children.getLastSibling(); lastSib.next = first; first = children; if (last == null) { last = lastSib; } } public void addChildrenToBack(Node children) { if (last != null) { last.next = children; } last = children.getLastSibling(); if (first == null) { first = children; } } /** * Add 'child' before 'node'. */ public void addChildBefore(Node newChild, Node node) { if (newChild.next != null) throw new RuntimeException( "newChild had siblings in addChildBefore"); if (first == node) { newChild.next = first; first = newChild; return; } Node prev = getChildBefore(node); addChildAfter(newChild, prev); } /** * Add 'child' after 'node'. */ public void addChildAfter(Node newChild, Node node) { if (newChild.next != null) throw new RuntimeException( "newChild had siblings in addChildAfter"); newChild.next = node.next; node.next = newChild; if (last == node) last = newChild; } public void removeChild(Node child) { Node prev = getChildBefore(child); if (prev == null) first = first.next; else prev.next = child.next; if (child == last) last = prev; child.next = null; } public void replaceChild(Node child, Node newChild) { newChild.next = child.next; if (child == first) { first = newChild; } else { Node prev = getChildBefore(child); prev.next = newChild; } if (child == last) last = newChild; child.next = null; } public void replaceChildAfter(Node prevChild, Node newChild) { Node child = prevChild.next; newChild.next = child.next; prevChild.next = newChild; if (child == last) last = newChild; child.next = null; } private static final String propToString(int propType) { if (Token.printTrees) { // If Context.printTrees is false, the compiler // can remove all these strings. switch (propType) { case FUNCTION_PROP: return "function"; case LOCAL_PROP: return "local"; case LOCAL_BLOCK_PROP: return "local_block"; case REGEXP_PROP: return "regexp"; case CASEARRAY_PROP: return "casearray"; case TARGETBLOCK_PROP: return "targetblock"; case VARIABLE_PROP: return "variable"; case ISNUMBER_PROP: return "isnumber"; case DIRECTCALL_PROP: return "directcall"; case SPECIALCALL_PROP: return "specialcall"; case SKIP_INDEXES_PROP: return "skip_indexes"; case OBJECT_IDS_PROP: return "object_ids_prop"; case INCRDECR_PROP: return "incrdecr_prop"; case CATCH_SCOPE_PROP: return "catch_scope_prop"; case LABEL_ID_PROP: return "label_id_prop"; case MEMBER_TYPE_PROP: return "member_type_prop"; case NAME_PROP: return "name_prop"; case CONTROL_BLOCK_PROP: return "control_block_prop"; case PARENTHESIZED_PROP: return "parenthesized_prop"; case GENERATOR_END_PROP: return "generator_end"; case DESTRUCTURING_ARRAY_LENGTH: return "destructuring_array_length"; case DESTRUCTURING_NAMES:return "destructuring_names"; default: Kit.codeBug(); } } return null; } private PropListItem lookupProperty(int propType) { PropListItem x = propListHead; while (x != null && propType != x.type) { x = x.next; } return x; } private PropListItem ensureProperty(int propType) { PropListItem item = lookupProperty(propType); if (item == null) { item = new PropListItem(); item.type = propType; item.next = propListHead; propListHead = item; } return item; } public void removeProp(int propType) { PropListItem x = propListHead; if (x != null) { PropListItem prev = null; while (x.type != propType) { prev = x; x = x.next; if (x == null) { return; } } if (prev == null) { propListHead = x.next; } else { prev.next = x.next; } } } public Object getProp(int propType) { PropListItem item = lookupProperty(propType); if (item == null) { return null; } return item.objectValue; } public int getIntProp(int propType, int defaultValue) { PropListItem item = lookupProperty(propType); if (item == null) { return defaultValue; } return item.intValue; } public int getExistingIntProp(int propType) { PropListItem item = lookupProperty(propType); if (item == null) { Kit.codeBug(); } return item.intValue; } public void putProp(int propType, Object prop) { if (prop == null) { removeProp(propType); } else { PropListItem item = ensureProperty(propType); item.objectValue = prop; } } public void putIntProp(int propType, int prop) { PropListItem item = ensureProperty(propType); item.intValue = prop; } public int getLineno() { return lineno; } /** Can only be called when <tt>getType() == Token.NUMBER</tt> */ public final double getDouble() { return ((NumberNode)this).number; } public final void setDouble(double number) { ((NumberNode)this).number = number; } /** Can only be called when node has String context. */ public final String getString() { return ((StringNode)this).str; } /** Can only be called when node has String context. */ public final void setString(String s) { if (s == null) Kit.codeBug(); ((StringNode)this).str = s; } /** Can only be called when node has String context. */ public final Scope getScope() { return ((StringNode)this).scope; } /** Can only be called when node has String context. */ public final void setScope(Scope s) { if (s == null) Kit.codeBug(); if (!(this instanceof StringNode)) { throw Kit.codeBug(); } ((StringNode)this).scope = s; } public static Node newTarget() { return new Node(Token.TARGET); } public final int labelId() { if (type != Token.TARGET && type != Token.YIELD) Kit.codeBug(); return getIntProp(LABEL_ID_PROP, -1); } public void labelId(int labelId) { if (type != Token.TARGET && type != Token.YIELD) Kit.codeBug(); putIntProp(LABEL_ID_PROP, labelId); } /** * Does consistent-return analysis on the function body when strict mode is * enabled. * * function (x) { return (x+1) } * is ok, but * function (x) { if (x < 0) return (x+1); } * is not becuase the function can potentially return a value when the * condition is satisfied and if not, the function does not explicitly * return value. * * This extends to checking mismatches such as "return" and "return <value>" * used in the same function. Warnings are not emitted if inconsistent * returns exist in code that can be statically shown to be unreachable. * Ex. * function (x) { while (true) { ... if (..) { return value } ... } } * emits no warning. However if the loop had a break statement, then a * warning would be emitted. * * The consistency analysis looks at control structures such as loops, ifs, * switch, try-catch-finally blocks, examines the reachable code paths and * warns the user about an inconsistent set of termination possibilities. * * Caveat: Since the parser flattens many control structures into almost * straight-line code with gotos, it makes such analysis hard. Hence this * analyser is written to taken advantage of patterns of code generated by * the parser (for loops, try blocks and such) and does not do a full * control flow analysis of the gotos and break/continue statements. * Future changes to the parser will affect this analysis. */ /** * These flags enumerate the possible ways a statement/function can * terminate. These flags are used by endCheck() and by the Parser to * detect inconsistent return usage. * * END_UNREACHED is reserved for code paths that are assumed to always be * able to execute (example: throw, continue) * * END_DROPS_OFF indicates if the statement can transfer control to the * next one. Statement such as return dont. A compound statement may have * some branch that drops off control to the next statement. * * END_RETURNS indicates that the statement can return (without arguments) * END_RETURNS_VALUE indicates that the statement can return a value. * * A compound statement such as * if (condition) { * return value; * } * Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck() */ static final int END_UNREACHED = 0; static final int END_DROPS_OFF = 1; static final int END_RETURNS = 2; static final int END_RETURNS_VALUE = 4; static final int END_YIELDS = 8; /** * Checks that every return usage in a function body is consistent with the * requirements of strict-mode. * @return true if the function satisfies strict mode requirement. */ public boolean hasConsistentReturnUsage() { int n = endCheck(); return (n & END_RETURNS_VALUE) == 0 || (n & (END_DROPS_OFF|END_RETURNS|END_YIELDS)) == 0; } /** * Returns in the then and else blocks must be consistent with each other. * If there is no else block, then the return statement can fall through. * @return logical OR of END_* flags */ private int endCheckIf() { Node th, el; int rv = END_UNREACHED; th = next; el = ((Jump)this).target; rv = th.endCheck(); if (el != null) rv |= el.endCheck(); else rv |= END_DROPS_OFF; return rv; } /** * Consistency of return statements is checked between the case statements. * If there is no default, then the switch can fall through. If there is a * default,we check to see if all code paths in the default return or if * there is a code path that can fall through. * @return logical OR of END_* flags */ private int endCheckSwitch() { Node n; int rv = END_UNREACHED; // examine the cases for (n = first.next; n != null; n = n.next) { if (n.type == Token.CASE) { rv |= ((Jump)n).target.endCheck(); } else break; } // we don't care how the cases drop into each other rv &= ~END_DROPS_OFF; // examine the default n = ((Jump)this).getDefault(); if (n != null) rv |= n.endCheck(); else rv |= END_DROPS_OFF; // remove the switch block rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED); return rv; } /** * If the block has a finally, return consistency is checked in the * finally block. If all code paths in the finally returns, then the * returns in the try-catch blocks don't matter. If there is a code path * that does not return or if there is no finally block, the returns * of the try and catch blocks are checked for mismatch. * @return logical OR of END_* flags */ private int endCheckTry() { Node n; int rv = END_UNREACHED; // check the finally if it exists n = ((Jump)this).getFinally(); if(n != null) { rv = n.next.first.endCheck(); } else { rv = END_DROPS_OFF; } // if the finally block always returns, then none of the returns // in the try or catch blocks matter if ((rv & END_DROPS_OFF) != 0) { rv &= ~END_DROPS_OFF; // examine the try block rv |= first.endCheck(); // check each catch block n = ((Jump)this).target; if (n != null) { // point to the first catch_scope for (n = n.next.first; n != null; n = n.next.next) { // check the block of user code in the catch_scope rv |= n.next.first.next.first.endCheck(); } } } return rv; } /** * Return statement in the loop body must be consistent. The default * assumption for any kind of a loop is that it will eventually terminate. * The only exception is a loop with a constant true condition. Code that * follows such a loop is examined only if one can statically determine * that there is a break out of the loop. * for(<> ; <>; <>) {} * for(<> in <> ) {} * while(<>) { } * do { } while(<>) * @return logical OR of END_* flags */ private int endCheckLoop() { Node n; int rv = END_UNREACHED; // To find the loop body, we look at the second to last node of the // loop node, which should be the predicate that the loop should // satisfy. // The target of the predicate is the loop-body for all 4 kinds of // loops. for (n = first; n.next != last; n = n.next) { /* skip */ } if (n.type != Token.IFEQ) return END_DROPS_OFF; // The target's next is the loop body block rv = ((Jump)n).target.next.endCheck(); // check to see if the loop condition is true if (n.first.type == Token.TRUE) rv &= ~END_DROPS_OFF; // look for effect of breaks rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED); return rv; } /** * A general block of code is examined statement by statement. If any * statement (even compound ones) returns in all branches, then subsequent * statements are not examined. * @return logical OR of END_* flags */ private int endCheckBlock() { Node n; int rv = END_DROPS_OFF; // check each statment and if the statement can continue onto the next // one, then check the next statement for (n=first; ((rv & END_DROPS_OFF) != 0) && n != null; n = n.next) { rv &= ~END_DROPS_OFF; rv |= n.endCheck(); } return rv; } /** * A labelled statement implies that there maybe a break to the label. The * function processes the labelled statement and then checks the * CONTROL_BLOCK_PROP property to see if there is ever a break to the * particular label. * @return logical OR of END_* flags */ private int endCheckLabel() { int rv = END_UNREACHED; rv = next.endCheck(); rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED); return rv; } /** * When a break is encountered annotate the statement being broken * out of by setting its CONTROL_BLOCK_PROP property. * @return logical OR of END_* flags */ private int endCheckBreak() { Node n = ((Jump) this).jumpNode; n.putIntProp(CONTROL_BLOCK_PROP, END_DROPS_OFF); return END_UNREACHED; } /** * endCheck() examines the body of a function, doing a basic reachability * analysis and returns a combination of flags END_* flags that indicate * how the function execution can terminate. These constitute only the * pessimistic set of termination conditions. It is possible that at * runtime certain code paths will never be actually taken. Hence this * analysis will flag errors in cases where there may not be errors. * @return logical OR of END_* flags */ private int endCheck() { switch(type) { case Token.BREAK: return endCheckBreak(); case Token.EXPR_VOID: if (this.first != null) return first.endCheck(); return END_DROPS_OFF; case Token.YIELD: return END_YIELDS; case Token.CONTINUE: case Token.THROW: return END_UNREACHED; case Token.RETURN: if (this.first != null) return END_RETURNS_VALUE; else return END_RETURNS; case Token.TARGET: if (next != null) return next.endCheck(); else return END_DROPS_OFF; case Token.LOOP: return endCheckLoop(); case Token.LOCAL_BLOCK: case Token.BLOCK: // there are several special kinds of blocks if (first == null) return END_DROPS_OFF; switch(first.type) { case Token.LABEL: return first.endCheckLabel(); case Token.IFNE: return first.endCheckIf(); case Token.SWITCH: return first.endCheckSwitch(); case Token.TRY: return first.endCheckTry(); default: return endCheckBlock(); } default: return END_DROPS_OFF; } } public boolean hasSideEffects() { switch (type) { case Token.EXPR_VOID: case Token.COMMA: if (last != null) return last.hasSideEffects(); else return true; case Token.HOOK: if (first == null || first.next == null || first.next.next == null) Kit.codeBug(); return first.next.hasSideEffects() && first.next.next.hasSideEffects(); case Token.ERROR: // Avoid cascaded error messages case Token.EXPR_RESULT: case Token.ASSIGN: case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ENTERWITH: case Token.LEAVEWITH: case Token.RETURN: case Token.GOTO: case Token.IFEQ: case Token.IFNE: case Token.NEW: case Token.DELPROP: case Token.SETNAME: case Token.SETPROP: case Token.SETELEM: case Token.CALL: case Token.THROW: case Token.RETHROW: case Token.SETVAR: case Token.CATCH_SCOPE: case Token.RETURN_RESULT: case Token.SET_REF: case Token.DEL_REF: case Token.REF_CALL: case Token.TRY: case Token.SEMI: case Token.INC: case Token.DEC: case Token.EXPORT: case Token.IMPORT: case Token.IF: case Token.ELSE: case Token.SWITCH: case Token.WHILE: case Token.DO: case Token.FOR: case Token.BREAK: case Token.CONTINUE: case Token.VAR: case Token.CONST: case Token.LET: case Token.LETEXPR: case Token.WITH: case Token.WITHEXPR: case Token.CATCH: case Token.FINALLY: case Token.BLOCK: case Token.LABEL: case Token.TARGET: case Token.LOOP: case Token.JSR: case Token.SETPROP_OP: case Token.SETELEM_OP: case Token.LOCAL_BLOCK: case Token.SET_REF_OP: case Token.YIELD: return true; default: return false; } } @Override public String toString() { if (Token.printTrees) { StringBuffer sb = new StringBuffer(); toString(new ObjToIntMap(), sb); return sb.toString(); } return String.valueOf(type); } private void toString(ObjToIntMap printIds, StringBuffer sb) { if (Token.printTrees) { sb.append(Token.name(type)); if (this instanceof StringNode) { sb.append(' '); sb.append(getString()); Scope scope = getScope(); if (scope != null) { sb.append("[scope: "); appendPrintId(scope, printIds, sb); sb.append("]"); } } else if (this instanceof Node.Scope) { if (this instanceof ScriptOrFnNode) { ScriptOrFnNode sof = (ScriptOrFnNode)this; if (this instanceof FunctionNode) { FunctionNode fn = (FunctionNode)this; sb.append(' '); sb.append(fn.getFunctionName()); } sb.append(" [source name: "); sb.append(sof.getSourceName()); sb.append("] [encoded source length: "); sb.append(sof.getEncodedSourceEnd() - sof.getEncodedSourceStart()); sb.append("] [base line: "); sb.append(sof.getBaseLineno()); sb.append("] [end line: "); sb.append(sof.getEndLineno()); sb.append(']'); } if (((Node.Scope)this).symbolTable != null) { sb.append(" [scope "); appendPrintId(this, printIds, sb); sb.append(": "); Iterator<String> iter = ((Node.Scope) this).symbolTable.keySet().iterator(); while (iter.hasNext()) { sb.append(iter.next()); sb.append(" "); } sb.append("]"); } } else if (this instanceof Jump) { Jump jump = (Jump)this; if (type == Token.BREAK || type == Token.CONTINUE) { sb.append(" [label: "); appendPrintId(jump.getJumpStatement(), printIds, sb); sb.append(']'); } else if (type == Token.TRY) { Node catchNode = jump.target; Node finallyTarget = jump.getFinally(); if (catchNode != null) { sb.append(" [catch: "); appendPrintId(catchNode, printIds, sb); sb.append(']'); } if (finallyTarget != null) { sb.append(" [finally: "); appendPrintId(finallyTarget, printIds, sb); sb.append(']'); } } else if (type == Token.LABEL || type == Token.LOOP || type == Token.SWITCH) { sb.append(" [break: "); appendPrintId(jump.target, printIds, sb); sb.append(']'); if (type == Token.LOOP) { sb.append(" [continue: "); appendPrintId(jump.getContinue(), printIds, sb); sb.append(']'); } } else { sb.append(" [target: "); appendPrintId(jump.target, printIds, sb); sb.append(']'); } } else if (type == Token.NUMBER) { sb.append(' '); sb.append(getDouble()); } else if (type == Token.TARGET) { sb.append(' '); appendPrintId(this, printIds, sb); } if (lineno != -1) { sb.append(' '); sb.append(lineno); } for (PropListItem x = propListHead; x != null; x = x.next) { int type = x.type; sb.append(" ["); sb.append(propToString(type)); sb.append(": "); String value; switch (type) { case TARGETBLOCK_PROP : // can't add this as it recurses value = "target block property"; break; case LOCAL_BLOCK_PROP : // can't add this as it is dull value = "last local block"; break; case ISNUMBER_PROP: switch (x.intValue) { case BOTH: value = "both"; break; case RIGHT: value = "right"; break; case LEFT: value = "left"; break; default: throw Kit.codeBug(); } break; case SPECIALCALL_PROP: switch (x.intValue) { case SPECIALCALL_EVAL: value = "eval"; break; case SPECIALCALL_WITH: value = "with"; break; default: // NON_SPECIALCALL should not be stored throw Kit.codeBug(); } break; case OBJECT_IDS_PROP: { Object[] a = (Object[]) x.objectValue; value = "["; for (int i=0; i < a.length; i++) { value += a[i].toString(); if (i+1 < a.length) value += ", "; } value += "]"; break; } default : Object obj = x.objectValue; if (obj != null) { value = obj.toString(); } else { value = String.valueOf(x.intValue); } break; } sb.append(value); sb.append(']'); } } } public String toStringTree(ScriptOrFnNode treeTop) { if (Token.printTrees) { StringBuffer sb = new StringBuffer(); toStringTreeHelper(treeTop, this, null, 0, sb); return sb.toString(); } return null; } private static void toStringTreeHelper(ScriptOrFnNode treeTop, Node n, ObjToIntMap printIds, int level, StringBuffer sb) { if (Token.printTrees) { if (printIds == null) { printIds = new ObjToIntMap(); generatePrintIds(treeTop, printIds); } for (int i = 0; i != level; ++i) { sb.append(" "); } n.toString(printIds, sb); sb.append('\n'); for (Node cursor = n.getFirstChild(); cursor != null; cursor = cursor.getNext()) { if (cursor.getType() == Token.FUNCTION) { int fnIndex = cursor.getExistingIntProp(Node.FUNCTION_PROP); FunctionNode fn = treeTop.getFunctionNode(fnIndex); toStringTreeHelper(fn, fn, null, level + 1, sb); } else { toStringTreeHelper(treeTop, cursor, printIds, level + 1, sb); } } } } private static void generatePrintIds(Node n, ObjToIntMap map) { if (Token.printTrees) { map.put(n, map.size()); for (Node cursor = n.getFirstChild(); cursor != null; cursor = cursor.getNext()) { generatePrintIds(cursor, map); } } } private static void appendPrintId(Node n, ObjToIntMap printIds, StringBuffer sb) { if (Token.printTrees) { if (n != null) { int id = printIds.get(n, -1); sb.append('#'); if (id != -1) { sb.append(id + 1); } else { sb.append("<not_available>"); } } } } int type; // type of the node; Token.NAME for example Node next; // next sibling private Node first; // first element of a linked list of children private Node last; // last element of a linked list of children protected int lineno = -1; /** * Linked list of properties. Since vast majority of nodes would have * no more then 2 properties, linked list saves memory and provides * fast lookup. If this does not holds, propListHead can be replaced * by UintMap. */ private PropListItem propListHead; }
false
false
null
null
diff --git a/src/de/ueller/midlet/gps/Trace.java b/src/de/ueller/midlet/gps/Trace.java index 4bf8c25..7ddca7a 100644 --- a/src/de/ueller/midlet/gps/Trace.java +++ b/src/de/ueller/midlet/gps/Trace.java @@ -1,1652 +1,1652 @@ package de.ueller.midlet.gps; /* * GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net * See Copying */ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.StreamConnection; //#if polish.api.fileconnection import javax.microedition.io.file.FileConnection; //#endif import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import javax.microedition.midlet.MIDlet; import javax.microedition.rms.RecordStoreException; import javax.microedition.rms.RecordStoreFullException; import javax.microedition.rms.RecordStoreNotOpenException; import de.ueller.gps.data.Configuration; import de.ueller.gps.data.Position; import de.ueller.gps.data.Satelit; import de.ueller.gps.nmea.NmeaInput; import de.ueller.gps.sirf.SirfInput; import de.ueller.gps.tools.HelperRoutines; import de.ueller.gpsMid.mapData.DictReader; import de.ueller.gpsMid.mapData.QueueDataReader; import de.ueller.gpsMid.mapData.QueueDictReader; import de.ueller.gpsMid.mapData.QueueReader; import de.ueller.gpsMid.mapData.Tile; import de.ueller.midlet.gps.data.MapName; import de.ueller.midlet.gps.data.ProjMath; import de.ueller.midlet.gps.data.Gpx; import de.ueller.midlet.gps.data.IntPoint; import de.ueller.midlet.gps.data.Mercator; import de.ueller.midlet.gps.data.MoreMath; import de.ueller.midlet.gps.data.Node; import de.ueller.midlet.gps.data.PositionMark; import de.ueller.midlet.gps.data.Projection; import de.ueller.midlet.gps.names.Names; import de.ueller.midlet.gps.routing.Connection; import de.ueller.midlet.gps.routing.ConnectionWithNode; import de.ueller.midlet.gps.routing.RouteHelper; import de.ueller.midlet.gps.routing.RouteNode; import de.ueller.midlet.gps.routing.Routing; import de.ueller.midlet.gps.tile.C; import de.ueller.midlet.gps.GuiMapFeatures; import de.ueller.midlet.gps.tile.Images; import de.ueller.midlet.gps.tile.PaintContext; import de.ueller.midlet.gps.GpsMidDisplayable; /** * Implements the main "Map" screen which displays the map, offers track recording etc. * @author Harald Mueller * */ public class Trace extends Canvas implements CommandListener, LocationMsgReceiver, Runnable , GpsMidDisplayable{ - /** Soft button for exiting the demo. */ + /** Soft button for exiting the map screen */ private final Command EXIT_CMD = new Command("Back", Command.BACK, 5); private final Command REFRESH_CMD = new Command("Refresh", Command.ITEM, 4); private final Command SEARCH_CMD = new Command("Search", Command.OK, 1); private final Command CONNECT_GPS_CMD = new Command("Start gps",Command.ITEM, 2); private final Command DISCONNECT_GPS_CMD = new Command("Stop gps",Command.ITEM, 2); private final Command START_RECORD_CMD = new Command("Start record",Command.ITEM, 4); private final Command STOP_RECORD_CMD = new Command("Stop record",Command.ITEM, 4); - private final Command TRANSFER_RECORD_CMD = new Command("Manage recorded",Command.ITEM, 5); - private final Command SAVE_WAYP_CMD = new Command("Save waypoint ",Command.ITEM, 7); + private final Command MANAGE_TRACKS_CMD = new Command("Manage tracks",Command.ITEM, 5); + private final Command SAVE_WAYP_CMD = new Command("Save waypoint",Command.ITEM, 7); private final Command MAN_WAYP_CMD = new Command("Manage waypoints",Command.ITEM, 7); private final Command ROUTE_TO_CMD = new Command("Route",Command.ITEM, 3); private final Command CAMERA_CMD = new Command("Camera",Command.ITEM, 9); private final Command SETTARGET_CMD = new Command("As Target",Command.ITEM, 10); private final Command MAPFEATURES_CMD = new Command("Map Features",Command.ITEM, 11); private InputStream inputStream; private StreamConnection conn; // private SirfInput si; private LocationMsgProducer locationProducer; private String solution = "NoFix"; private boolean gpsRecenter = true; private Position pos = new Position(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1, new Date()); Node center = new Node(49.328010f, 11.352556f); Projection projection; private final GpsMid parent; private String lastMsg; private Calendar lastMsgTime = Calendar.getInstance(); private long collected = 0; public PaintContext pc; public float scale = 15000f; int showAddons = 0; private int fontHeight = 0; private static long pressedKeyTime = 0; private static int pressedKeyCode = 0; private static int ignoreKeyCode = 0; private boolean rootCalc=false; Tile t[] = new Tile[6]; PositionMark source; // this is only for visual debugging of the routing engine Vector routeNodes=new Vector(); private final static Logger logger = Logger.getInstance(Trace.class,Logger.DEBUG); //#mdebug info public static final String statMsg[] = { "no Start1:", "no Start2:", "to long :", "interrupt:", "checksum :", "no End1 :", "no End2 :" }; //#enddebug /** * Quality of Bluetooth reception, 0..100. */ private byte btquality; private int[] statRecord; private Satelit[] sat; private Image satelit; /** * Current speed from GPS in km/h. */ private int speed; /** * Current course from GPS in compass degrees, 0..359. */ private int course; private Names namesThread; // private VisibleCollector vc; private ImageCollector imageCollector; private QueueDataReader tileReader; private QueueDictReader dictReader; private Runtime runtime = Runtime.getRuntime(); private PositionMark target; private Vector route=null; private final Configuration config; private Vector recordMark=null; private boolean running=false; private static final int CENTERPOS = Graphics.HCENTER|Graphics.VCENTER; public Gpx gpx; private static Trace traceInstance=null; private Routing routeEngine; private byte arrow; private Image scaledPict = null; private int iPassedRouteArrow=0; private static Font routeFont; private static int routeFontHeight; private static final String[] directions = { "mark", "hard right", "right", "half right", "straight on", "half left", "left", "hard left"}; public Trace(GpsMid parent, Configuration config) throws Exception { //#debug System.out.println("init Trace"); this.config = config; this.parent = parent; addCommand(EXIT_CMD); addCommand(SEARCH_CMD); addCommand(CONNECT_GPS_CMD); addCommand(ROUTE_TO_CMD); addCommand(START_RECORD_CMD); - addCommand(TRANSFER_RECORD_CMD); + addCommand(MANAGE_TRACKS_CMD); addCommand(SAVE_WAYP_CMD); addCommand(MAN_WAYP_CMD); //#if polish.api.mmapi && polish.api.advancedmultimedia addCommand(CAMERA_CMD); //#endif addCommand(SETTARGET_CMD); addCommand(MAPFEATURES_CMD); setCommandListener(this); try { satelit = Image.createImage("/satelit.png"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { startup(); } catch (Exception e) { logger.fatal("Got an exception during startup: " + e.getMessage()); e.printStackTrace(); return; } // setTitle("initTrace ready"); traceInstance = this; } public static Trace getInstance() { return traceInstance; } // start the LocationProvider in background public void run() { try { if (running){ receiveMessage("GPS starter already running"); return; } //#debug info logger.info("start thread init locationprovider"); if (locationProducer != null){ receiveMessage("Location provider already running"); return; } if (config.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE){ receiveMessage("No location provider"); return; } running=true; receiveMessage("Connect to "+Configuration.LOCATIONPROVIDER[config.getLocationProvider()]); // System.out.println(config.getBtUrl()); // System.out.println(config.getRender()); switch (config.getLocationProvider()){ case Configuration.LOCATIONPROVIDER_SIRF: case Configuration.LOCATIONPROVIDER_NMEA: //#debug debug logger.debug("Connect to "+config.getBtUrl()); if (! openBtConnection(config.getBtUrl())){ running=false; return; } } receiveMessage("BT Connected"); //#debug debug logger.debug("rm connect, add disconnect"); removeCommand(CONNECT_GPS_CMD); addCommand(DISCONNECT_GPS_CMD); switch (config.getLocationProvider()){ case Configuration.LOCATIONPROVIDER_SIRF: locationProducer = new SirfInput(); break; case Configuration.LOCATIONPROVIDER_NMEA: locationProducer = new NmeaInput(); //#if polish.api.fileconnection /** * Allow for logging the raw NMEA data coming from the gps mouse */ String url = config.getGpsRawLoggerUrl(); //logger.error("Raw logging url: " + url); if (config.getGpsRawLoggerEnable() && (url != null)) { try { logger.info("Raw NMEA logging to: " + url); url += "rawGpsNMEA" + HelperRoutines.formatSimpleDateNow() + ".txt"; javax.microedition.io.Connection logCon = Connector.open(url); if (logCon instanceof FileConnection) { FileConnection fileCon = (FileConnection)logCon; if (!fileCon.exists()) fileCon.create(); ((NmeaInput)locationProducer).enableRawLogging(((FileConnection)logCon).openOutputStream()); } else { logger.info("Trying to perform raw logging of NMEA on anything else than filesystem is currently not supported"); } } catch (IOException ioe) { logger.exception("Couldn't open file for raw logging of Gps data",ioe); } catch (SecurityException se) { logger.error("Permission to write data for NMEA raw logging was denied"); } } //#endif break; case Configuration.LOCATIONPROVIDER_JSR179: //#if polish.api.locationapi try { String jsr179Version = null; try { jsr179Version = System.getProperty("microedition.location.version"); } catch (RuntimeException re) { /** * Some phones throw exceptions if trying to access properties that don't * exist, so we have to catch these and just ignore them. */ } catch (Exception e) { /** * See above */ } if (jsr179Version != null && jsr179Version.length() > 0) { Class jsr179Class = Class.forName("de.ueller.gps.jsr179.JSR179Input"); locationProducer = (LocationMsgProducer) jsr179Class.newInstance(); } } catch (ClassNotFoundException cnfe) { locationDecoderEnd(); logger.exception("Your phone does not support JSR179, please use a different location provider", cnfe); running = false; return; } //#else // keep eclipse happy if (true){ logger.error("JSR179 is not compiled in this version of GpsMid"); running = false; return; } //#endif break; } if (locationProducer == null) { logger.error("Your phone does not seem to support this method of location input, please choose a different one"); running = false; return; } locationProducer.init(inputStream, this); //#debug info logger.info("end startLocationPovider thread"); // setTitle("lp="+config.getLocationProvider() + " " + config.getBtUrl()); } catch (SecurityException se) { /** * The application was not permitted to connect to the required resources * Not much we can do here other than gracefully shutdown the thread * */ } catch (OutOfMemoryError oome) { logger.fatal("Trace thread crashed as out of memory: " + oome.getMessage()); oome.printStackTrace(); } catch (Exception e) { logger.fatal("Trace thread crashed unexpectadly with error " + e.getMessage()); e.printStackTrace(); } finally { running = false; } running = false; } public synchronized void pause(){ logger.debug("Pausing application"); if (imageCollector != null) { imageCollector.suspend(); } if (locationProducer != null){ locationProducer.close(); } else { return; } while (locationProducer != null){ try { wait(200); } catch (InterruptedException e) { } } } public void resume(){ logger.debug("resuming application"); if (imageCollector != null) { imageCollector.resume(); } Thread thread = new Thread(this); thread.start(); } private boolean openBtConnection(String url){ if (inputStream != null){ return true; } if (url == null) return false; try { conn = (StreamConnection) Connector.open(url); inputStream = conn.openInputStream(); /** * There is at least one, perhaps more BT gps receivers, that * seem to kill the bluetooth connection if we don't send it * something for some reason. Perhaps due to poor powermanagment? * We don't have anything to send, so send an arbitrary 0. */ if (getConfig().getBtKeepAlive()) { final OutputStream os = conn.openOutputStream(); TimerTask tt = new TimerTask() { public void run() { if (os != null) { try { logger.debug("Writing bogus keep-alive"); os.write(0); } catch (IOException e) { logger.info("Closing keep alive timer"); this.cancel(); } } } }; logger.info("Setting keep alive timer: " + t); Timer t = new Timer(); t.schedule(tt, 1000,1000); } } catch (SecurityException se) { /** * The application was not permitted to connect to bluetooth */ receiveMessage("Connectiong to BT not permitted"); return false; } catch (IOException e) { receiveMessage("err BT:"+e.getMessage()); return false; } return true; } public void commandAction(Command c, Displayable d) { try { if (c == EXIT_CMD) { // FIXME: This is a workaround. It would be better if recording would not be stopped when returning to map if (gpx.isRecordingTrk()) { parent.getInstance().alert("Record Mode", "Please stop recording before returning to the map screen." , 2000); return; } if (locationProducer != null){ locationProducer.close(); } if (imageCollector != null) { imageCollector.suspend(); } // shutdown(); pause(); parent.show(); return; } if (! rootCalc){ if (c == START_RECORD_CMD){ try { gpx.newTrk(); removeCommand(START_RECORD_CMD); addCommand(STOP_RECORD_CMD); } catch (RuntimeException e) { receiveMessage(e.getMessage()); } } if (c == STOP_RECORD_CMD){ gpx.saveTrk(); removeCommand(STOP_RECORD_CMD); addCommand(START_RECORD_CMD); - addCommand(TRANSFER_RECORD_CMD); + addCommand(MANAGE_TRACKS_CMD); } - if (c == TRANSFER_RECORD_CMD){ + if (c == MANAGE_TRACKS_CMD){ if (gpx.isRecordingTrk()) { parent.getInstance().alert("Record Mode", "You need to stop recording before managing tracks." , 2000); return; } // if (gpx.isRecordingTrk()) { // gpx.saveTrk(); // removeCommand(STOP_RECORD_CMD); // addCommand(START_RECORD_CMD); // } if (imageCollector != null) { imageCollector.suspend(); } GuiGpx gpx = new GuiGpx(this); gpx.show(); } if (c == REFRESH_CMD) { repaint(0, 0, getWidth(), getHeight()); } if (c == CONNECT_GPS_CMD){ if (locationProducer == null){ Thread thread = new Thread(this); thread.start(); } } if (c == SEARCH_CMD){ if (imageCollector != null) { imageCollector.suspend(); } GuiSearch search = new GuiSearch(this); search.show(); } if (c == DISCONNECT_GPS_CMD){ pause(); } if (c == ROUTE_TO_CMD){ if (config.isStopAllWhileRouteing()){ stopImageCollector(); } System.out.println("Routing source: " + source); routeNodes=new Vector(); routeEngine = new Routing(t,this); routeEngine.solve(source, pc.target); // resume(); } if (c == SAVE_WAYP_CMD) { GuiWaypointSave gwps = new GuiWaypointSave(this,new PositionMark(center.radlat, center.radlon)); gwps.show(); } if (c == MAN_WAYP_CMD) { GuiWaypoint gwp = new GuiWaypoint(this); gwp.show(); } if (c == MAPFEATURES_CMD) { GuiMapFeatures gmf = new GuiMapFeatures(this); gmf.show(); repaint(0, 0, getWidth(), getHeight()); } //#if polish.api.mmapi && polish.api.advancedmultimedia if (c == CAMERA_CMD){ if (imageCollector != null) { imageCollector.suspend(); } try { Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera"); Object GuiCameraObject = GuiCameraClass.newInstance(); GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject; cam.init(this, getConfig()); cam.show(); } catch (ClassNotFoundException cnfe) { logger.exception("Your phone does not support the necessary JSRs to use the camera", cnfe); } } + //#endif if (c == SETTARGET_CMD) { if (source != null) { setTarget(source); } } - //#endif } else { logger.error(" currently in route Caclulation"); } } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void startImageCollector() throws Exception { Images i; i = new Images(); pc = new PaintContext(this, i); pc.c = new C(); imageCollector = new ImageCollector(t, this.getWidth(), this.getHeight(), this, i, pc.c); projection = new Mercator(center, scale, getWidth(), getHeight()); pc.setP(projection); pc.center = center.clone(); pc.scale = scale; pc.xSize = this.getWidth(); pc.ySize = this.getHeight(); } private void stopImageCollector(){ cleanup(); imageCollector.stop(); imageCollector=null; System.gc(); } public void startup() throws Exception { // logger.info("reading Data ..."); namesThread = new Names(); new DictReader(this); // Thread thread = new Thread(this); // thread.start(); // logger.info("Create queueDataReader"); tileReader = new QueueDataReader(this); // logger.info("create imageCollector"); dictReader = new QueueDictReader(this); this.gpx = new Gpx(); setDict(gpx, (byte)5); startImageCollector(); } public void shutdown() { try { stopImageCollector(); if (inputStream != null) { inputStream.close(); inputStream = null; } if (namesThread != null) { namesThread.stop(); namesThread = null; } if (dictReader != null) { dictReader.shutdown(); dictReader = null; } if (tileReader != null) { tileReader.shutdown(); tileReader = null; } } catch (IOException e) { } if (locationProducer != null){ locationProducer.close(); } } protected void sizeChanged(int w, int h) { if (imageCollector != null){ logger.info("Size of Canvas changed to " + w + "|" + h); if (w > imageCollector.xSize || h > imageCollector.ySize) { System.out.println(pc.xSize + " | " + pc.ySize); stopImageCollector(); try { startImageCollector(); imageCollector.resume(); imageCollector.newDataReady(); } catch (Exception e) { logger.exception("Could not reinitialise Image Collector after size change", e); } } /** * Recalculate the projection, as it may depends on the size of the screen */ updatePosition(); } } protected void paint(Graphics g) { if (lastMsg != null && getTitle() != null) { if (System.currentTimeMillis() > (lastMsgTime.getTime().getTime() + 5000)) { /** * Be careful with calling setTitle in paint. * setTitle may cause a repaint, which would * cause the painter thread to spinn slowing * everything else down */ setTitle(null); } } try { int yc = 1; int la = 18; getPC(); // cleans the screen g.setColor(C.BACKGROUND_COLOR); g.fillRect(0, 0, this.getWidth(), this.getHeight()); pc.g = g; if (imageCollector != null){ imageCollector.paint(pc); } switch (showAddons) { case 1: showScale(pc); break; case 2: yc = showSpeed(g, yc, la); yc = showDistanceToTarget(g, yc, la); break; case 3: showSatelite(g); break; case 4: yc = showConnectStatistics(g, yc, la); break; case 5: yc = showMemory(g, yc, la); break; default: showAddons = 0; } showMovement(g); g.setColor(0, 0, 0); if (locationProducer != null){ if (gpx.isRecordingTrk()) {// we are recording tracklogs if(fontHeight==0) { fontHeight=g.getFont().getHeight(); } g.setColor(255, 0, 0); g.drawString(gpx.recorded+"r", getWidth() - 1, 1+fontHeight, Graphics.TOP | Graphics.RIGHT); g.setColor(0); } g.drawString(solution, getWidth() - 1, 1, Graphics.TOP | Graphics.RIGHT); } else { g.drawString("Off", getWidth() - 1, 1, Graphics.TOP | Graphics.RIGHT); } if (pc != null){ showTarget(pc); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); // System.out.println("continue .."); } } /** * */ private void getPC() { pc.xSize = this.getWidth(); pc.ySize = this.getHeight(); pc.setP( projection); projection.inverse(pc.xSize, 0, pc.screenRU); projection.inverse(0, pc.ySize, pc.screenLD); pc.target=target; } public void cleanup() { namesThread.cleanup(); tileReader.incUnusedCounter(); dictReader.incUnusedCounter(); } public void searchElement(PositionMark pm) throws Exception{ PaintContext pc = new PaintContext(this, null); // take a bigger angle for lon because of positions near to the pols. Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true); Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true); pc.screenLD=nld; pc.screenRU=nru; pc.target=pm; for (int i=0; i<4; i++){ t[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD); } } private int showConnectStatistics(Graphics g, int yc, int la) { if (statRecord == null) { g.drawString("No stats yet", 0, yc, Graphics.TOP | Graphics.LEFT); return yc+la; } g.setColor(0, 0, 0); //#mdebug info for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) { g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } //#enddebug g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Count : " + collected, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; return yc; } private void showSatelite(Graphics g) { int centerX = getWidth() / 2; int centerY = getHeight() / 2; int dia = Math.min(getWidth(), getHeight()) - 6; int r = dia / 2; g.setColor(255, 50, 50); g.drawArc(centerX - r, centerY - r, dia, dia, 0, 360); if (sat == null) return; for (byte i = 0; i < sat.length; i++) { Satelit s = sat[i]; if (s == null) continue; //This array may be sparsely filled. if (s.id != 0) { double el = s.elev / 180d * Math.PI; double az = s.azimut / 180 * Math.PI; double sr = r * Math.cos(el); if (s.isLocked()) g.setColor(0, 255, 0); else g.setColor(255, 0, 0); int px = centerX + (int) (Math.sin(az) * sr); int py = centerY - (int) (Math.cos(az) * sr); // g.drawString(""+s.id, px, py, // Graphics.BASELINE|Graphics.HCENTER); g.drawImage(satelit, px, py, Graphics.HCENTER | Graphics.VCENTER); py += 9; // draw a bar under image that indicates green/red status and // signal strength g.fillRect(px - 9, py, (int)(s.snr*18.0/100.0), 2); } } // g.drawImage(satelit, 5, 5, 0); } public void showTarget(PaintContext pc){ if (target != null){ pc.getP().forward(target.lat, target.lon, pc.lineP2,true); // System.out.println(target.toString()); pc.g.drawImage(pc.images.IMG_TARGET,pc.lineP2.x,pc.lineP2.y,CENTERPOS); pc.g.setColor(0,0,0); if (target.displayName != null) pc.g.drawString(target.displayName, pc.lineP2.x, pc.lineP2.y+8, Graphics.TOP | Graphics.HCENTER); pc.g.setColor(255,50,50); pc.g.setStrokeStyle(Graphics.DOTTED); pc.g.drawLine(pc.lineP2.x,pc.lineP2.y,pc.xSize/2,pc.ySize/2); showRoute(pc); } if (recordMark != null){ PositionMark pm; pc.g.setStrokeStyle(Graphics.SOLID); pc.g.setColor(255, 100, 100); for (int i=0; i<recordMark.size();i++){ pm = (PositionMark) recordMark.elementAt(i); if (pm.lat < pc.screenLD.radlat) { continue; } if (pm.lon < pc.screenLD.radlon) { continue; } if (pm.lat > pc.screenRU.radlat) { continue; } if (pm.lon > pc.screenRU.radlon) { continue; } pc.getP().forward(pm.lat, pm.lon, pc.lineP2,true); pc.g.drawImage(pc.images.IMG_MARK,pc.lineP2.x,pc.lineP2.y,CENTERPOS); } } } /** * Draws a map scale onto screen. * This calculation is currently horribly * inefficient. There must be a better way * than this. * * @param pc */ public void showScale(PaintContext pc) { Node n1 = new Node(); Node n2 = new Node(); float scale; int scalePx; //Calculate the lat and lon coordinates of two //points that are 35 pixels apart pc.getP().inverse(10, 10, n1); pc.getP().inverse(45, 10, n2); //Calculate the distance between them in meters float d = ProjMath.getDistance(n1, n2); //round this distance up to the nearest 5 or 10 int ordMag = (int)(MoreMath.log(d)/MoreMath.log(10.0f)); if (d < 2.5*MoreMath.pow(10,ordMag)) { scale = 2.5f*MoreMath.pow(10,ordMag); } else if (d < 5*MoreMath.pow(10,ordMag)) { scale = 5*MoreMath.pow(10,ordMag); } else { scale = 10*MoreMath.pow(10,ordMag); } //Calculate how many pixels this distance is apart scalePx = (int)(35.0f*scale/d); //Draw the scale bar pc.g.setColor(0x00000000); pc.g.drawLine(10,10, 10 + scalePx, 10); pc.g.drawLine(10,11, 10 + scalePx, 11); //double line width pc.g.drawLine(10, 8, 10, 13); pc.g.drawLine(10 + scalePx, 8, 10 + scalePx, 13); if (scale > 1000) { pc.g.drawString(Integer.toString((int)(scale/1000.0f)) + "km", 10 + scalePx/2 ,12, Graphics.HCENTER | Graphics.TOP); } else { pc.g.drawString(Integer.toString((int)scale) + "m", 10 + scalePx/2 ,12, Graphics.HCENTER | Graphics.TOP); } } /** * @param pc */ private void showRoute(PaintContext pc) { final int PASSINGDISTANCE=25; ConnectionWithNode c; // Show helper nodes for Routing for (int x=0; x<routeNodes.size();x++){ RouteHelper n=(RouteHelper) routeNodes.elementAt(x); pc.getP().forward(n.node.radlat, n.node.radlon, pc.lineP2,true); pc.g.drawRect(pc.lineP2.x-5, pc.lineP2.y-5, 10, 10); pc.g.drawString(n.name, pc.lineP2.x+7, pc.lineP2.y+5, Graphics.BOTTOM | Graphics.LEFT); } if (route != null && route.size() > 0){ RouteNode lastTo; // find nearest routing arrow (to center of screen) int iNearest=0; if (config.getCfgBitState(config.CFGBIT_ROUTING_HELP)) { c = (ConnectionWithNode) route.elementAt(0); lastTo=c.to; float minimumDistance=99999; float distance=99999; for (int i=1; i<route.size();i++){ c = (ConnectionWithNode) route.elementAt(i); if (c!=null && c.to!=null && lastTo!=null) { // skip connections that are closer than 25 m to the previous one if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) { continue; } distance = ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon); if (distance<minimumDistance) { minimumDistance=distance; iNearest=i; } lastTo=c.to; } } System.out.println("iNearest "+ iNearest + "dist: " + minimumDistance); // if nearest route arrow is closer than PASSINGDISTANCE meters we're currently passing this route arrow if (minimumDistance<PASSINGDISTANCE) { iPassedRouteArrow=iNearest; System.out.println("iPassedRouteArrow "+ iPassedRouteArrow); } else { c = (ConnectionWithNode) route.elementAt(iPassedRouteArrow); // if we got away more than PASSINGDISTANCE m of the previously passed routing arrow if (ProjMath.getDistance(center.radlat, center.radlon, c.to.lat, c.to.lon) >= PASSINGDISTANCE) { // assume we should start to emphasize the next routing arrow now iNearest=iPassedRouteArrow+1; } } } c = (ConnectionWithNode) route.elementAt(0); byte lastEndBearing=c.endBearing; lastTo=c.to; byte a=0; for (int i=1; i<route.size();i++){ c = (ConnectionWithNode) route.elementAt(i); if (c == null){ System.out.println("show Route got null connection"); } if (c.to == null){ System.out.println("show Route got connection with NULL as target"); } if (lastTo == null){ System.out.println("show Route strange lastTo is null"); } if (pc == null){ System.out.println("show Route strange pc is null"); } if (pc.screenLD == null){ System.out.println("show Route strange pc.screenLD is null"); } // skip connections that are closer than 25 m to the previous one if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) { // draw small circle for left out connection pc.g.setColor(0x00FDDF9F); pc.getP().forward(c.to.lat, c.to.lon, pc.lineP2,true); final byte radius=6; pc.g.fillArc(pc.lineP2.x-radius/2,pc.lineP2.y-radius/2,radius,radius,0,359); //System.out.println("Skipped routing arrow " + i); // if this would have been our iNearest, use next one as iNearest if(i==iNearest) iNearest++; continue; } if(i!=iNearest) { if (lastTo.lat < pc.screenLD.radlat) { lastEndBearing=c.endBearing; lastTo=c.to; continue; } if (lastTo.lon < pc.screenLD.radlon) { lastEndBearing=c.endBearing; lastTo=c.to; continue; } if (lastTo.lat > pc.screenRU.radlat) { lastEndBearing=c.endBearing; lastTo=c.to; continue; } if (lastTo.lon > pc.screenRU.radlon) { lastEndBearing=c.endBearing; lastTo=c.to; continue; } } Image pict = pc.images.IMG_MARK; a=0; int turn=(c.startBearing-lastEndBearing) * 2; if (turn > 180) turn -= 360; if (turn < -180) turn += 360; // System.out.println("from: " + lastEndBearing*2 + " to:" +c.startBearing*2+ " turn " + turn); if (turn > 110) { pict=pc.images.IMG_HARDRIGHT; a=1; } else if (turn > 70){ pict=pc.images.IMG_RIGHT; a=2; } else if (turn > 20){ pict=pc.images.IMG_HALFRIGHT; a=3; } else if (turn >= -20){ pict=pc.images.IMG_STRAIGHTON; a=4; } else if (turn >= -70){ pict=pc.images.IMG_HALFLEFT; a=5; } else if (turn >= -110){ pict=pc.images.IMG_LEFT; a=6; } else { pict=pc.images.IMG_HARDLEFT; a=7; } pc.getP().forward(lastTo.lat, lastTo.lon, pc.lineP2,true); // optionally scale nearest arrow if (i==iNearest) { Font originalFont = pc.g.getFont(); if (routeFont==null) { routeFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM); routeFontHeight=routeFont.getHeight(); } pc.g.setFont(routeFont); pc.g.setColor(230,230,230); pc.g.fillRect(0,pc.ySize-15-routeFontHeight, pc.xSize, routeFontHeight); pc.g.setColor(0,0,0); double distance=ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon); int intDistance=new Double(distance).intValue(); pc.g.drawString(directions[a] + ((intDistance<PASSINGDISTANCE)?"":" in " + intDistance + "m"), pc.xSize/2,pc.ySize-15, Graphics.HCENTER | Graphics.BOTTOM ); pc.g.setFont(originalFont); if (a!=arrow) { arrow=a; scaledPict=doubleImage(pict); } pict=scaledPict; } pc.g.drawImage(pict,pc.lineP2.x,pc.lineP2.y,CENTERPOS); lastEndBearing=c.endBearing; lastTo=c.to; } } } public static Image doubleImage(Image original) { int w=original.getWidth(); int h=original.getHeight(); int[] rawInput = new int[w * h]; original.getRGB(rawInput, 0, w, 0, 0, h, h); int[] rawOutput = new int[w*h*4]; int outOffset= 1; int inOffset= 0; int lineInOffset=0; int val=0; for (int y=0;y<h*2;y++) { if((y&1)==1) { outOffset++; inOffset=lineInOffset; } else { outOffset--; lineInOffset=inOffset; } for (int x=0; x<w; x++) { /* unfortunately many devices can draw semitransparent pictures but only support transparent and opaque in their graphics routines. So we just keep full transparency as otherwise the device will convert semitransparent from the png to full transparent pixels making the new picture much too bright */ val=rawInput[inOffset]; if( (val & 0xFF000000) != 0 ) { val|=0xFF000000; } rawOutput[outOffset]=val; /// as a workaround for semitransparency we only draw every 2nd pixel outOffset+=2; inOffset++; } } return Image.createRGBImage(rawOutput, w*2, h*2, true); } public void showMovement(Graphics g) { g.setColor(0, 0, 0); int centerX = getWidth() / 2; int centerY = getHeight() / 2; int posX, posY; if (!gpsRecenter) { IntPoint p1 = new IntPoint(0,0); pc.getP().forward((float)(pos.latitude/360.0*2*Math.PI), (float)(pos.longitude/360.0*2*Math.PI),p1,true); posX = p1.getX(); posY = p1.getY(); } else { posX = centerX; posY = centerY; } float radc = (float) (course * Math.PI / 180d); int px = posX + (int) (Math.sin(radc) * 20); int py = posY - (int) (Math.cos(radc) * 20); g.drawRect(posX - 2, posY - 2, 4, 4); g.drawLine(posX, posY, px, py); g.drawLine(centerX-2, centerY - 2, centerX + 2, centerY + 2); g.drawLine(centerX-2, centerY + 2, centerX + 2, centerY - 2); } public int showMemory(Graphics g, int yc, int la) { g.setColor(0, 0, 0); g.drawString("Freemem: " + runtime.freeMemory(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Totmem: " + runtime.totalMemory(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Percent: " + (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Threads running: " + Thread.activeCount(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Names: " + namesThread.getNameCount(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Single T: " + tileReader.getLivingTilesCount() + "/" + tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("File T: " + dictReader.getLivingTilesCount() + "/" + dictReader.getRequestQueueSize(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("LastMsg: " + lastMsg, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString( "at " + lastMsgTime.get(Calendar.HOUR_OF_DAY) + ":" + HelperRoutines.formatInt2(lastMsgTime.get(Calendar.MINUTE)) + ":" + HelperRoutines.formatInt2(lastMsgTime.get(Calendar.SECOND)), 0, yc, Graphics.TOP | Graphics.LEFT ); return (yc); } public int showSpeed(Graphics g, int yc, int la) { g.setColor(0, 0, 0); g.drawString("speed : " + speed, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("course : " + course, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("height : " + pos.altitude, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; return yc; } public int showDistanceToTarget(Graphics g, int yc, int la) { g.setColor(0, 0, 0); String text; if (target == null) { text = "Distance: N/A"; } else { float distance = ProjMath.getDistance(target.lat, target.lon, center.radlat, center.radlon); if (distance > 10000) { text = "Distance: " + Integer.toString((int)(distance/1000.0f)) + "km"; } else if (distance > 1000) { text = "Distance: " + Float.toString(((int)(distance/100.0f))/10.0f) + "km"; } else { text = "Distance: " + Integer.toString((int)distance) + "m"; } } g.drawString(text , 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; return yc; } private void updatePosition() { if (pc != null){ projection = new Mercator(center, scale, getWidth(), getHeight()); pc.setP(projection); pc.center = center.clone(); pc.scale = scale; repaint(0, 0, getWidth(), getHeight()); } } public synchronized void receivePosItion(float lat, float lon, float scale) { logger.debug("Now displaying: " + (lat*MoreMath.FAC_RADTODEC) + "|" + (lon*MoreMath.FAC_RADTODEC)); center.setLatLon(lat, lon,true); this.scale = scale; updatePosition(); } public synchronized void receivePosItion(Position pos) { logger.info("New position: " + pos); this.pos = pos; collected++; if (gpsRecenter) { center.setLatLon(pos.latitude, pos.longitude); } speed = (int) (pos.speed * 3.6f); if (gpx.isRecordingTrk()){ try { gpx.addTrkPt(pos); } catch (Exception e) { receiveMessage(e.getMessage()); } } course = (int) pos.course; updatePosition(); } public synchronized void receiveMessage(String s) { lastMsg = s; //#debug parent.log(s); setTitle(lastMsg); lastMsgTime.setTime( new Date( System.currentTimeMillis() ) ); } public void receiveStatelit(Satelit[] sat) { this.sat = sat; } public MIDlet getParent() { return parent; } protected void keyRepeated(int keyCode) { // strange seem to be working in emulator only with this debug line logger.debug("keyRepeated " + keyCode); //Scrolling should work with repeated keys the same //as pressing the key multiple times if (keyCode==ignoreKeyCode) { logger.debug("key ignored " + keyCode); return; } int gameActionCode = this.getGameAction(keyCode); if ((gameActionCode == UP) || (gameActionCode == DOWN) || (gameActionCode == RIGHT) || (gameActionCode == LEFT)) { keyPressed(keyCode); return; } if ((keyCode == KEY_NUM2) || (keyCode == KEY_NUM8) || (keyCode == KEY_NUM4) || (keyCode == KEY_NUM6)) { keyPressed(keyCode); return; } long keyTime=System.currentTimeMillis(); // other key is held down if ( (keyTime-pressedKeyTime)>=1000 && pressedKeyCode==keyCode) { if(keyCode == KEY_NUM5) { ignoreKeyCode=keyCode; commandAction(SAVE_WAYP_CMD,(Displayable) null); return; } if(keyCode == KEY_STAR) { ignoreKeyCode=keyCode; commandAction(MAN_WAYP_CMD,(Displayable) null); return; } if(keyCode == KEY_POUND) { ignoreKeyCode=keyCode; - commandAction(TRANSFER_RECORD_CMD,(Displayable) null); + commandAction(MANAGE_TRACKS_CMD,(Displayable) null); return; } if(keyCode == KEY_NUM0) { ignoreKeyCode=keyCode; if ( gpx.isRecordingTrk() ) { GpsMid.getInstance().alert("Gps track recording", "Stopping to record" , 750); commandAction(STOP_RECORD_CMD,(Displayable) null); } else { GpsMid.getInstance().alert("Gps track recording", "Starting to record" , 750); commandAction(START_RECORD_CMD,(Displayable) null); } return; } } } // // manage keys that would have different meanings when // // held down in keyReleased protected void keyReleased(int keyCode) { // if key was not handled as held down key // strange seem to be working in emulator only with this debug line logger.debug("keyReleased " + keyCode); if (keyCode == ignoreKeyCode) { ignoreKeyCode=0; return; } // handle this key normally (shortly pressed) if (keyCode == KEY_NUM5) { gpsRecenter = true; } else if (keyCode == KEY_STAR) { commandAction(MAPFEATURES_CMD,(Displayable) null); return; } else if (keyCode == KEY_POUND) { // toggle Backlight config.setCfgBitState(config.CFGBIT_BACKLIGHT_ON, !(config.getCfgBitState(config.CFGBIT_BACKLIGHT_ON)), false); if ( config.getCfgBitState(config.CFGBIT_BACKLIGHT_ON, false) ) { GpsMid.getInstance().alert("Backlight", "Backlight ON" , 750); } else { GpsMid.getInstance().alert("Backlight", "Backlight off" , 750); } parent.stopBackLightTimer(); parent.startBackLightTimer(); } else if (keyCode == KEY_NUM0) { boolean fullScreen = !config.getCfgBitState(config.CFGBIT_FULLSCREEN); config.setCfgBitState(config.CFGBIT_FULLSCREEN, fullScreen, false); setFullScreenMode(fullScreen); } repaint(0, 0, getWidth(), getHeight()); } protected void keyPressed(int keyCode) { // logger.debug("keyPressed " + keyCode); ignoreKeyCode=0; pressedKeyCode=keyCode; pressedKeyTime=System.currentTimeMillis(); float f = 0.00003f / 15000f; int keyStatus; if (this.getGameAction(keyCode) == UP) { center.radlat += f * scale * 0.1f; gpsRecenter = false; } else if (this.getGameAction(keyCode) == DOWN) { center.radlat -= f * scale * 0.1f; gpsRecenter = false; } else if (this.getGameAction(keyCode) == LEFT) { center.radlon -= f * scale * 0.1f; gpsRecenter = false; } else if (this.getGameAction(keyCode) == RIGHT) { center.radlon += f * scale * 0.1f; gpsRecenter = false; } if (keyCode == KEY_NUM2) { center.radlat += f * scale; } else if (keyCode == KEY_NUM8) { center.radlat -= f * scale; } else if (keyCode == KEY_NUM4) { center.radlon -= f * scale; } else if (keyCode == KEY_NUM6) { center.radlon += f * scale; } else if (keyCode == KEY_NUM1) { scale = scale * 1.5f; } else if (keyCode == KEY_NUM3) { scale = scale / 1.5f; } else if (keyCode == KEY_NUM7) { showAddons++; } else if (keyCode == KEY_NUM9) { course += 5; /** Non standard Key: hopefully is mapped to * the delete / clear key. According to * www.j2meforums.com/wiki/index.php/Canvas_Keycodes * most major mobiles that have this key map to -8 **/ } else if (keyCode == -8) { commandAction(ROUTE_TO_CMD,(Displayable) null); return; //#if polish.api.mmapi && polish.api.advancedmultimedia } else if (keyCode == Configuration.KEYCODE_CAMERA_COVER_OPEN) { if (imageCollector != null) { imageCollector.suspend(); } try { Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera"); Object GuiCameraObject = GuiCameraClass.newInstance(); GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject; cam.init(this, getConfig()); cam.show(); } catch (ClassNotFoundException cnfe) { logger.exception("Your phone does not support the necessary JSRs to use the camera", cnfe); } catch (InstantiationException e) { logger.exception("Your phone does not support the necessary JSRs to use the camera", e); } catch (IllegalAccessException e) { logger.exception("Your phone does not support the necessary JSRs to use the camera", e); } //#endif } else { keyStatus = keyCode; } projection = new Mercator(center, scale, getWidth(), getHeight()); pc.setP(projection); pc.center = center.clone(); pc.scale = scale; repaint(0, 0, getWidth(), getHeight()); } public void setDict(Tile dict, byte zl) { t[zl] = dict; // Tile.trace=this; addCommand(REFRESH_CMD); // if (zl == 3) { // setTitle(null); // } else { // setTitle("dict " + zl + "ready"); // } if (zl == 0) { // read saved position from config config.getStartupPos(center); if(center.radlat==0.0f && center.radlon==0.0f) { // if no saved position use center of map dict.getCenter(center); } projection = new Mercator(center, scale, getWidth(), getHeight()); if (pc != null) { pc.setP(projection); pc.center = center.clone(); pc.scale = scale; } } updatePosition(); } public void receiveStatistics(int[] statRecord, byte quality) { this.btquality = quality; this.statRecord = statRecord; repaint(0, 0, getWidth(), getHeight()); } public synchronized void locationDecoderEnd() { //#debug info logger.info("enter locationDecoderEnd"); if (gpx != null) { /** * Close and Save the gpx recording, to ensure we don't loose data */ gpx.saveTrk(); } removeCommand(DISCONNECT_GPS_CMD); if (locationProducer == null){ //#debug info logger.info("leave locationDecoderEnd no producer"); return; } locationProducer = null; if (inputStream != null){ try { inputStream.close(); } catch (IOException e) { } inputStream=null; } if (conn != null){ try { conn.close(); } catch (IOException e) { } conn=null; inputStream=null; } notify(); addCommand(CONNECT_GPS_CMD); //#debug info logger.info("end locationDecoderEnd"); } public void receiveSolution(String s) { solution = s; } public String getName(int idx) { if (idx < 0) return null; return namesThread.getName(idx); } public void requestRedraw() { repaint(0, 0, getWidth(), getHeight()); } public void newDataReady() { if (imageCollector != null) imageCollector.newDataReady(); } public void show() { //Display.getDisplay(parent).setCurrent(this); GpsMid.getInstance().show(this); setFullScreenMode(config.getCfgBitState(config.CFGBIT_FULLSCREEN)); if (imageCollector != null) { imageCollector.resume(); imageCollector.newDataReady(); } requestRedraw(); } public Configuration getConfig() { return config; } public void locationDecoderEnd(String msg) { receiveMessage(msg); locationDecoderEnd(); } public PositionMark getTarget() { return target; } public void setTarget(PositionMark target) { this.target = target; pc.target = target; center.setLatLon(target.lat, target.lon,true); projection = new Mercator(center, scale, getWidth(), getHeight()); pc.setP( projection); pc.center = center.clone(); pc.scale = scale; repaint(0, 0, getWidth(), getHeight()); } /** * This is the callback routine if RouteCalculation is ready * @param route */ public void setRoute(Vector route) { this.route = route; rootCalc=false; routeEngine=null; try { if (config.isStopAllWhileRouteing()){ startImageCollector(); // imageCollector thread starts up suspended, // so we need to resume it imageCollector.resume(); } else { // resume(); } iPassedRouteArrow=0; repaint(0, 0, getWidth(), getHeight()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * If we are running out of memory, try * dropping all the caches in order to try * and recover from out of memory errors. * Not guaranteed to work, as it needs * to allocate some memory for dropping * caches. */ public void dropCache() { tileReader.dropCache(); dictReader.dropCache(); System.gc(); namesThread.dropCache(); System.gc(); if (gpx != null) { gpx.dropCache(); } } public QueueDataReader getDataReader() { return tileReader; } public QueueDictReader getDictReader() { return dictReader; } public Vector getRouteNodes() { return routeNodes; } public void setRouteNodes(Vector routeNodes) { this.routeNodes = routeNodes; } protected void hideNotify() { logger.info("Hide notify has been called, screen will nolonger be updated"); } protected void showNotify() { logger.info("Show notify has been called, screen will be updated again"); } }
false
false
null
null
diff --git a/core/java/android/widget/AlphabetIndexer.java b/core/java/android/widget/AlphabetIndexer.java index 4e466a09..f50676ab 100644 --- a/core/java/android/widget/AlphabetIndexer.java +++ b/core/java/android/widget/AlphabetIndexer.java @@ -1,282 +1,282 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget; import android.database.Cursor; import android.database.DataSetObserver; import android.util.SparseIntArray; /** * A helper class for adapters that implement the SectionIndexer interface. * If the items in the adapter are sorted by simple alphabet-based sorting, then * this class provides a way to do fast indexing of large lists using binary search. * It caches the indices that have been determined through the binary search and also * invalidates the cache if changes occur in the cursor. * <p/> * Your adapter is responsible for updating the cursor by calling {@link #setCursor} if the * cursor changes. {@link #getPositionForSection} method does the binary search for the starting * index of a given section (alphabet). */ public class AlphabetIndexer extends DataSetObserver implements SectionIndexer { /** * Cursor that is used by the adapter of the list view. */ protected Cursor mDataCursor; /** * The index of the cursor column that this list is sorted on. */ protected int mColumnIndex; /** * The string of characters that make up the indexing sections. */ protected CharSequence mAlphabet; /** * Cached length of the alphabet array. */ private int mAlphabetLength; /** * This contains a cache of the computed indices so far. It will get reset whenever * the dataset changes or the cursor changes. */ private SparseIntArray mAlphaMap; /** * Use a collator to compare strings in a localized manner. */ private java.text.Collator mCollator; /** * The section array converted from the alphabet string. */ private String[] mAlphabetArray; /** * Constructs the indexer. * @param cursor the cursor containing the data set * @param sortedColumnIndex the column number in the cursor that is sorted * alphabetically * @param alphabet string containing the alphabet, with space as the first character. * For example, use the string " ABCDEFGHIJKLMNOPQRSTUVWXYZ" for English indexing. * The characters must be uppercase and be sorted in ascii/unicode order. Basically * characters in the alphabet will show up as preview letters. */ public AlphabetIndexer(Cursor cursor, int sortedColumnIndex, CharSequence alphabet) { mDataCursor = cursor; mColumnIndex = sortedColumnIndex; mAlphabet = alphabet; mAlphabetLength = alphabet.length(); mAlphabetArray = new String[mAlphabetLength]; for (int i = 0; i < mAlphabetLength; i++) { mAlphabetArray[i] = Character.toString(mAlphabet.charAt(i)); } mAlphaMap = new SparseIntArray(mAlphabetLength); if (cursor != null) { cursor.registerDataSetObserver(this); } // Get a Collator for the current locale for string comparisons. mCollator = java.text.Collator.getInstance(); mCollator.setStrength(java.text.Collator.PRIMARY); } /** * Returns the section array constructed from the alphabet provided in the constructor. * @return the section array */ public Object[] getSections() { return mAlphabetArray; } /** * Sets a new cursor as the data set and resets the cache of indices. * @param cursor the new cursor to use as the data set */ public void setCursor(Cursor cursor) { if (mDataCursor != null) { mDataCursor.unregisterDataSetObserver(this); } mDataCursor = cursor; if (cursor != null) { mDataCursor.registerDataSetObserver(this); } mAlphaMap.clear(); } /** * Default implementation compares the first character of word with letter. */ protected int compare(String word, String letter) { return mCollator.compare(word.substring(0, 1), letter); } /** * Performs a binary search or cache lookup to find the first row that * matches a given section's starting letter. * @param sectionIndex the section to search for * @return the row index of the first occurrence, or the nearest next letter. * For instance, if searching for "T" and no "T" is found, then the first * row starting with "U" or any higher letter is returned. If there is no * data following "T" at all, then the list size is returned. */ public int getPositionForSection(int sectionIndex) { final SparseIntArray alphaMap = mAlphaMap; final Cursor cursor = mDataCursor; if (cursor == null || mAlphabet == null) { return 0; } // Check bounds if (sectionIndex <= 0) { return 0; } if (sectionIndex >= mAlphabetLength) { sectionIndex = mAlphabetLength - 1; } int savedCursorPos = cursor.getPosition(); int count = cursor.getCount(); int start = 0; int end = count; int pos; char letter = mAlphabet.charAt(sectionIndex); String targetLetter = Character.toString(letter); int key = letter; // Check map if (Integer.MIN_VALUE != (pos = alphaMap.get(key, Integer.MIN_VALUE))) { // Is it approximate? Using negative value to indicate that it's // an approximation and positive value when it is the accurate // position. if (pos < 0) { pos = -pos; end = pos; } else { // Not approximate, this is the confirmed start of section, return it return pos; } } // Do we have the position of the previous section? if (sectionIndex > 0) { int prevLetter = mAlphabet.charAt(sectionIndex - 1); int prevLetterPos = alphaMap.get(prevLetter, Integer.MIN_VALUE); if (prevLetterPos != Integer.MIN_VALUE) { start = Math.abs(prevLetterPos); } } // Now that we have a possibly optimized start and end, let's binary search pos = (end + start) / 2; while (pos < end) { // Get letter at pos cursor.moveToPosition(pos); String curName = cursor.getString(mColumnIndex); if (curName == null) { if (pos == 0) { break; } else { pos--; continue; } } int diff = compare(curName, targetLetter); if (diff != 0) { // Commenting out approximation code because it doesn't work for certain // lists with custom comparators // Enter approximation in hash if a better solution doesn't exist // String startingLetter = Character.toString(getFirstLetter(curName)); // int startingLetterKey = startingLetter.charAt(0); // int curPos = alphaMap.get(startingLetterKey, Integer.MIN_VALUE); // if (curPos == Integer.MIN_VALUE || Math.abs(curPos) > pos) { // Negative pos indicates that it is an approximation // alphaMap.put(startingLetterKey, -pos); // } // if (mCollator.compare(startingLetter, targetLetter) < 0) { if (diff < 0) { start = pos + 1; if (start >= count) { pos = count; break; } } else { end = pos; } } else { // They're the same, but that doesn't mean it's the start if (start == pos) { // This is it break; } else { // Need to go further lower to find the starting row end = pos; } } pos = (start + end) / 2; } alphaMap.put(key, pos); cursor.moveToPosition(savedCursorPos); return pos; } /** * Returns the section index for a given position in the list by querying the item * and comparing it with all items in the section array. */ public int getSectionForPosition(int position) { int savedCursorPos = mDataCursor.getPosition(); mDataCursor.moveToPosition(position); - mDataCursor.moveToPosition(savedCursorPos); String curName = mDataCursor.getString(mColumnIndex); + mDataCursor.moveToPosition(savedCursorPos); // Linear search, as there are only a few items in the section index // Could speed this up later if it actually gets used. for (int i = 0; i < mAlphabetLength; i++) { char letter = mAlphabet.charAt(i); String targetLetter = Character.toString(letter); if (compare(curName, targetLetter) == 0) { return i; } } return 0; // Don't recognize the letter - falls under zero'th section } /* * @hide */ @Override public void onChanged() { super.onChanged(); mAlphaMap.clear(); } /* * @hide */ @Override public void onInvalidated() { super.onInvalidated(); mAlphaMap.clear(); } }
false
false
null
null
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPerDocProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPerDocProducer.java index 94eaa4b95..88f91c3b7 100644 --- a/lucene/core/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPerDocProducer.java +++ b/lucene/core/src/java/org/apache/lucene/codecs/simpletext/SimpleTextPerDocProducer.java @@ -1,431 +1,431 @@ package org.apache.lucene.codecs.simpletext; /** * 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. */ import static org.apache.lucene.codecs.simpletext.SimpleTextDocValuesConsumer.DOC; import static org.apache.lucene.codecs.simpletext.SimpleTextDocValuesConsumer.END; import static org.apache.lucene.codecs.simpletext.SimpleTextDocValuesConsumer.HEADER; import static org.apache.lucene.codecs.simpletext.SimpleTextDocValuesConsumer.VALUE; import static org.apache.lucene.codecs.simpletext.SimpleTextDocValuesConsumer.VALUE_SIZE; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import org.apache.lucene.codecs.DocValuesArraySource; import org.apache.lucene.codecs.PerDocProducerBase; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.DocValues.SortedSource; import org.apache.lucene.index.DocValues.Source; import org.apache.lucene.index.DocValues.Type; import org.apache.lucene.index.IndexFileNames; import org.apache.lucene.index.SegmentReadState; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.StringHelper; import org.apache.lucene.util.packed.PackedInts.Reader; /** * @lucene.experimental */ public class SimpleTextPerDocProducer extends PerDocProducerBase { protected final TreeMap<String, DocValues> docValues; private Comparator<BytesRef> comp; private final String segmentSuffix; /** - * Creates a new {@link Lucene40DocValuesProducer} instance and loads all + * Creates a new {@link SimpleTextPerDocProducer} instance and loads all * {@link DocValues} instances for this segment and codec. */ public SimpleTextPerDocProducer(SegmentReadState state, Comparator<BytesRef> comp, String segmentSuffix) throws IOException { this.comp = comp; this.segmentSuffix = segmentSuffix; if (anyDocValuesFields(state.fieldInfos)) { docValues = load(state.fieldInfos, state.segmentInfo.name, state.segmentInfo.docCount, state.dir, state.context); } else { docValues = new TreeMap<String, DocValues>(); } } @Override protected Map<String, DocValues> docValues() { return docValues; } protected DocValues loadDocValues(int docCount, Directory dir, String id, DocValues.Type type, IOContext context) throws IOException { return new SimpleTextDocValues(dir, context, type, id, docCount, comp, segmentSuffix); } @Override protected void closeInternal(Collection<? extends Closeable> closeables) throws IOException { IOUtils.close(closeables); } private static class SimpleTextDocValues extends DocValues { private int docCount; @Override public void close() throws IOException { try { super.close(); } finally { IOUtils.close(input); } } private Type type; private Comparator<BytesRef> comp; private int valueSize; private final IndexInput input; public SimpleTextDocValues(Directory dir, IOContext ctx, Type type, String id, int docCount, Comparator<BytesRef> comp, String segmentSuffix) throws IOException { this.type = type; this.docCount = docCount; this.comp = comp; final String fileName = IndexFileNames.segmentFileName(id, "", segmentSuffix); boolean success = false; IndexInput in = null; try { in = dir.openInput(fileName, ctx); valueSize = readHeader(in); success = true; } finally { if (!success) { IOUtils.closeWhileHandlingException(in); } } input = in; } @Override public Source load() throws IOException { boolean success = false; IndexInput in = (IndexInput) input.clone(); try { Source source = null; switch (type) { case BYTES_FIXED_DEREF: case BYTES_FIXED_SORTED: case BYTES_FIXED_STRAIGHT: case BYTES_VAR_DEREF: case BYTES_VAR_SORTED: case BYTES_VAR_STRAIGHT: source = read(in, new ValueReader(type, docCount, comp)); break; case FIXED_INTS_16: case FIXED_INTS_32: case VAR_INTS: case FIXED_INTS_64: case FIXED_INTS_8: case FLOAT_32: case FLOAT_64: source = read(in, new ValueReader(type, docCount, null)); break; default: throw new IllegalArgumentException("unknown type: " + type); } assert source != null; success = true; return source; } finally { if (!success) { IOUtils.closeWhileHandlingException(in); } else { IOUtils.close(in); } } } private int readHeader(IndexInput in) throws IOException { BytesRef scratch = new BytesRef(); SimpleTextUtil.readLine(in, scratch); assert StringHelper.startsWith(scratch, HEADER); SimpleTextUtil.readLine(in, scratch); assert StringHelper.startsWith(scratch, VALUE_SIZE); return Integer.parseInt(readString(scratch.offset + VALUE_SIZE.length, scratch)); } private Source read(IndexInput in, ValueReader reader) throws IOException { BytesRef scratch = new BytesRef(); for (int i = 0; i < docCount; i++) { SimpleTextUtil.readLine(in, scratch); assert StringHelper.startsWith(scratch, DOC) : scratch.utf8ToString(); SimpleTextUtil.readLine(in, scratch); assert StringHelper.startsWith(scratch, VALUE); reader.fromString(i, scratch, scratch.offset + VALUE.length); } SimpleTextUtil.readLine(in, scratch); assert scratch.equals(END); return reader.getSource(); } @Override public Source getDirectSource() throws IOException { return this.getSource(); } @Override public int getValueSize() { return valueSize; } @Override public Type type() { return type; } } public static String readString(int offset, BytesRef scratch) { return new String(scratch.bytes, scratch.offset + offset, scratch.length - offset, IOUtils.CHARSET_UTF_8); } private static final class ValueReader { private final Type type; private byte[] bytes; private short[] shorts; private int[] ints; private long[] longs; private float[] floats; private double[] doubles; private Source source; private BytesRefHash hash; private BytesRef scratch; public ValueReader(Type type, int maxDocs, Comparator<BytesRef> comp) { super(); this.type = type; Source docValuesArray = null; switch (type) { case FIXED_INTS_16: shorts = new short[maxDocs]; docValuesArray = DocValuesArraySource.forType(type) .newFromArray(shorts); break; case FIXED_INTS_32: ints = new int[maxDocs]; docValuesArray = DocValuesArraySource.forType(type).newFromArray(ints); break; case FIXED_INTS_64: longs = new long[maxDocs]; docValuesArray = DocValuesArraySource.forType(type) .newFromArray(longs); break; case VAR_INTS: longs = new long[maxDocs]; docValuesArray = new VarIntsArraySource(type, longs); break; case FIXED_INTS_8: bytes = new byte[maxDocs]; docValuesArray = DocValuesArraySource.forType(type).newFromArray(bytes); break; case FLOAT_32: floats = new float[maxDocs]; docValuesArray = DocValuesArraySource.forType(type) .newFromArray(floats); break; case FLOAT_64: doubles = new double[maxDocs]; docValuesArray = DocValuesArraySource.forType(type).newFromArray( doubles); break; case BYTES_FIXED_DEREF: case BYTES_FIXED_SORTED: case BYTES_FIXED_STRAIGHT: case BYTES_VAR_DEREF: case BYTES_VAR_SORTED: case BYTES_VAR_STRAIGHT: assert comp != null; hash = new BytesRefHash(); BytesSource bytesSource = new BytesSource(type, comp, maxDocs, hash); ints = bytesSource.docIdToEntry; source = bytesSource; scratch = new BytesRef(); break; } if (docValuesArray != null) { assert source == null; this.source = docValuesArray; } } public void fromString(int ord, BytesRef ref, int offset) { switch (type) { case FIXED_INTS_16: assert shorts != null; shorts[ord] = Short.parseShort(readString(offset, ref)); break; case FIXED_INTS_32: assert ints != null; ints[ord] = Integer.parseInt(readString(offset, ref)); break; case FIXED_INTS_64: case VAR_INTS: assert longs != null; longs[ord] = Long.parseLong(readString(offset, ref)); break; case FIXED_INTS_8: assert bytes != null; bytes[ord] = (byte) Integer.parseInt(readString(offset, ref)); break; case FLOAT_32: assert floats != null; floats[ord] = Float.parseFloat(readString(offset, ref)); break; case FLOAT_64: assert doubles != null; doubles[ord] = Double.parseDouble(readString(offset, ref)); break; case BYTES_FIXED_DEREF: case BYTES_FIXED_SORTED: case BYTES_FIXED_STRAIGHT: case BYTES_VAR_DEREF: case BYTES_VAR_SORTED: case BYTES_VAR_STRAIGHT: scratch.bytes = ref.bytes; scratch.length = ref.length - offset; scratch.offset = ref.offset + offset; int key = hash.add(scratch); ints[ord] = key < 0 ? (-key) - 1 : key; break; } } public Source getSource() { if (source instanceof BytesSource) { ((BytesSource) source).maybeSort(); } return source; } } private static final class BytesSource extends SortedSource { private final BytesRefHash hash; int[] docIdToEntry; int[] sortedEntries; int[] adresses; private final boolean isSorted; protected BytesSource(Type type, Comparator<BytesRef> comp, int maxDoc, BytesRefHash hash) { super(type, comp); docIdToEntry = new int[maxDoc]; this.hash = hash; isSorted = type == Type.BYTES_FIXED_SORTED || type == Type.BYTES_VAR_SORTED; } void maybeSort() { if (isSorted) { adresses = new int[hash.size()]; sortedEntries = hash.sort(getComparator()); for (int i = 0; i < adresses.length; i++) { int entry = sortedEntries[i]; adresses[entry] = i; } } } @Override public BytesRef getBytes(int docID, BytesRef ref) { if (isSorted) { return hash.get(sortedEntries[ord(docID)], ref); } else { return hash.get(docIdToEntry[docID], ref); } } @Override public SortedSource asSortedSource() { if (isSorted) { return this; } return null; } @Override public int ord(int docID) { assert isSorted; try { return adresses[docIdToEntry[docID]]; } catch (Exception e) { return 0; } } @Override public BytesRef getByOrd(int ord, BytesRef bytesRef) { assert isSorted; return hash.get(sortedEntries[ord], bytesRef); } @Override public Reader getDocToOrd() { return null; } @Override public int getValueCount() { return hash.size(); } } private static class VarIntsArraySource extends Source { private final long[] array; protected VarIntsArraySource(Type type, long[] array) { super(type); this.array = array; } @Override public long getInt(int docID) { return array[docID]; } @Override public BytesRef getBytes(int docID, BytesRef ref) { DocValuesArraySource.copyLong(ref, getInt(docID)); return ref; } } }
true
false
null
null
diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java index b209436d9..c6cf3a3d0 100644 --- a/src/com/android/launcher3/PagedView.java +++ b/src/com/android/launcher3/PagedView.java @@ -1,2800 +1,2804 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.Rect; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.accessibility.AccessibilityEventCompat; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.Scroller; import java.util.ArrayList; interface Page { public int getPageChildCount(); public View getChildOnPageAt(int i); public void removeAllViewsOnPage(); public void removeViewOnPageAt(int i); public int indexOfChildOnPage(View v); } /** * An abstraction of the original Workspace which supports browsing through a * sequential list of "pages" */ public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener { private static final String TAG = "PagedView"; private static final boolean DEBUG = false; protected static final int INVALID_PAGE = -1; // the min drag distance for a fling to register, to prevent random page shifts private static final int MIN_LENGTH_FOR_FLING = 25; protected static final int PAGE_SNAP_ANIMATION_DURATION = 750; protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950; protected static final float NANOTIME_DIV = 1000000000.0f; private static final float OVERSCROLL_ACCELERATE_FACTOR = 2; private static final float OVERSCROLL_DAMP_FACTOR = 0.14f; private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f; // The page is moved more than halfway, automatically move to the next page on touch up. private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f; // The following constants need to be scaled based on density. The scaled versions will be // assigned to the corresponding member variables below. private static final int FLING_THRESHOLD_VELOCITY = 500; private static final int MIN_SNAP_VELOCITY = 1500; private static final int MIN_FLING_VELOCITY = 250; // We are disabling touch interaction of the widget region for factory ROM. private static final boolean DISABLE_TOUCH_INTERACTION = false; private static final boolean DISABLE_TOUCH_SIDE_PAGES = true; private static final boolean DISABLE_FLING_TO_DELETE = true; private boolean mFreeScroll = false; private int mFreeScrollMinScrollX = -1; private int mFreeScrollMaxScrollX = -1; static final int AUTOMATIC_PAGE_SPACING = -1; protected int mFlingThresholdVelocity; protected int mMinFlingVelocity; protected int mMinSnapVelocity; protected float mDensity; protected float mSmoothingTime; protected float mTouchX; protected boolean mFirstLayout = true; private int mNormalChildHeight; protected int mCurrentPage; protected int mRestorePage = -1; protected int mChildCountOnLastLayout; protected int mNextPage = INVALID_PAGE; protected int mMaxScrollX; protected Scroller mScroller; private VelocityTracker mVelocityTracker; private float mParentDownMotionX; private float mParentDownMotionY; private float mDownMotionX; private float mDownMotionY; private float mDownScrollX; private float mDragViewBaselineLeft; protected float mLastMotionX; protected float mLastMotionXRemainder; protected float mLastMotionY; protected float mTotalMotionX; private int mLastScreenCenter = -1; private boolean mCancelTap; private int[] mPageScrolls; protected final static int TOUCH_STATE_REST = 0; protected final static int TOUCH_STATE_SCROLLING = 1; protected final static int TOUCH_STATE_PREV_PAGE = 2; protected final static int TOUCH_STATE_NEXT_PAGE = 3; protected final static int TOUCH_STATE_REORDERING = 4; protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f; protected int mTouchState = TOUCH_STATE_REST; protected boolean mForceScreenScrolled = false; protected OnLongClickListener mLongClickListener; protected int mTouchSlop; private int mPagingTouchSlop; private int mMaximumVelocity; protected int mPageSpacing; protected int mPageLayoutPaddingTop; protected int mPageLayoutPaddingBottom; protected int mPageLayoutPaddingLeft; protected int mPageLayoutPaddingRight; protected int mPageLayoutWidthGap; protected int mPageLayoutHeightGap; protected int mCellCountX = 0; protected int mCellCountY = 0; protected boolean mCenterPagesVertically; protected boolean mAllowOverScroll = true; protected int mUnboundedScrollX; protected int[] mTempVisiblePagesRange = new int[2]; protected boolean mForceDrawAllChildrenNextFrame; // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise // it is equal to the scaled overscroll position. We use a separate value so as to prevent // the screens from continuing to translate beyond the normal bounds. protected int mOverScrollX; protected static final int INVALID_POINTER = -1; protected int mActivePointerId = INVALID_POINTER; private PageSwitchListener mPageSwitchListener; protected ArrayList<Boolean> mDirtyPageContent; // If true, syncPages and syncPageItems will be called to refresh pages protected boolean mContentIsRefreshable = true; // If true, modify alpha of neighboring pages as user scrolls left/right protected boolean mFadeInAdjacentScreens = false; // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding // to switch to a new page protected boolean mUsePagingTouchSlop = true; // If true, the subclass should directly update scrollX itself in its computeScroll method // (SmoothPagedView does this) protected boolean mDeferScrollUpdate = false; protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false; protected boolean mIsPageMoving = false; // All syncs and layout passes are deferred until data is ready. protected boolean mIsDataReady = false; protected boolean mAllowLongPress = true; // Page Indicator private int mPageIndicatorViewId; private PageIndicator mPageIndicator; private boolean mAllowPagedViewAnimations = true; // The viewport whether the pages are to be contained (the actual view may be larger than the // viewport) private Rect mViewport = new Rect(); // Reordering // We use the min scale to determine how much to expand the actually PagedView measured // dimensions such that when we are zoomed out, the view is not clipped private int REORDERING_DROP_REPOSITION_DURATION = 200; protected int REORDERING_REORDER_REPOSITION_DURATION = 300; protected int REORDERING_ZOOM_IN_OUT_DURATION = 250; private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80; private float mMinScale = 1f; private boolean mUseMinScale = false; protected View mDragView; protected AnimatorSet mZoomInOutAnim; private Runnable mSidePageHoverRunnable; private int mSidePageHoverIndex = -1; // This variable's scope is only for the duration of startReordering() and endReordering() private boolean mReorderingStarted = false; // This variable's scope is for the duration of startReordering() and after the zoomIn() // animation after endReordering() private boolean mIsReordering; // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2; private int mPostReorderingPreZoomInRemainingAnimationCount; private Runnable mPostReorderingPreZoomInRunnable; // Convenience/caching private Matrix mTmpInvMatrix = new Matrix(); private float[] mTmpPoint = new float[2]; private int[] mTmpIntPoint = new int[2]; private Rect mTmpRect = new Rect(); private Rect mAltTmpRect = new Rect(); // Fling to delete private int FLING_TO_DELETE_FADE_OUT_DURATION = 350; private float FLING_TO_DELETE_FRICTION = 0.035f; // The degrees specifies how much deviation from the up vector to still consider a fling "up" private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f; protected int mFlingToDeleteThresholdVelocity = -1400; // Drag to delete private boolean mDeferringForDelete = false; private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250; private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350; // Drop to delete private View mDeleteDropTarget; private boolean mAutoComputePageSpacing = false; private boolean mRecomputePageSpacing = false; // Bouncer private boolean mTopAlignPageWhenShrinkingForBouncer = false; protected final Rect mInsets = new Rect(); protected int mFirstChildLeft; public interface PageSwitchListener { void onPageSwitch(View newPage, int newPageIndex); } public PagedView(Context context) { this(context, null); } public PagedView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagedView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, defStyle, 0); setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0)); if (mPageSpacing < 0) { mAutoComputePageSpacing = mRecomputePageSpacing = true; } mPageLayoutPaddingTop = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingTop, 0); mPageLayoutPaddingBottom = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingBottom, 0); mPageLayoutPaddingLeft = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingLeft, 0); mPageLayoutPaddingRight = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutPaddingRight, 0); mPageLayoutWidthGap = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutWidthGap, 0); mPageLayoutHeightGap = a.getDimensionPixelSize( R.styleable.PagedView_pageLayoutHeightGap, 0); mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1); a.recycle(); setHapticFeedbackEnabled(false); init(); } /** * Initializes various states for this workspace. */ protected void init() { mDirtyPageContent = new ArrayList<Boolean>(); mDirtyPageContent.ensureCapacity(32); mScroller = new Scroller(getContext(), new ScrollInterpolator()); mCurrentPage = 0; mCenterPagesVertically = true; final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledPagingTouchSlop(); mPagingTouchSlop = configuration.getScaledPagingTouchSlop(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mDensity = getResources().getDisplayMetrics().density; // Scale the fling-to-delete threshold by the density mFlingToDeleteThresholdVelocity = (int) (mFlingToDeleteThresholdVelocity * mDensity); mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity); mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity); mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity); setOnHierarchyChangeListener(this); } protected void onAttachedToWindow() { super.onAttachedToWindow(); // Hook up the page indicator ViewGroup parent = (ViewGroup) getParent(); if (mPageIndicator == null && mPageIndicatorViewId > -1) { mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId); mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); ArrayList<PageIndicator.PageMarkerResources> markers = new ArrayList<PageIndicator.PageMarkerResources>(); for (int i = 0; i < getChildCount(); ++i) { markers.add(getPageIndicatorMarker(i)); } mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations); - mPageIndicator.setOnClickListener(getPageIndicatorClickListener()); + + OnClickListener listener = getPageIndicatorClickListener(); + if (listener != null) { + mPageIndicator.setOnClickListener(listener); + } mPageIndicator.setContentDescription(getPageIndicatorDescription()); } } protected String getPageIndicatorDescription() { return getCurrentPageDescription(); } protected OnClickListener getPageIndicatorClickListener() { return null; } protected void onDetachedFromWindow() { // Unhook the page indicator mPageIndicator = null; } void setDeleteDropTarget(View v) { mDeleteDropTarget = v; } // Convenience methods to map points from self to parent and vice versa float[] mapPointFromViewToParent(View v, float x, float y) { mTmpPoint[0] = x; mTmpPoint[1] = y; v.getMatrix().mapPoints(mTmpPoint); mTmpPoint[0] += v.getLeft(); mTmpPoint[1] += v.getTop(); return mTmpPoint; } float[] mapPointFromParentToView(View v, float x, float y) { mTmpPoint[0] = x - v.getLeft(); mTmpPoint[1] = y - v.getTop(); v.getMatrix().invert(mTmpInvMatrix); mTmpInvMatrix.mapPoints(mTmpPoint); return mTmpPoint; } void updateDragViewTranslationDuringDrag() { if (mDragView != null) { float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) + (mDragViewBaselineLeft - mDragView.getLeft()); float y = mLastMotionY - mDownMotionY; mDragView.setTranslationX(x); mDragView.setTranslationY(y); if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y); } } public void setMinScale(float f) { mMinScale = f; mUseMinScale = true; requestLayout(); } @Override public void setScaleX(float scaleX) { super.setScaleX(scaleX); if (isReordering(true)) { float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); mLastMotionX = p[0]; mLastMotionY = p[1]; updateDragViewTranslationDuringDrag(); } } // Convenience methods to get the actual width/height of the PagedView (since it is measured // to be larger to account for the minimum possible scale) int getViewportWidth() { return mViewport.width(); } int getViewportHeight() { return mViewport.height(); } // Convenience methods to get the offset ASSUMING that we are centering the pages in the // PagedView both horizontally and vertically int getViewportOffsetX() { return (getMeasuredWidth() - getViewportWidth()) / 2; } int getViewportOffsetY() { return (getMeasuredHeight() - getViewportHeight()) / 2; } PageIndicator getPageIndicator() { return mPageIndicator; } protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { return new PageIndicator.PageMarkerResources(); } public void setPageSwitchListener(PageSwitchListener pageSwitchListener) { mPageSwitchListener = pageSwitchListener; if (mPageSwitchListener != null) { mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); } } /** * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api. */ public boolean isLayoutRtl() { return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); } /** * Called by subclasses to mark that data is ready, and that we can begin loading and laying * out pages. */ protected void setDataIsReady() { mIsDataReady = true; } protected boolean isDataReady() { return mIsDataReady; } /** * Returns the index of the currently displayed page. * * @return The index of the currently displayed page. */ int getCurrentPage() { return mCurrentPage; } int getNextPage() { return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; } int getPageCount() { return getChildCount(); } View getPageAt(int index) { return getChildAt(index); } protected int indexToPage(int index) { return index; } /** * Updates the scroll of the current page immediately to its final scroll position. We use this * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of * the previous tab page. */ protected void updateCurrentPageScroll() { // If the current page is invalid, just reset the scroll position to zero int newX = 0; if (0 <= mCurrentPage && mCurrentPage < getPageCount()) { newX = getScrollForPage(mCurrentPage); } scrollTo(newX, 0); mScroller.setFinalX(newX); mScroller.forceFinished(true); } /** * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation * ends, {@link #resumeScrolling()} should be called, along with * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling. */ void pauseScrolling() { mScroller.forceFinished(true); } /** * Enables scrolling again. * @see #pauseScrolling() */ void resumeScrolling() { } /** * Sets the current page. */ void setCurrentPage(int currentPage) { if (!mScroller.isFinished()) { mScroller.abortAnimation(); // We need to clean up the next page here to avoid computeScrollHelper from // updating current page on the pass. mNextPage = INVALID_PAGE; } // don't introduce any checks like mCurrentPage == currentPage here-- if we change the // the default if (getChildCount() == 0) { return; } mForceScreenScrolled = true; mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1)); updateCurrentPageScroll(); notifyPageSwitchListener(); invalidate(); } /** * The restore page will be set in place of the current page at the next (likely first) * layout. */ void setRestorePage(int restorePage) { mRestorePage = restorePage; } protected void notifyPageSwitchListener() { if (mPageSwitchListener != null) { mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); } // Update the page indicator (when we aren't reordering) if (mPageIndicator != null && !isReordering(false)) { mPageIndicator.setActiveMarker(getNextPage()); } } protected void pageBeginMoving() { if (!mIsPageMoving) { mIsPageMoving = true; onPageBeginMoving(); } } protected void pageEndMoving() { if (mIsPageMoving) { mIsPageMoving = false; onPageEndMoving(); } } protected boolean isPageMoving() { return mIsPageMoving; } // a method that subclasses can override to add behavior protected void onPageBeginMoving() { } // a method that subclasses can override to add behavior protected void onPageEndMoving() { } /** * Registers the specified listener on each page contained in this workspace. * * @param l The listener used to respond to long clicks. */ @Override public void setOnLongClickListener(OnLongClickListener l) { mLongClickListener = l; final int count = getPageCount(); for (int i = 0; i < count; i++) { getPageAt(i).setOnLongClickListener(l); } super.setOnLongClickListener(l); } @Override public void scrollBy(int x, int y) { scrollTo(mUnboundedScrollX + x, getScrollY() + y); } @Override public void scrollTo(int x, int y) { // In free scroll mode, we clamp the scrollX if (mFreeScroll) { x = Math.min(x, mFreeScrollMaxScrollX); x = Math.max(x, mFreeScrollMinScrollX); } final boolean isRtl = isLayoutRtl(); mUnboundedScrollX = x; boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0); boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX); if (isXBeforeFirstPage) { super.scrollTo(0, y); if (mAllowOverScroll) { if (isRtl) { overScroll(x - mMaxScrollX); } else { overScroll(x); } } } else if (isXAfterLastPage) { super.scrollTo(mMaxScrollX, y); if (mAllowOverScroll) { if (isRtl) { overScroll(x); } else { overScroll(x - mMaxScrollX); } } } else { mOverScrollX = x; super.scrollTo(x, y); } mTouchX = x; mSmoothingTime = System.nanoTime() / NANOTIME_DIV; // Update the last motion events when scrolling if (isReordering(true)) { float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); mLastMotionX = p[0]; mLastMotionY = p[1]; updateDragViewTranslationDuringDrag(); } } private void sendScrollAccessibilityEvent() { AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (am.isEnabled()) { AccessibilityEvent ev = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED); ev.setItemCount(getChildCount()); ev.setFromIndex(mCurrentPage); final int action; if (getNextPage() >= mCurrentPage) { action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD; } else { action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD; } ev.setAction(action); sendAccessibilityEventUnchecked(ev); } } // we moved this functionality to a helper function so SmoothPagedView can reuse it protected boolean computeScrollHelper() { if (mScroller.computeScrollOffset()) { // Don't bother scrolling if the page does not need to be moved if (getScrollX() != mScroller.getCurrX() || getScrollY() != mScroller.getCurrY() || mOverScrollX != mScroller.getCurrX()) { float scaleX = mFreeScroll ? getScaleX() : 1f; int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX)); scrollTo(scrollX, mScroller.getCurrY()); } invalidate(); return true; } else if (mNextPage != INVALID_PAGE) { sendScrollAccessibilityEvent(); mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1)); mNextPage = INVALID_PAGE; notifyPageSwitchListener(); // Load the associated pages if necessary if (mDeferLoadAssociatedPagesUntilScrollCompletes) { loadAssociatedPages(mCurrentPage); mDeferLoadAssociatedPagesUntilScrollCompletes = false; } // We don't want to trigger a page end moving unless the page has settled // and the user has stopped scrolling if (mTouchState == TOUCH_STATE_REST) { pageEndMoving(); } onPostReorderingAnimationCompleted(); AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (am.isEnabled()) { // Notify the user when the page changes announceForAccessibility(getCurrentPageDescription()); } return true; } return false; } @Override public void computeScroll() { computeScrollHelper(); } protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) { return mTopAlignPageWhenShrinkingForBouncer; } public static class LayoutParams extends ViewGroup.LayoutParams { public boolean isFullScreenPage = false; /** * {@inheritDoc} */ public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } public void addFullScreenPage(View page) { LayoutParams lp = generateDefaultLayoutParams(); lp.isFullScreenPage = true; super.addView(page, 0, lp); } public int getNormalChildHeight() { return mNormalChildHeight; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (!mIsDataReady || getChildCount() == 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // We measure the dimensions of the PagedView to be larger than the pages so that when we // zoom out (and scale down), the view is still contained in the parent int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the // viewport, we can be at most one and a half screens offset once we scale down DisplayMetrics dm = getResources().getDisplayMetrics(); int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom); int parentWidthSize, parentHeightSize; int scaledWidthSize, scaledHeightSize; if (mUseMinScale) { parentWidthSize = (int) (1.5f * maxSize); parentHeightSize = maxSize; scaledWidthSize = (int) (parentWidthSize / mMinScale); scaledHeightSize = (int) (parentHeightSize / mMinScale); } else { scaledWidthSize = widthSize; scaledHeightSize = heightSize; } mViewport.set(0, 0, widthSize, heightSize); if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // Return early if we aren't given a proper dimension if (widthSize <= 0 || heightSize <= 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } /* Allow the height to be set as WRAP_CONTENT. This allows the particular case * of the All apps view on XLarge displays to not take up more space then it needs. Width * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect * each page to have the same width. */ final int verticalPadding = getPaddingTop() + getPaddingBottom(); final int horizontalPadding = getPaddingLeft() + getPaddingRight(); // The children are given the same width and height as the workspace // unless they were set to WRAP_CONTENT if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize); if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize); if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize); if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding); if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { // disallowing padding in paged view (just pass 0) final View child = getPageAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childWidthMode; int childHeightMode; int childWidth; int childHeight; if (!lp.isFullScreenPage) { if (lp.width == LayoutParams.WRAP_CONTENT) { childWidthMode = MeasureSpec.AT_MOST; } else { childWidthMode = MeasureSpec.EXACTLY; } if (lp.height == LayoutParams.WRAP_CONTENT) { childHeightMode = MeasureSpec.AT_MOST; } else { childHeightMode = MeasureSpec.EXACTLY; } childWidth = widthSize - horizontalPadding; childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom; mNormalChildHeight = childHeight; } else { childWidthMode = MeasureSpec.EXACTLY; childHeightMode = MeasureSpec.EXACTLY; if (mUseMinScale) { childWidth = getViewportWidth(); childHeight = getViewportHeight(); } else { childWidth = widthSize - getPaddingLeft() - getPaddingRight(); childHeight = heightSize - getPaddingTop() - getPaddingBottom(); } } final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, childWidthMode); final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, childHeightMode); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } setMeasuredDimension(scaledWidthSize, scaledHeightSize); if (childCount > 0) { // Calculate the variable page spacing if necessary if (mAutoComputePageSpacing && mRecomputePageSpacing) { // The gap between pages in the PagedView should be equal to the gap from the page // to the edge of the screen (so it is not visible in the current screen). To // account for unequal padding on each side of the paged view, we take the maximum // of the left/right gap and use that as the gap between each page. int offset = (getViewportWidth() - getChildWidth(0)) / 2; int spacing = Math.max(offset, widthSize - offset - getChildAt(0).getMeasuredWidth()); setPageSpacing(spacing); mRecomputePageSpacing = false; } } } public void setPageSpacing(int pageSpacing) { mPageSpacing = pageSpacing; requestLayout(); } protected int getFirstChildLeft() { return mFirstChildLeft; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (!mIsDataReady || getChildCount() == 0) { return; } if (DEBUG) Log.d(TAG, "PagedView.onLayout()"); final int childCount = getChildCount(); int screenWidth = getViewportWidth(); int offsetX = getViewportOffsetX(); int offsetY = getViewportOffsetY(); // Update the viewport offsets mViewport.offset(offsetX, offsetY); final boolean isRtl = isLayoutRtl(); final int startIndex = isRtl ? childCount - 1 : 0; final int endIndex = isRtl ? -1 : childCount; final int delta = isRtl ? -1 : 1; int verticalPadding = getPaddingTop() + getPaddingBottom(); int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2; if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) { mPageScrolls = new int[getChildCount()]; } for (int i = startIndex; i != endIndex; i += delta) { final View child = getPageAt(i); if (child.getVisibility() != View.GONE) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childTop; if (lp.isFullScreenPage) { childTop = offsetY; } else { childTop = offsetY + getPaddingTop() + mInsets.top; if (mCenterPagesVertically) { childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2; } } final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + childHeight); // We assume the left and right padding are equal, and hence center the pages // horizontally int scrollOffset = (getViewportWidth() - childWidth) / 2; mPageScrolls[i] = childLeft - scrollOffset - offsetX; if (i != endIndex - delta) { childLeft += childWidth + scrollOffset; int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2; childLeft += nextScrollOffset; } } } if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { setHorizontalScrollBarEnabled(false); updateCurrentPageScroll(); setHorizontalScrollBarEnabled(true); mFirstLayout = false; } if (childCount > 0) { final int index = isLayoutRtl() ? 0 : childCount - 1; mMaxScrollX = getScrollForPage(index); } else { mMaxScrollX = 0; } if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() && !mDeferringForDelete) { if (mRestorePage > -1) { setCurrentPage(mRestorePage); mRestorePage = -1; } else { setCurrentPage(getNextPage()); } } mChildCountOnLastLayout = getChildCount(); if (isReordering(true)) { updateDragViewTranslationDuringDrag(); } } protected void screenScrolled(int screenCenter) { boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX; if (mFadeInAdjacentScreens && !isInOverscroll) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child != null) { float scrollProgress = getScrollProgress(screenCenter, child, i); float alpha = 1 - Math.abs(scrollProgress); child.setAlpha(alpha); } } invalidate(); } } protected void enablePagedViewAnimations() { mAllowPagedViewAnimations = true; } protected void disablePagedViewAnimations() { mAllowPagedViewAnimations = false; } @Override public void onChildViewAdded(View parent, View child) { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null && !isReordering(false)) { int pageIndex = indexOfChild(child); mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex), mAllowPagedViewAnimations); } // This ensures that when children are added, they get the correct transforms / alphas // in accordance with any scroll effects. mForceScreenScrolled = true; mRecomputePageSpacing = true; updateFreescrollBounds(); invalidate(); } @Override public void onChildViewRemoved(View parent, View child) { mForceScreenScrolled = true; updateFreescrollBounds(); invalidate(); } private void removeMarkerForView(int index) { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null && !isReordering(false)) { mPageIndicator.removeMarker(index, mAllowPagedViewAnimations); } } @Override public void removeView(View v) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeMarkerForView(indexOfChild(v)); super.removeView(v); } @Override public void removeViewInLayout(View v) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeMarkerForView(indexOfChild(v)); super.removeViewInLayout(v); } @Override public void removeViewAt(int index) { // XXX: We should find a better way to hook into this before the view // gets removed form its parent... removeViewAt(index); super.removeViewAt(index); } @Override public void removeAllViewsInLayout() { // Update the page indicator, we don't update the page indicator as we // add/remove pages if (mPageIndicator != null) { mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); } super.removeAllViewsInLayout(); } protected int getChildOffset(int index) { if (index < 0 || index > getChildCount() - 1) return 0; int offset = getPageAt(index).getLeft() - getViewportOffsetX(); return offset; } protected void getOverviewModePages(int[] range) { range[0] = 0; range[1] = Math.max(0, getChildCount() - 1); } protected void getVisiblePages(int[] range) { final int pageCount = getChildCount(); mTmpIntPoint[0] = mTmpIntPoint[1] = 0; range[0] = -1; range[1] = -1; if (pageCount > 0) { int viewportWidth = getViewportWidth(); int curScreen = 0; int count = getChildCount(); for (int i = 0; i < count; i++) { View currPage = getPageAt(i); mTmpIntPoint[0] = 0; Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); if (mTmpIntPoint[0] > viewportWidth) { if (range[0] == -1) { continue; } else { break; } } mTmpIntPoint[0] = currPage.getMeasuredWidth(); Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); if (mTmpIntPoint[0] < 0) { if (range[0] == -1) { continue; } else { break; } } curScreen = i; if (range[0] < 0) { range[0] = curScreen; } } range[1] = curScreen; } else { range[0] = -1; range[1] = -1; } } protected boolean shouldDrawChild(View child) { return child.getAlpha() > 0 && child.getVisibility() == VISIBLE; } @Override protected void dispatchDraw(Canvas canvas) { int halfScreenSize = getViewportWidth() / 2; // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. // Otherwise it is equal to the scaled overscroll position. int screenCenter = mOverScrollX + halfScreenSize; if (screenCenter != mLastScreenCenter || mForceScreenScrolled) { // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can // set it for the next frame mForceScreenScrolled = false; screenScrolled(screenCenter); mLastScreenCenter = screenCenter; } // Find out which screens are visible; as an optimization we only call draw on them final int pageCount = getChildCount(); if (pageCount > 0) { getVisiblePages(mTempVisiblePagesRange); final int leftScreen = mTempVisiblePagesRange[0]; final int rightScreen = mTempVisiblePagesRange[1]; if (leftScreen != -1 && rightScreen != -1) { final long drawingTime = getDrawingTime(); // Clip to the bounds canvas.save(); canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(), getScrollY() + getBottom() - getTop()); // Draw all the children, leaving the drag view for last for (int i = pageCount - 1; i >= 0; i--) { final View v = getPageAt(i); if (v == mDragView) continue; if (mForceDrawAllChildrenNextFrame || (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) { drawChild(canvas, v, drawingTime); } } // Draw the drag view on top (if there is one) if (mDragView != null) { drawChild(canvas, mDragView, drawingTime); } mForceDrawAllChildrenNextFrame = false; canvas.restore(); } } } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { int page = indexToPage(indexOfChild(child)); if (page != mCurrentPage || !mScroller.isFinished()) { snapToPage(page); return true; } return false; } @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int focusablePage; if (mNextPage != INVALID_PAGE) { focusablePage = mNextPage; } else { focusablePage = mCurrentPage; } View v = getPageAt(focusablePage); if (v != null) { return v.requestFocus(direction, previouslyFocusedRect); } return false; } @Override public boolean dispatchUnhandledMove(View focused, int direction) { // XXX-RTL: This will be fixed in a future CL if (direction == View.FOCUS_LEFT) { if (getCurrentPage() > 0) { snapToPage(getCurrentPage() - 1); return true; } } else if (direction == View.FOCUS_RIGHT) { if (getCurrentPage() < getPageCount() - 1) { snapToPage(getCurrentPage() + 1); return true; } } return super.dispatchUnhandledMove(focused, direction); } @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { // XXX-RTL: This will be fixed in a future CL if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) { getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode); } if (direction == View.FOCUS_LEFT) { if (mCurrentPage > 0) { getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode); } } else if (direction == View.FOCUS_RIGHT){ if (mCurrentPage < getPageCount() - 1) { getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode); } } } /** * If one of our descendant views decides that it could be focused now, only * pass that along if it's on the current page. * * This happens when live folders requery, and if they're off page, they * end up calling requestFocus, which pulls it on page. */ @Override public void focusableViewAvailable(View focused) { View current = getPageAt(mCurrentPage); View v = focused; while (true) { if (v == current) { super.focusableViewAvailable(focused); return; } if (v == this) { return; } ViewParent parent = v.getParent(); if (parent instanceof View) { v = (View)v.getParent(); } else { return; } } } /** * {@inheritDoc} */ @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { // We need to make sure to cancel our long press if // a scrollable widget takes over touch events final View currentPage = getPageAt(mCurrentPage); currentPage.cancelLongPress(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } /** * Return true if a tap at (x, y) should trigger a flip to the previous page. */ protected boolean hitsPreviousPage(float x, float y) { int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; if (isLayoutRtl()) { return (x > (getViewportOffsetX() + getViewportWidth() - offset + mPageSpacing)); } return (x < getViewportOffsetX() + offset - mPageSpacing); } /** * Return true if a tap at (x, y) should trigger a flip to the next page. */ protected boolean hitsNextPage(float x, float y) { int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; if (isLayoutRtl()) { return (x < getViewportOffsetX() + offset - mPageSpacing); } return (x > (getViewportOffsetX() + getViewportWidth() - offset + mPageSpacing)); } /** Returns whether x and y originated within the buffered viewport */ private boolean isTouchPointInViewportWithBuffer(int x, int y) { mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top, mViewport.right + mViewport.width() / 2, mViewport.bottom); return mTmpRect.contains(x, y); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (DISABLE_TOUCH_INTERACTION) { return false; } /* * This method JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we do the actual * scrolling there. */ acquireVelocityTrackerAndAddMovement(ev); // Skip touch handling if there are no pages to swipe if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev); /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) { return true; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ if (mActivePointerId != INVALID_POINTER) { determineScrollingStart(ev); } // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN // event. in that case, treat the first occurence of a move event as a ACTION_DOWN // i.e. fall through to the next case (don't break) // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events // while it's small- this was causing a crash before we checked for INVALID_POINTER) break; } case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); // Remember location of down touch mDownMotionX = x; mDownMotionY = y; mDownScrollX = getScrollX(); mLastMotionX = x; mLastMotionY = y; float[] p = mapPointFromViewToParent(this, x, y); mParentDownMotionX = p[0]; mParentDownMotionY = p[1]; mLastMotionXRemainder = 0; mTotalMotionX = 0; mActivePointerId = ev.getPointerId(0); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX()); final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop); if (finishedScrolling) { mTouchState = TOUCH_STATE_REST; mScroller.abortAnimation(); } else { if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) { mTouchState = TOUCH_STATE_SCROLLING; } else { mTouchState = TOUCH_STATE_REST; } } // check if this can be the beginning of a tap on the side of the pages // to scroll the current page if (!DISABLE_TOUCH_SIDE_PAGES) { if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) { if (getChildCount() > 0) { if (hitsPreviousPage(x, y)) { mTouchState = TOUCH_STATE_PREV_PAGE; } else if (hitsNextPage(x, y)) { mTouchState = TOUCH_STATE_NEXT_PAGE; } } } } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: resetTouchState(); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); releaseVelocityTracker(); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mTouchState != TOUCH_STATE_REST; } protected void determineScrollingStart(MotionEvent ev) { determineScrollingStart(ev, 1.0f); } /* * Determines if we should change the touch state to start scrolling after the * user moves their touch point too far. */ protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { // Disallow scrolling if we don't have a valid pointer index final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex == -1) return; // Disallow scrolling if we started the gesture from outside the viewport final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return; final int xDiff = (int) Math.abs(x - mLastMotionX); final int yDiff = (int) Math.abs(y - mLastMotionY); final int touchSlop = Math.round(touchSlopScale * mTouchSlop); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > touchSlop; boolean yMoved = yDiff > touchSlop; if (xMoved || xPaged || yMoved) { if (mUsePagingTouchSlop ? xPaged : xMoved) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; mTotalMotionX += Math.abs(mLastMotionX - x); mLastMotionX = x; mLastMotionXRemainder = 0; mTouchX = getViewportOffsetX() + getScrollX(); mSmoothingTime = System.nanoTime() / NANOTIME_DIV; pageBeginMoving(); } } } protected float getMaxScrollProgress() { return 1.0f; } protected void cancelCurrentPageLongPress() { if (mAllowLongPress) { //mAllowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentPage = getPageAt(mCurrentPage); if (currentPage != null) { currentPage.cancelLongPress(); } } } protected float getBoundedScrollProgress(int screenCenter, View v, int page) { final int halfScreenSize = getViewportWidth() / 2; screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter); screenCenter = Math.max(halfScreenSize, screenCenter); return getScrollProgress(screenCenter, v, page); } protected float getScrollProgress(int screenCenter, View v, int page) { final int halfScreenSize = getViewportWidth() / 2; int totalDistance = v.getMeasuredWidth() + mPageSpacing; int delta = screenCenter - (getScrollForPage(page) + halfScreenSize); float scrollProgress = delta / (totalDistance * 1.0f); scrollProgress = Math.min(scrollProgress, getMaxScrollProgress()); scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress()); return scrollProgress; } public int getScrollForPage(int index) { if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { return 0; } else { return mPageScrolls[index]; } } // This curve determines how the effect of scrolling over the limits of the page dimishes // as the user pulls further and further from the bounds private float overScrollInfluenceCurve(float f) { f -= 1.0f; return f * f * f + 1.0f; } protected void acceleratedOverScroll(float amount) { int screenSize = getViewportWidth(); // We want to reach the max over scroll effect when the user has // over scrolled half the size of the screen float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize); if (f == 0) return; // Clamp this factor, f, to -1 < f < 1 if (Math.abs(f) >= 1) { f /= Math.abs(f); } int overScrollAmount = (int) Math.round(f * screenSize); if (amount < 0) { mOverScrollX = overScrollAmount; super.scrollTo(0, getScrollY()); } else { mOverScrollX = mMaxScrollX + overScrollAmount; super.scrollTo(mMaxScrollX, getScrollY()); } invalidate(); } protected void dampedOverScroll(float amount) { int screenSize = getViewportWidth(); float f = (amount / screenSize); if (f == 0) return; f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); // Clamp this factor, f, to -1 < f < 1 if (Math.abs(f) >= 1) { f /= Math.abs(f); } int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize); if (amount < 0) { mOverScrollX = overScrollAmount; super.scrollTo(0, getScrollY()); } else { mOverScrollX = mMaxScrollX + overScrollAmount; super.scrollTo(mMaxScrollX, getScrollY()); } invalidate(); } protected void overScroll(float amount) { dampedOverScroll(amount); } protected float maxOverScroll() { // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not // exceed). Used to find out how much extra wallpaper we need for the over scroll effect float f = 1.0f; f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); return OVERSCROLL_DAMP_FACTOR * f; } protected void enableFreeScroll() { setEnableFreeScroll(true, -1); } protected void disableFreeScroll(int snapPage) { setEnableFreeScroll(false, snapPage); } void updateFreescrollBounds() { getOverviewModePages(mTempVisiblePagesRange); if (isLayoutRtl()) { mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]); mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]); } else { mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]); mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]); } } private void setEnableFreeScroll(boolean freeScroll, int snapPage) { mFreeScroll = freeScroll; if (snapPage == -1) { snapPage = getPageNearestToCenterOfScreen(); } if (!mFreeScroll) { snapToPage(snapPage); } else { updateFreescrollBounds(); getOverviewModePages(mTempVisiblePagesRange); if (getCurrentPage() < mTempVisiblePagesRange[0]) { setCurrentPage(mTempVisiblePagesRange[0]); } else if (getCurrentPage() > mTempVisiblePagesRange[1]) { setCurrentPage(mTempVisiblePagesRange[1]); } } setEnableOverscroll(!freeScroll); } private void setEnableOverscroll(boolean enable) { mAllowOverScroll = enable; } int getNearestHoverOverPageIndex() { if (mDragView != null) { int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2) + mDragView.getTranslationX()); getOverviewModePages(mTempVisiblePagesRange); int minDistance = Integer.MAX_VALUE; int minIndex = indexOfChild(mDragView); for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) { View page = getPageAt(i); int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2); int d = Math.abs(dragX - pageX); if (d < minDistance) { minIndex = i; minDistance = d; } } return minIndex; } return -1; } @Override public boolean onTouchEvent(MotionEvent ev) { if (DISABLE_TOUCH_INTERACTION) { return false; } super.onTouchEvent(ev); // Skip touch handling if there are no pages to swipe if (getChildCount() <= 0) return super.onTouchEvent(ev); acquireVelocityTrackerAndAddMovement(ev); final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { mScroller.abortAnimation(); } // Remember where the motion event started mDownMotionX = mLastMotionX = ev.getX(); mDownMotionY = mLastMotionY = ev.getY(); mDownScrollX = getScrollX(); float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = p[0]; mParentDownMotionY = p[1]; mLastMotionXRemainder = 0; mTotalMotionX = 0; mActivePointerId = ev.getPointerId(0); if (mTouchState == TOUCH_STATE_SCROLLING) { pageBeginMoving(); } break; case MotionEvent.ACTION_MOVE: if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex == -1) return true; final float x = ev.getX(pointerIndex); final float deltaX = mLastMotionX + mLastMotionXRemainder - x; mTotalMotionX += Math.abs(deltaX); // Only scroll and update mLastMotionX if we have moved some discrete amount. We // keep the remainder because we are actually testing if we've moved from the last // scrolled position (which is discrete). if (Math.abs(deltaX) >= 1.0f) { mTouchX += deltaX; mSmoothingTime = System.nanoTime() / NANOTIME_DIV; if (!mDeferScrollUpdate) { scrollBy((int) deltaX, 0); if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX); } else { invalidate(); } mLastMotionX = x; mLastMotionXRemainder = deltaX - (int) deltaX; } else { awakenScrollBars(); } } else if (mTouchState == TOUCH_STATE_REORDERING) { // Update the last motion position mLastMotionX = ev.getX(); mLastMotionY = ev.getY(); // Update the parent down so that our zoom animations take this new movement into // account float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = pt[0]; mParentDownMotionY = pt[1]; updateDragViewTranslationDuringDrag(); // Find the closest page to the touch point final int dragViewIndex = indexOfChild(mDragView); // Change the drag view if we are hovering over the drop target boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget( (int) mParentDownMotionX, (int) mParentDownMotionY); setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete); if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX); if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY); if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX); if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY); final int pageUnderPointIndex = getNearestHoverOverPageIndex(); if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) && !isHoveringOverDelete) { mTempVisiblePagesRange[0] = 0; mTempVisiblePagesRange[1] = getPageCount() - 1; getOverviewModePages(mTempVisiblePagesRange); if (mTempVisiblePagesRange[0] <= pageUnderPointIndex && pageUnderPointIndex <= mTempVisiblePagesRange[1] && pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) { mSidePageHoverIndex = pageUnderPointIndex; mSidePageHoverRunnable = new Runnable() { @Override public void run() { // Setup the scroll to the correct page before we swap the views snapToPage(pageUnderPointIndex); // For each of the pages between the paged view and the drag view, // animate them from the previous position to the new position in // the layout (as a result of the drag view moving in the layout) int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1; int lowerIndex = (dragViewIndex < pageUnderPointIndex) ? dragViewIndex + 1 : pageUnderPointIndex; int upperIndex = (dragViewIndex > pageUnderPointIndex) ? dragViewIndex - 1 : pageUnderPointIndex; for (int i = lowerIndex; i <= upperIndex; ++i) { View v = getChildAt(i); // dragViewIndex < pageUnderPointIndex, so after we remove the // drag view all subsequent views to pageUnderPointIndex will // shift down. int oldX = getViewportOffsetX() + getChildOffset(i); int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta); // Animate the view translation from its old position to its new // position AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY); if (anim != null) { anim.cancel(); } v.setTranslationX(oldX - newX); anim = new AnimatorSet(); anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION); anim.playTogether( ObjectAnimator.ofFloat(v, "translationX", 0f)); anim.start(); v.setTag(anim); } removeView(mDragView); onRemoveView(mDragView, false); addView(mDragView, pageUnderPointIndex); onAddView(mDragView, pageUnderPointIndex); mSidePageHoverIndex = -1; mPageIndicator.setActiveMarker(getNextPage()); } }; postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT); } } else { removeCallbacks(mSidePageHoverRunnable); mSidePageHoverIndex = -1; } } else { determineScrollingStart(ev); } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = ev.findPointerIndex(activePointerId); final float x = ev.getX(pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int velocityX = (int) velocityTracker.getXVelocity(activePointerId); final int deltaX = (int) (x - mDownMotionX); final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth(); boolean isSignificantMove = Math.abs(deltaX) > pageWidth * SIGNIFICANT_MOVE_THRESHOLD; mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING && Math.abs(velocityX) > mFlingThresholdVelocity; if (!mFreeScroll) { // In the case that the page is moved far to one direction and then is flung // in the opposite direction, we use a threshold to determine whether we should // just return to the starting page, or if we should skip one further. boolean returnToOriginalPage = false; if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && Math.signum(velocityX) != Math.signum(deltaX) && isFling) { returnToOriginalPage = true; } int finalPage; // We give flings precedence over large moves, which is why we short-circuit our // test for a large move if a fling has been registered. That is, a large // move to the left and fling to the right will register as a fling to the right. final boolean isRtl = isLayoutRtl(); boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0; boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0; if (((isSignificantMove && !isDeltaXLeft && !isFling) || (isFling && !isVelocityXLeft)) && mCurrentPage > 0) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1; snapToPageWithVelocity(finalPage, velocityX); } else if (((isSignificantMove && isDeltaXLeft && !isFling) || (isFling && isVelocityXLeft)) && mCurrentPage < getChildCount() - 1) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1; snapToPageWithVelocity(finalPage, velocityX); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.max(0, mCurrentPage - 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else { if (!mScroller.isFinished()) { mScroller.abortAnimation(); } float scaleX = getScaleX(); int vX = (int) (-velocityX * scaleX); int initialScrollX = (int) (getScrollX() * scaleX); mScroller.fling(initialScrollX, getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0); invalidate(); } } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_REORDERING) { // Update the last motion position mLastMotionX = ev.getX(); mLastMotionY = ev.getY(); // Update the parent down so that our zoom animations take this new movement into // account float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); mParentDownMotionX = pt[0]; mParentDownMotionY = pt[1]; updateDragViewTranslationDuringDrag(); boolean handledFling = false; if (!DISABLE_FLING_TO_DELETE) { // Check the velocity and see if we are flinging-to-delete PointF flingToDeleteVector = isFlingingToDelete(); if (flingToDeleteVector != null) { onFlingToDelete(flingToDeleteVector); handledFling = true; } } if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX, (int) mParentDownMotionY)) { onDropToDelete(); } } else { if (!mCancelTap) { onUnhandledTap(ev); } } // Remove the callback to wait for the side page hover timeout removeCallbacks(mSidePageHoverRunnable); // End any intermediate reordering states resetTouchState(); break; case MotionEvent.ACTION_CANCEL: if (mTouchState == TOUCH_STATE_SCROLLING) { snapToDestination(); } resetTouchState(); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); releaseVelocityTracker(); break; } return true; } public void onFlingToDelete(View v) {} public void onRemoveView(View v, boolean deletePermanently) {} public void onRemoveViewAnimationCompleted() {} public void onAddView(View v, int index) {} private void resetTouchState() { releaseVelocityTracker(); endReordering(); mCancelTap = false; mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; } protected void onUnhandledTap(MotionEvent ev) { ((Launcher) getContext()).onClick(this); } @Override public boolean onGenericMotionEvent(MotionEvent event) { if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: { // Handle mouse (or ext. device) by shifting the page depending on the scroll final float vscroll; final float hscroll; if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { vscroll = 0; hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); } else { vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); } if (hscroll != 0 || vscroll != 0) { boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0) : (hscroll > 0 || vscroll > 0); if (isForwardScroll) { scrollRight(); } else { scrollLeft(); } return true; } } } } return super.onGenericMotionEvent(event); } private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); } private void releaseVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.clear(); mVelocityTracker.recycle(); mVelocityTracker = null; } } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = mDownMotionX = ev.getX(newPointerIndex); mLastMotionY = ev.getY(newPointerIndex); mLastMotionXRemainder = 0; mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public void requestChildFocus(View child, View focused) { super.requestChildFocus(child, focused); int page = indexToPage(indexOfChild(child)); if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) { snapToPage(page); } } protected int getChildWidth(int index) { return getPageAt(index).getMeasuredWidth(); } int getPageNearestToPoint(float x) { int index = 0; for (int i = 0; i < getChildCount(); ++i) { if (x < getChildAt(i).getRight() - getScrollX()) { return index; } else { index++; } } return Math.min(index, getChildCount() - 1); } int getPageNearestToCenterOfScreen() { int minDistanceFromScreenCenter = Integer.MAX_VALUE; int minDistanceFromScreenCenterIndex = -1; int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2); final int childCount = getChildCount(); for (int i = 0; i < childCount; ++i) { View layout = (View) getPageAt(i); int childWidth = layout.getMeasuredWidth(); int halfChildWidth = (childWidth / 2); int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth; int distanceFromScreenCenter = Math.abs(childCenter - screenCenter); if (distanceFromScreenCenter < minDistanceFromScreenCenter) { minDistanceFromScreenCenter = distanceFromScreenCenter; minDistanceFromScreenCenterIndex = i; } } return minDistanceFromScreenCenterIndex; } protected void snapToDestination() { snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION); } private static class ScrollInterpolator implements Interpolator { public ScrollInterpolator() { } public float getInterpolation(float t) { t -= 1.0f; return t*t*t*t*t + 1; } } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) Math.sin(f); } protected void snapToPageWithVelocity(int whichPage, int velocity) { whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1)); int halfScreenSize = getViewportWidth() / 2; final int newX = getScrollForPage(whichPage); int delta = newX - mUnboundedScrollX; int duration = 0; if (Math.abs(velocity) < mMinFlingVelocity) { // If the velocity is low enough, then treat this more as an automatic page advance // as opposed to an apparent physical response to flinging snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); return; } // Here we compute a "distance" that will be used in the computation of the overall // snap duration. This is a function of the actual distance that needs to be traveled; // we keep this value close to half screen size in order to reduce the variance in snap // duration as a function of the distance the page needs to travel. float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize)); float distance = halfScreenSize + halfScreenSize * distanceInfluenceForSnapDuration(distanceRatio); velocity = Math.abs(velocity); velocity = Math.max(mMinSnapVelocity, velocity); // we want the page's snap velocity to approximately match the velocity at which the // user flings, so we scale the duration by a value near to the derivative of the scroll // interpolator at zero, ie. 5. We use 4 to make it a little slower. duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); snapToPage(whichPage, delta, duration); } protected void snapToPage(int whichPage) { snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); } protected void snapToPageImmediately(int whichPage) { snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true); } protected void snapToPage(int whichPage, int duration) { snapToPage(whichPage, duration, false); } protected void snapToPage(int whichPage, int duration, boolean immediate) { whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1)); int newX = getScrollForPage(whichPage); final int sX = mUnboundedScrollX; final int delta = newX - sX; snapToPage(whichPage, delta, duration, immediate); } protected void snapToPage(int whichPage, int delta, int duration) { snapToPage(whichPage, delta, duration, false); } protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) { mNextPage = whichPage; View focusedChild = getFocusedChild(); if (focusedChild != null && whichPage != mCurrentPage && focusedChild == getPageAt(mCurrentPage)) { focusedChild.clearFocus(); } sendScrollAccessibilityEvent(); pageBeginMoving(); awakenScrollBars(duration); if (immediate) { duration = 0; } else if (duration == 0) { duration = Math.abs(delta); } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration); notifyPageSwitchListener(); // Trigger a compute() to finish switching pages if necessary if (immediate) { computeScroll(); } // Defer loading associated pages until the scroll settles mDeferLoadAssociatedPagesUntilScrollCompletes = true; mForceScreenScrolled = true; invalidate(); } public void scrollLeft() { if (getNextPage() > 0) snapToPage(getNextPage() - 1); } public void scrollRight() { if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1); } public int getPageForView(View v) { int result = -1; if (v != null) { ViewParent vp = v.getParent(); int count = getChildCount(); for (int i = 0; i < count; i++) { if (vp == getPageAt(i)) { return i; } } } return result; } /** * @return True is long presses are still allowed for the current touch */ public boolean allowLongPress() { return mAllowLongPress; } @Override public boolean performLongClick() { mCancelTap = true; return super.performLongClick(); } /** * Set true to allow long-press events to be triggered, usually checked by * {@link Launcher} to accept or block dpad-initiated long-presses. */ public void setAllowLongPress(boolean allowLongPress) { mAllowLongPress = allowLongPress; } public static class SavedState extends BaseSavedState { int currentPage = -1; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPage = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(currentPage); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } protected void loadAssociatedPages(int page) { loadAssociatedPages(page, false); } protected void loadAssociatedPages(int page, boolean immediateAndOnly) { if (mContentIsRefreshable) { final int count = getChildCount(); if (page < count) { int lowerPageBound = getAssociatedLowerPageBound(page); int upperPageBound = getAssociatedUpperPageBound(page); if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/" + upperPageBound); // First, clear any pages that should no longer be loaded for (int i = 0; i < count; ++i) { Page layout = (Page) getPageAt(i); if ((i < lowerPageBound) || (i > upperPageBound)) { if (layout.getPageChildCount() > 0) { layout.removeAllViewsOnPage(); } mDirtyPageContent.set(i, true); } } // Next, load any new pages for (int i = 0; i < count; ++i) { if ((i != page) && immediateAndOnly) { continue; } if (lowerPageBound <= i && i <= upperPageBound) { if (mDirtyPageContent.get(i)) { syncPageItems(i, (i == page) && immediateAndOnly); mDirtyPageContent.set(i, false); } } } } } } protected int getAssociatedLowerPageBound(int page) { return Math.max(0, page - 1); } protected int getAssociatedUpperPageBound(int page) { final int count = getChildCount(); return Math.min(page + 1, count - 1); } /** * This method is called ONLY to synchronize the number of pages that the paged view has. * To actually fill the pages with information, implement syncPageItems() below. It is * guaranteed that syncPageItems() will be called for a particular page before it is shown, * and therefore, individual page items do not need to be updated in this method. */ public abstract void syncPages(); /** * This method is called to synchronize the items that are on a particular page. If views on * the page can be reused, then they should be updated within this method. */ public abstract void syncPageItems(int page, boolean immediate); protected void invalidatePageData() { invalidatePageData(-1, false); } protected void invalidatePageData(int currentPage) { invalidatePageData(currentPage, false); } protected void invalidatePageData(int currentPage, boolean immediateAndOnly) { if (!mIsDataReady) { return; } if (mContentIsRefreshable) { // Force all scrolling-related behavior to end mScroller.forceFinished(true); mNextPage = INVALID_PAGE; // Update all the pages syncPages(); // We must force a measure after we've loaded the pages to update the content width and // to determine the full scroll width measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); // Set a new page as the current page if necessary if (currentPage > -1) { setCurrentPage(Math.min(getPageCount() - 1, currentPage)); } // Mark each of the pages as dirty final int count = getChildCount(); mDirtyPageContent.clear(); for (int i = 0; i < count; ++i) { mDirtyPageContent.add(true); } // Load any pages that are necessary for the current window of views loadAssociatedPages(mCurrentPage, immediateAndOnly); requestLayout(); } if (isPageMoving()) { // If the page is moving, then snap it to the final position to ensure we don't get // stuck between pages snapToDestination(); } } // Animate the drag view back to the original position void animateDragViewToOriginalPosition() { if (mDragView != null) { AnimatorSet anim = new AnimatorSet(); anim.setDuration(REORDERING_DROP_REPOSITION_DURATION); anim.playTogether( ObjectAnimator.ofFloat(mDragView, "translationX", 0f), ObjectAnimator.ofFloat(mDragView, "translationY", 0f), ObjectAnimator.ofFloat(mDragView, "scaleX", 1f), ObjectAnimator.ofFloat(mDragView, "scaleY", 1f)); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { onPostReorderingAnimationCompleted(); } }); anim.start(); } } protected void onStartReordering() { // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.) mTouchState = TOUCH_STATE_REORDERING; mIsReordering = true; // We must invalidate to trigger a redraw to update the layers such that the drag view // is always drawn on top invalidate(); } private void onPostReorderingAnimationCompleted() { // Trigger the callback when reordering has settled --mPostReorderingPreZoomInRemainingAnimationCount; if (mPostReorderingPreZoomInRunnable != null && mPostReorderingPreZoomInRemainingAnimationCount == 0) { mPostReorderingPreZoomInRunnable.run(); mPostReorderingPreZoomInRunnable = null; } } protected void onEndReordering() { mIsReordering = false; } public boolean startReordering(View v) { int dragViewIndex = indexOfChild(v); if (mTouchState != TOUCH_STATE_REST) return false; mTempVisiblePagesRange[0] = 0; mTempVisiblePagesRange[1] = getPageCount() - 1; getOverviewModePages(mTempVisiblePagesRange); mReorderingStarted = true; // Check if we are within the reordering range if (mTempVisiblePagesRange[0] <= dragViewIndex && dragViewIndex <= mTempVisiblePagesRange[1]) { // Find the drag view under the pointer mDragView = getChildAt(dragViewIndex); mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start(); mDragViewBaselineLeft = mDragView.getLeft(); disableFreeScroll(-1); onStartReordering(); return true; } return false; } boolean isReordering(boolean testTouchState) { boolean state = mIsReordering; if (testTouchState) { state &= (mTouchState == TOUCH_STATE_REORDERING); } return state; } void endReordering() { // For simplicity, we call endReordering sometimes even if reordering was never started. // In that case, we don't want to do anything. if (!mReorderingStarted) return; mReorderingStarted = false; // If we haven't flung-to-delete the current child, then we just animate the drag view // back into position final Runnable onCompleteRunnable = new Runnable() { @Override public void run() { onEndReordering(); } }; if (!mDeferringForDelete) { mPostReorderingPreZoomInRunnable = new Runnable() { public void run() { onCompleteRunnable.run(); enableFreeScroll(); }; }; mPostReorderingPreZoomInRemainingAnimationCount = NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT; // Snap to the current page snapToPage(indexOfChild(mDragView), 0); // Animate the drag view back to the front position animateDragViewToOriginalPosition(); } else { // Handled in post-delete-animation-callbacks } } /* * Flinging to delete - IN PROGRESS */ private PointF isFlingingToDelete() { ViewConfiguration config = ViewConfiguration.get(getContext()); mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity()); if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) { // Do a quick dot product test to ensure that we are flinging upwards PointF vel = new PointF(mVelocityTracker.getXVelocity(), mVelocityTracker.getYVelocity()); PointF upVec = new PointF(0f, -1f); float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) / (vel.length() * upVec.length())); if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) { return vel; } } return null; } /** * Creates an animation from the current drag view along its current velocity vector. * For this animation, the alpha runs for a fixed duration and we update the position * progressively. */ private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener { private View mDragView; private PointF mVelocity; private Rect mFrom; private long mPrevTime; private float mFriction; private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f); public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from, long startTime, float friction) { mDragView = dragView; mVelocity = vel; mFrom = from; mPrevTime = startTime; mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction); } @Override public void onAnimationUpdate(ValueAnimator animation) { float t = ((Float) animation.getAnimatedValue()).floatValue(); long curTime = AnimationUtils.currentAnimationTimeMillis(); mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f); mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f); mDragView.setTranslationX(mFrom.left); mDragView.setTranslationY(mFrom.top); mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t)); mVelocity.x *= mFriction; mVelocity.y *= mFriction; mPrevTime = curTime; } }; private static final int ANIM_TAG_KEY = 100; private Runnable createPostDeleteAnimationRunnable(final View dragView) { return new Runnable() { @Override public void run() { int dragViewIndex = indexOfChild(dragView); // For each of the pages around the drag view, animate them from the previous // position to the new position in the layout (as a result of the drag view moving // in the layout) // NOTE: We can make an assumption here because we have side-bound pages that we // will always have pages to animate in from the left getOverviewModePages(mTempVisiblePagesRange); boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]); boolean slideFromLeft = (isLastWidgetPage || dragViewIndex > mTempVisiblePagesRange[0]); // Setup the scroll to the correct page before we swap the views if (slideFromLeft) { snapToPageImmediately(dragViewIndex - 1); } int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]); int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1); int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 ); int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex); ArrayList<Animator> animations = new ArrayList<Animator>(); for (int i = lowerIndex; i <= upperIndex; ++i) { View v = getChildAt(i); // dragViewIndex < pageUnderPointIndex, so after we remove the // drag view all subsequent views to pageUnderPointIndex will // shift down. int oldX = 0; int newX = 0; if (slideFromLeft) { if (i == 0) { // Simulate the page being offscreen with the page spacing oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i) - mPageSpacing; } else { oldX = getViewportOffsetX() + getChildOffset(i - 1); } newX = getViewportOffsetX() + getChildOffset(i); } else { oldX = getChildOffset(i) - getChildOffset(i - 1); newX = 0; } // Animate the view translation from its old position to its new // position AnimatorSet anim = (AnimatorSet) v.getTag(); if (anim != null) { anim.cancel(); } // Note: Hacky, but we want to skip any optimizations to not draw completely // hidden views v.setAlpha(Math.max(v.getAlpha(), 0.01f)); v.setTranslationX(oldX - newX); anim = new AnimatorSet(); anim.playTogether( ObjectAnimator.ofFloat(v, "translationX", 0f), ObjectAnimator.ofFloat(v, "alpha", 1f)); animations.add(anim); v.setTag(ANIM_TAG_KEY, anim); } AnimatorSet slideAnimations = new AnimatorSet(); slideAnimations.playTogether(animations); slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION); slideAnimations.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mDeferringForDelete = false; onEndReordering(); onRemoveViewAnimationCompleted(); } }); slideAnimations.start(); removeView(dragView); onRemoveView(dragView, true); } }; } public void onFlingToDelete(PointF vel) { final long startTime = AnimationUtils.currentAnimationTimeMillis(); // NOTE: Because it takes time for the first frame of animation to actually be // called and we expect the animation to be a continuation of the fling, we have // to account for the time that has elapsed since the fling finished. And since // we don't have a startDelay, we will always get call to update when we call // start() (which we want to ignore). final TimeInterpolator tInterpolator = new TimeInterpolator() { private int mCount = -1; private long mStartTime; private float mOffset; /* Anonymous inner class ctor */ { mStartTime = startTime; } @Override public float getInterpolation(float t) { if (mCount < 0) { mCount++; } else if (mCount == 0) { mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() - mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION); mCount++; } return Math.min(1f, mOffset + t); } }; final Rect from = new Rect(); final View dragView = mDragView; from.left = (int) dragView.getTranslationX(); from.top = (int) dragView.getTranslationY(); AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel, from, startTime, FLING_TO_DELETE_FRICTION); final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); // Create and start the animation ValueAnimator mDropAnim = new ValueAnimator(); mDropAnim.setInterpolator(tInterpolator); mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION); mDropAnim.setFloatValues(0f, 1f); mDropAnim.addUpdateListener(updateCb); mDropAnim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { onAnimationEndRunnable.run(); } }); mDropAnim.start(); mDeferringForDelete = true; } /* Drag to delete */ private boolean isHoveringOverDeleteDropTarget(int x, int y) { if (mDeleteDropTarget != null) { mAltTmpRect.set(0, 0, 0, 0); View parent = (View) mDeleteDropTarget.getParent(); if (parent != null) { parent.getGlobalVisibleRect(mAltTmpRect); } mDeleteDropTarget.getGlobalVisibleRect(mTmpRect); mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top); return mTmpRect.contains(x, y); } return false; } protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {} private void onDropToDelete() { final View dragView = mDragView; final float toScale = 0f; final float toAlpha = 0f; // Create and start the complex animation ArrayList<Animator> animations = new ArrayList<Animator>(); AnimatorSet motionAnim = new AnimatorSet(); motionAnim.setInterpolator(new DecelerateInterpolator(2)); motionAnim.playTogether( ObjectAnimator.ofFloat(dragView, "scaleX", toScale), ObjectAnimator.ofFloat(dragView, "scaleY", toScale)); animations.add(motionAnim); AnimatorSet alphaAnim = new AnimatorSet(); alphaAnim.setInterpolator(new LinearInterpolator()); alphaAnim.playTogether( ObjectAnimator.ofFloat(dragView, "alpha", toAlpha)); animations.add(alphaAnim); final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); AnimatorSet anim = new AnimatorSet(); anim.playTogether(animations); anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION); anim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { onAnimationEndRunnable.run(); } }); anim.start(); mDeferringForDelete = true; } /* Accessibility */ @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setScrollable(getPageCount() > 1); if (getCurrentPage() < getPageCount() - 1) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (getCurrentPage() > 0) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } @Override public void sendAccessibilityEvent(int eventType) { // Don't let the view send real scroll events. if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) { super.sendAccessibilityEvent(eventType); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setScrollable(true); } @Override public boolean performAccessibilityAction(int action, Bundle arguments) { if (super.performAccessibilityAction(action, arguments)) { return true; } switch (action) { case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (getCurrentPage() < getPageCount() - 1) { scrollRight(); return true; } } break; case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (getCurrentPage() > 0) { scrollLeft(); return true; } } break; } return false; } protected String getCurrentPageDescription() { return String.format(getContext().getString(R.string.default_scroll_format), getNextPage() + 1, getChildCount()); } @Override public boolean onHoverEvent(android.view.MotionEvent event) { return true; } }
true
false
null
null
diff --git a/drools-core/src/main/java/org/drools/base/mvel/MVELCompilationUnit.java b/drools-core/src/main/java/org/drools/base/mvel/MVELCompilationUnit.java index c3f8e96c83..548bd7216a 100644 --- a/drools-core/src/main/java/org/drools/base/mvel/MVELCompilationUnit.java +++ b/drools-core/src/main/java/org/drools/base/mvel/MVELCompilationUnit.java @@ -1,773 +1,773 @@ /* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.base.mvel; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.util.*; import org.drools.FactHandle; import org.drools.RuntimeDroolsException; import org.drools.base.EvaluatorWrapper; import org.drools.base.ModifyInterceptor; import org.drools.common.AgendaItem; import org.drools.common.InternalFactHandle; import org.drools.common.InternalWorkingMemory; import org.drools.definition.rule.Rule; import org.drools.reteoo.LeftTuple; import org.drools.rule.Declaration; import org.drools.rule.MVELDialectRuntimeData; import org.drools.spi.GlobalResolver; import org.drools.spi.KnowledgeHelper; import org.mvel2.DataConversion; import org.mvel2.MVEL; import org.mvel2.ParserConfiguration; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.*; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.util.SimpleVariableSpaceModel; public class MVELCompilationUnit implements Externalizable, Cloneable { private static final long serialVersionUID = 510l; private String name; private String expression; private String[] globalIdentifiers; private EvaluatorWrapper[] operators; private Declaration[] previousDeclarations; private Declaration[] localDeclarations; private String[] otherIdentifiers; private String[] inputIdentifiers; private String[] inputTypes; private int languageLevel; private boolean strictMode; private SimpleVariableSpaceModel varModel; private int allVarsLength; public static final Map<String, Interceptor> INTERCEPTORS = new InterceptorMap(); static { //for handling dates as string literals DataConversion.addConversionHandler( Date.class, new MVELDateCoercion() ); DataConversion.addConversionHandler( Calendar.class, new MVELCalendarCoercion() ); } private static final Map<String, Class< ? >> primitivesMap = new HashMap<String, Class< ? >>(); static { primitivesMap.put( "int", int.class ); primitivesMap.put( "boolean", boolean.class ); primitivesMap.put( "float", float.class ); primitivesMap.put( "long", long.class ); primitivesMap.put( "short", short.class ); primitivesMap.put( "byte", byte.class ); primitivesMap.put( "double", double.class ); primitivesMap.put( "char", char.class ); } public static final Object COMPILER_LOCK = new Object(); public MVELCompilationUnit() { } public MVELCompilationUnit(String name, String expression, String[] globalIdentifiers, EvaluatorWrapper[] operators, Declaration[] previousDeclarations, Declaration[] localDeclarations, String[] otherIdentifiers, String[] inputIdentifiers, String[] inputTypes, int languageLevel, boolean strictMode) { this.name = name; this.expression = expression; this.globalIdentifiers = globalIdentifiers; this.operators = operators; this.previousDeclarations = previousDeclarations; this.localDeclarations = localDeclarations; this.otherIdentifiers = otherIdentifiers; this.inputIdentifiers = inputIdentifiers; this.inputTypes = inputTypes; this.languageLevel = languageLevel; this.strictMode = strictMode; } public String getExpression() { return expression; } public void writeExternal( ObjectOutput out ) throws IOException { out.writeUTF( name ); out.writeUTF( expression ); out.writeObject( globalIdentifiers ); out.writeObject( operators ); out.writeObject( previousDeclarations ); out.writeObject( localDeclarations ); out.writeObject( otherIdentifiers ); out.writeObject( inputIdentifiers ); out.writeObject( inputTypes ); out.writeInt( languageLevel ); out.writeBoolean( strictMode ); } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { name = in.readUTF(); expression = in.readUTF(); globalIdentifiers = (String[]) in.readObject(); operators = (EvaluatorWrapper[]) in.readObject(); previousDeclarations = (Declaration[]) in.readObject(); localDeclarations = (Declaration[]) in.readObject(); otherIdentifiers = (String[]) in.readObject(); inputIdentifiers = (String[]) in.readObject(); inputTypes = (String[]) in.readObject(); languageLevel = in.readInt(); strictMode = in.readBoolean(); } public Serializable getCompiledExpression(MVELDialectRuntimeData runtimeData ) { ParserConfiguration conf = runtimeData.getParserConfiguration(); final ParserContext parserContext = new ParserContext( conf ); if ( MVELDebugHandler.isDebugMode() ) { parserContext.setDebugSymbols( true ); } parserContext.setStrictTypeEnforcement( strictMode ); parserContext.setStrongTyping( strictMode ); parserContext.setIndexAllocation( true ); if ( INTERCEPTORS != null ) { parserContext.setInterceptors(INTERCEPTORS); } parserContext.addIndexedInput( inputIdentifiers ); String identifier = null; String type = null; try { for ( int i = 0, length = inputIdentifiers.length; i < length; i++ ) { identifier = inputIdentifiers[i]; type = inputTypes[i]; Class< ? > cls = loadClass( runtimeData.getRootClassLoader(), inputTypes[i] ); parserContext.addInput( inputIdentifiers[i], cls ); } } catch ( ClassNotFoundException e ) { throw new RuntimeDroolsException( "Unable to resolve class '" + type + "' for identifier '" + identifier ); } parserContext.setSourceFile( name ); String[] varNames = parserContext.getIndexedVarNames(); ExecutableStatement stmt = (ExecutableStatement) compile( expression, runtimeData.getRootClassLoader(), parserContext, languageLevel ); Set<String> localNames = parserContext.getVariables().keySet(); parserContext.addIndexedLocals(localNames); String[] locals = localNames.toArray(new String[localNames.size()]); String[] allVars = new String[varNames.length + locals.length]; System.arraycopy(varNames, 0, allVars, 0, varNames.length); System.arraycopy(locals, 0, allVars, varNames.length, locals.length); this.varModel = new SimpleVariableSpaceModel(allVars); this.allVarsLength = allVars.length; return stmt; } public VariableResolverFactory createFactory() { Object[] vals = new Object[inputIdentifiers.length]; VariableResolverFactory factory = varModel.createFactory( vals ); DroolsVarFactory df = new DroolsVarFactory(); factory.setNextFactory( df ); return factory; } public VariableResolverFactory getFactory(final Object knowledgeHelper, final Rule rule, final Object rightObject, final LeftTuple tuples, final Object[] otherVars, final InternalWorkingMemory workingMemory, final GlobalResolver globals) { VariableResolverFactory factory = createFactory(); updateFactory(knowledgeHelper, rule, rightObject, tuples, otherVars, workingMemory, globals, factory); return factory; } public void updateFactory(Object knowledgeHelper, Rule rule, Object rightObject, LeftTuple tuples, Object[] otherVars, InternalWorkingMemory workingMemory, GlobalResolver globals, VariableResolverFactory factory) { int varLength = inputIdentifiers.length; int i = 0; if ( rightObject != null ) { factory.getIndexedVariableResolver( i++ ).setValue( rightObject ); } factory.getIndexedVariableResolver( i++ ).setValue( knowledgeHelper ); factory.getIndexedVariableResolver( i++ ).setValue( knowledgeHelper ); factory.getIndexedVariableResolver( i++ ).setValue( rule ); if ( globalIdentifiers != null ) { for ( int j = 0, length = globalIdentifiers.length; j < length; j++ ) { factory.getIndexedVariableResolver( i++ ).setValue( globals.resolveGlobal( this.globalIdentifiers[j] ) ); } } InternalFactHandle[] handles; if( tuples != null ) { handles = tuples.toFactHandles(); } else { handles = new InternalFactHandle[0]; } if ( operators != null ) { for ( int j = 0, length = operators.length; j < length; j++ ) { // TODO: need to have one operator per working memory factory.getIndexedVariableResolver( i++ ).setValue( operators[j].setWorkingMemory( workingMemory ) ); if ( operators[j].getLeftBinding() != null ) { if( operators[j].getLeftBinding().getIdentifier().equals( "this" )) { operators[j].setLeftHandle( (InternalFactHandle) workingMemory.getFactHandle( rightObject ) ); } else { operators[j].setLeftHandle( getFactHandle( operators[j].getLeftBinding(), handles ) ); } } if ( operators[j].getRightBinding() != null ) { if( operators[j].getRightBinding().getIdentifier().equals( "this" )) { operators[j].setRightHandle( (InternalFactHandle) workingMemory.getFactHandle( rightObject ) ); } else { operators[j].setRightHandle( getFactHandle( operators[j].getRightBinding(), handles ) ); } } } } IdentityHashMap<Object, FactHandle> identityMap = null; if ( knowledgeHelper != null ) { identityMap = new IdentityHashMap<Object, FactHandle>(); } if ( tuples != null ) { if ( this.previousDeclarations != null && this.previousDeclarations.length > 0 ) { // Consequences with 'or's will have different declaration offsets, so use the one's from the RTN's subrule. Declaration[] prevDecl = this.previousDeclarations; if ( knowledgeHelper != null ) { // we know this is a rule prevDecl = ((AgendaItem)((KnowledgeHelper)knowledgeHelper).getActivation()).getRuleTerminalNode().getDeclarations(); } for ( int j = 0, length = prevDecl.length; j < length; j++ ) { Declaration decl = prevDecl[j]; InternalFactHandle handle = getFactHandle( decl, handles ); Object o = decl.getValue( workingMemory, handle.getObject() ); if ( knowledgeHelper != null && decl.isPatternDeclaration() ) { identityMap.put( o, handle ); } factory.getIndexedVariableResolver( i++ ).setValue( o ); } } } if ( this.localDeclarations != null && this.localDeclarations.length > 0 ) { for ( int j = 0, length = this.localDeclarations.length; j < length; j++ ) { Declaration decl = this.localDeclarations[j]; Object o = decl.getValue( workingMemory, rightObject ); factory.getIndexedVariableResolver( i++ ).setValue( o ); } } int otherVarsPos = 0; if ( otherVars != null ) { otherVarsPos = i; for ( Object o : otherVars ) { factory.getIndexedVariableResolver( i++ ).setValue( o ); } } int otherVarsLength = i - otherVarsPos; for ( i = varLength; i < this.allVarsLength; i++ ) { // null all local vars factory.getIndexedVariableResolver( i ).setValue( null ); } DroolsVarFactory df = ( DroolsVarFactory ) factory.getNextFactory(); df.setOtherVarsPos( otherVarsPos ); df.setOtherVarsLength( otherVarsLength ); if ( knowledgeHelper != null && knowledgeHelper instanceof KnowledgeHelper ) { KnowledgeHelper kh = ( KnowledgeHelper ) knowledgeHelper; kh.setIdentityMap( identityMap ); df.setKnowledgeHelper( kh ); } } private static InternalFactHandle getFactHandle( Declaration declaration, InternalFactHandle[] handles ) { return handles.length >= declaration.getPattern().getOffset() ? handles[declaration.getPattern().getOffset()] : null; } public static Serializable compile( final String text, final ClassLoader classLoader, final ParserContext parserContext, final int languageLevel ) { MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true; MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; MVEL.COMPILER_OPT_ALLOW_RESOLVE_INNERCLASSES_WITH_DOTNOTATION = true; MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = true; // Just temporary as PropertyHandler is not working with ASM OptimizerFactory.setDefaultOptimizer( OptimizerFactory.SAFE_REFLECTIVE ); if ( MVELDebugHandler.isDebugMode() ) { parserContext.setDebugSymbols( true ); } return MVEL.compileExpression( text.trim(), parserContext ); } public static Class loadClass( ClassLoader classLoader, String className ) throws ClassNotFoundException { Class cls = primitivesMap.get( className ); if ( cls == null ) { cls = classLoader.loadClass( className ); } return cls; } public void replaceDeclaration( Declaration declaration, Declaration resolved ) { if ( previousDeclarations != null ) { for ( int i = 0; i < previousDeclarations.length; i++ ) { if ( previousDeclarations[i].equals( declaration ) ) { previousDeclarations[i] = resolved; } } } if ( localDeclarations != null ) { for ( int i = 0; i < localDeclarations.length; i++ ) { if ( localDeclarations[i].equals( declaration ) ) { localDeclarations[i] = resolved; } } } } @Override public MVELCompilationUnit clone() { MVELCompilationUnit unit = new MVELCompilationUnit( name, expression, globalIdentifiers, operators, - previousDeclarations, - localDeclarations, + previousDeclarations != null ? Arrays.copyOf(previousDeclarations, previousDeclarations.length) : null, + localDeclarations != null ? Arrays.copyOf(localDeclarations, localDeclarations.length) : null, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, strictMode ); unit.varModel = this.varModel; return unit; } public static long getSerialversionuid() { return serialVersionUID; } public String getName() { return name; } public String[] getGlobalIdentifiers() { return globalIdentifiers; } public Declaration[] getPreviousDeclarations() { return previousDeclarations; } public void setPreviousDeclarations( Declaration[] previousDeclarations ) { this.previousDeclarations = previousDeclarations; } public Declaration[] getLocalDeclarations() { return localDeclarations; } public String[] getOtherIdentifiers() { return otherIdentifiers; } public String[] getInputIdentifiers() { return inputIdentifiers; } public String[] getInputTypes() { return inputTypes; } public int getLanguageLevel() { return languageLevel; } public boolean isStrictMode() { return strictMode; } public static Map getInterceptors() { return INTERCEPTORS; } public static Map<String, Class< ? >> getPrimitivesmap() { return primitivesMap; } public static Object getCompilerLock() { return COMPILER_LOCK; } public static class DroolsVarFactory implements VariableResolverFactory { private KnowledgeHelper knowledgeHelper; private int otherVarsPos; private int otherVarsLength; // private Object[] values; // public DroolsMVELIndexedFactory(String[] varNames, // Object[] values) { // this.indexedVariableNames = varNames; // this.values = values; // this.indexedVariableResolvers = createResolvers( values ); // } // // public DroolsMVELIndexedFactory(String[] varNames, // Object[] values, // VariableResolverFactory factory) { // this.indexedVariableNames = varNames; // this.values = values; // this.nextFactory = new MapVariableResolverFactory(); // this.nextFactory.setNextFactory( factory ); // this.indexedVariableResolvers = createResolvers( values ); // } // // private static VariableResolver[] createResolvers( Object[] values ) { // VariableResolver[] vr = new VariableResolver[values.length]; // for ( int i = 0; i < values.length; i++ ) { // vr[i] = new IndexVariableResolver( i, // values ); // } // return vr; // } public KnowledgeHelper getKnowledgeHelper() { return this.knowledgeHelper ; } public void setKnowledgeHelper(KnowledgeHelper kh) { this.knowledgeHelper = kh; } public int getOtherVarsPos() { return otherVarsPos; } public void setOtherVarsPos( int otherVarsPos ) { this.otherVarsPos = otherVarsPos; } public int getOtherVarsLength() { return otherVarsLength; } public void setOtherVarsLength( int otherVarsLength ) { this.otherVarsLength = otherVarsLength; } public VariableResolver createIndexedVariable( int index, String name, Object value ) { throw new UnsupportedOperationException(); // indexedVariableResolvers[index].setValue( value ); // return indexedVariableResolvers[index]; } public VariableResolver getIndexedVariableResolver( int index ) { throw new UnsupportedOperationException(); //return indexedVariableResolvers[index]; } public VariableResolver createVariable( String name, Object value ) { throw new UnsupportedOperationException(); // VariableResolver vr = getResolver( name ); // if ( vr != null ) { // vr.setValue( value ); // return vr; // } else { // if ( nextFactory == null ) nextFactory = new MapVariableResolverFactory( new HashMap() ); // return nextFactory.createVariable( name, // value ); // } } public VariableResolver createVariable( String name, Object value, Class< ? > type ) { throw new UnsupportedOperationException(); // VariableResolver vr = getResolver( name ); // if ( vr != null ) { // if ( vr.getType() != null ) { // throw new RuntimeException( "variable already defined within scope: " + vr.getType() + " " + name ); // } else { // vr.setValue( value ); // return vr; // } // } else { // if ( nextFactory == null ) nextFactory = new MapVariableResolverFactory( new HashMap() ); // return nextFactory.createVariable( name, // value, // type ); // } } public VariableResolver getVariableResolver( String name ) { return null; } public boolean isResolveable( String name ) { //return isTarget( name ) || (nextFactory != null && nextFactory.isResolveable( name )); return false; } protected VariableResolver addResolver( String name, VariableResolver vr ) { throw new UnsupportedOperationException(); // variableResolvers.put( name, // vr ); // return vr; } private VariableResolver getResolver( String name ) { // for ( int i = 0; i < indexedVariableNames.length; i++ ) { // if ( indexedVariableNames[i].equals( name ) ) { // return indexedVariableResolvers[i]; // } // } return null; } public boolean isTarget( String name ) { // for ( String indexedVariableName : indexedVariableNames ) { // if ( indexedVariableName.equals( name ) ) { // return true; // } // } return false; } public Set<String> getKnownVariables() { // Set<String> vars = new HashSet<String>(); // for ( int i = 0; i < indexedVariableNames.length; i++ ) { // vars.add( indexedVariableNames[i] ); // } return Collections.emptySet(); } public void clear() { // variableResolvers.clear(); } public boolean isIndexedFactory() { return false; } public VariableResolver createIndexedVariable(int index, String name, Object value, Class< ? > typee) { // TODO Auto-generated method stub return null; } public VariableResolver setIndexedVariableResolver(int index, VariableResolver variableResolver) { // TODO Auto-generated method stub return null; } public VariableResolverFactory getNextFactory() { // TODO Auto-generated method stub return null; } public VariableResolverFactory setNextFactory(VariableResolverFactory resolverFactory) { // TODO Auto-generated method stub return null; } public int variableIndexOf(String name) { // TODO Auto-generated method stub return 0; } public boolean tiltFlag() { // TODO Auto-generated method stub return false; } public void setTiltFlag(boolean tilt) { // TODO Auto-generated method stub } } public static class PropertyHandlerFactoryFixer extends PropertyHandlerFactory { public static Map<Class, PropertyHandler> getPropertyHandlerClass() { return propertyHandlerClass; } } private static class InterceptorMap implements Map<String, Interceptor> { public int size() { return 1; } public boolean isEmpty() { return false; } public boolean containsKey(Object key) { return key != null && key.equals("Modify"); } public boolean containsValue(Object value) { return false; } public Interceptor get(Object key) { return new ModifyInterceptor(); } public Interceptor put(String key, Interceptor value) { throw new UnsupportedOperationException(); } public Interceptor remove(Object key) { throw new UnsupportedOperationException(); } public void putAll(Map<? extends String, ? extends Interceptor> m) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public Set<String> keySet() { return new HashSet<String>() {{ add("Modify"); }}; } public Collection<Interceptor> values() { return new ArrayList<Interceptor>() {{ add(new ModifyInterceptor()); }}; } public Set<Entry<String, Interceptor>> entrySet() { return new HashSet<Entry<String, Interceptor>>() {{ add(new Entry<String, Interceptor>() { public String getKey() { return "Modify"; } public Interceptor getValue() { return new ModifyInterceptor(); } public Interceptor setValue(Interceptor value) { throw new UnsupportedOperationException(); } }); }}; } } } diff --git a/drools-core/src/main/java/org/drools/rule/Declaration.java b/drools-core/src/main/java/org/drools/rule/Declaration.java index 97879bc933..9139b63324 100644 --- a/drools-core/src/main/java/org/drools/rule/Declaration.java +++ b/drools-core/src/main/java/org/drools/rule/Declaration.java @@ -1,374 +1,374 @@ package org.drools.rule; /* * $Id: Declaration.java,v 1.1 2005/07/26 01:06:31 mproctor Exp $ * * Copyright 2001-2003 (C) The Werken Company. All Rights Reserved. * * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "drools" must not be used to endorse or promote products derived * from this Software without prior written permission of The Werken Company. * For written permission, please contact [email protected]. * * 4. Products derived from this Software may not be called "drools" nor may * "drools" appear in their names without prior written permission of The Werken * Company. "drools" is a trademark of The Werken Company. * * 5. Due credit should be given to The Werken Company. (http://werken.com/) * * THIS SOFTWARE IS PROVIDED BY THE WERKEN COMPANY AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE WERKEN COMPANY OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Method; import java.util.Collection; import java.util.Iterator; import org.drools.RuntimeDroolsException; import org.drools.base.ValueType; import org.drools.base.extractors.SelfReferenceClassFieldReader; import org.drools.common.InternalWorkingMemory; import org.drools.core.util.ClassUtils; import org.drools.spi.AcceptsReadAccessor; import org.drools.spi.InternalReadAccessor; import static org.drools.core.util.ClassUtils.canonicalName; import static org.drools.core.util.ClassUtils.convertFromPrimitiveType; public class Declaration implements Externalizable, AcceptsReadAccessor, Cloneable { // ------------------------------------------------------------ // Instance members // ------------------------------------------------------------ private static final long serialVersionUID = 510l; /** The identifier for the variable. */ private String identifier; private String bindingName; private InternalReadAccessor readAccessor; private Pattern pattern; private boolean internalFact; // ------------------------------------------------------------ // Constructors // ------------------------------------------------------------ public Declaration() { this( null, null, null ); } /** * Construct. * * @param identifier * The name of the variable. * @param objectType * The type of this variable declaration. * @param order * The index within a rule. */ public Declaration(final String identifier, final Pattern pattern) { this( identifier, null, pattern, false ); } /** * Construct. * * @param identifier * The name of the variable. * @param objectType * The type of this variable declaration. * @param order * The index within a rule. */ public Declaration(final String identifier, final InternalReadAccessor extractor, final Pattern pattern) { this( identifier, extractor, pattern, false ); } /** * Construct. * * @param identifier * The name of the variable. * @param objectType * The type of this variable declaration. * @param order * The index within a rule. * @param internalFact * True if this is an internal fact created by the engine, like a collection result * of a collect CE */ public Declaration(final String identifier, final InternalReadAccessor extractor, final Pattern pattern, final boolean internalFact) { this.identifier = identifier; this.readAccessor = extractor; this.pattern = pattern; this.internalFact = internalFact; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { identifier = (String) in.readObject(); readAccessor = (InternalReadAccessor) in.readObject(); pattern = (Pattern) in.readObject(); internalFact = in.readBoolean(); bindingName = (String) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( identifier ); out.writeObject( readAccessor ); out.writeObject( pattern ); out.writeBoolean( internalFact ); out.writeObject( bindingName ); } public void setReadAccessor(InternalReadAccessor readAccessor) { this.readAccessor = readAccessor; } // ------------------------------------------------------------ // Instance methods // ------------------------------------------------------------ /** * Retrieve the variable's identifier. * * @return The variable's identifier. */ public String getIdentifier() { return this.identifier; } public String getBindingName() { return bindingName != null ? bindingName : identifier; } public void setBindingName(String bindingName) { this.bindingName = bindingName; } /** * Retrieve the <code>ValueType</code>. * * @return The ValueType. */ public ValueType getValueType() { return this.readAccessor.getValueType(); } /** * Returns the index of the pattern * * @return the pattern */ public Pattern getPattern() { return this.pattern; } public void setPattern(final Pattern pattern) { this.pattern = pattern; } /** * Returns true if this declaration is a pattern declaration * @return */ public boolean isPatternDeclaration() { return ( this.pattern != null && this.pattern.getDeclaration() == this ) || this.getIdentifier().equals( "this" ) ; } /** * Returns the Extractor expression * * @return */ public InternalReadAccessor getExtractor() { return this.readAccessor; } public Object getValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getValue( workingMemory, object ); } public char getCharValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getCharValue( workingMemory, object ); } public int getIntValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getIntValue( workingMemory, object ); } public byte getByteValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getByteValue( workingMemory, object ); } public short getShortValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getShortValue( workingMemory, object ); } public long getLongValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getLongValue( workingMemory, object ); } public float getFloatValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getFloatValue( workingMemory, object ); } public double getDoubleValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getDoubleValue( workingMemory, object ); } public boolean getBooleanValue(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getBooleanValue( workingMemory, object ); } public int getHashCode(InternalWorkingMemory workingMemory, final Object object) { return this.readAccessor.getHashCode( workingMemory, object ); } public boolean isGlobal() { if( this.readAccessor == null ) return false; return this.readAccessor.isGlobal(); } public Method getNativeReadMethod() { if ( this.readAccessor != null ) { return this.readAccessor.getNativeReadMethod(); } else { // This only happens if there was an error else where, such as building the initial declaration binding // return getValue to avoid null pointers, so rest of drl can attempt to build try { return this.getClass().getDeclaredMethod( "getValue", new Class[]{InternalWorkingMemory.class, Object.class} ); } catch ( final Exception e ) { throw new RuntimeDroolsException( "This is a bug. Please report to development team: " + e.getMessage(), e ); } } } public String getNativeReadMethodName() { return readAccessor != null ? readAccessor.getNativeReadMethodName() : "getValue"; } private transient String cachedTypeName; public String getTypeName() { if (cachedTypeName == null) { // we assume that null extractor errors are reported else where cachedTypeName = getExtractor() != null ? canonicalName(getExtractor().getExtractToClass()) : "java.lang.Object"; } return cachedTypeName; } private transient String cachedBoxedTypeName; public String getBoxedTypeName() { if (cachedBoxedTypeName == null) { // we assume that null extractor errors are reported else where cachedBoxedTypeName = getExtractor() != null ? canonicalName(convertFromPrimitiveType(getExtractor().getExtractToClass())) : "java.lang.Object"; } return cachedBoxedTypeName; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public String toString() { return "(" + this.readAccessor.getValueType() + ") " + this.identifier; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * this.pattern.getOffset(); result = PRIME * this.readAccessor.hashCode(); result = PRIME * this.identifier.hashCode(); return result; } public boolean equals(final Object object) { if ( this == object ) { return true; } if ( object == null || getClass() != object.getClass() ) { return false; } final Declaration other = (Declaration) object; return this.pattern.getOffset() == other.pattern.getOffset() && this.identifier.equals( other.identifier ) && this.readAccessor.equals( other.readAccessor ); } public boolean isInternalFact() { return internalFact; } - public Object clone() { + public Declaration clone() { return new Declaration( this.identifier, this.readAccessor, this.pattern ); } } diff --git a/drools-core/src/main/java/org/drools/rule/Pattern.java b/drools-core/src/main/java/org/drools/rule/Pattern.java index d0a386edd3..014ec4dd82 100644 --- a/drools-core/src/main/java/org/drools/rule/Pattern.java +++ b/drools-core/src/main/java/org/drools/rule/Pattern.java @@ -1,418 +1,418 @@ /* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.rule; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; import org.drools.base.ClassObjectType; import org.drools.rule.constraint.MvelConstraint; import org.drools.spi.AcceptsClassObjectType; import org.drools.spi.Constraint; import org.drools.spi.ObjectType; import org.drools.spi.PatternExtractor; import org.drools.spi.Constraint.ConstraintType; public class Pattern implements RuleConditionElement, AcceptsClassObjectType, Externalizable { private static final long serialVersionUID = 510l; private ObjectType objectType; private List<Constraint> constraints = Collections.EMPTY_LIST; private Declaration declaration; private Map<String, Declaration> declarations; private int index; private PatternSource source; private List<Behavior> behaviors; private List<String> listenedProperties; public static final String ATTR_LISTENED_PROPS = "watch"; // this is the offset of the related fact inside a tuple. i.e: // the position of the related fact inside the tuple; private int offset; public Pattern() { this( 0, null ); } public Pattern(final int index, final ObjectType objectType) { this( index, index, objectType, null ); } public Pattern(final int index, final ObjectType objectType, final String identifier) { this( index, index, objectType, identifier ); } public Pattern(final int index, final int offset, final ObjectType objectType, final String identifier) { this( index, offset, objectType, identifier, false ); } public Pattern(final int index, final int offset, final ObjectType objectType, final String identifier, final boolean isInternalFact) { this.index = index; this.offset = offset; this.objectType = objectType; if ( identifier != null && (!identifier.equals( "" )) ) { this.declaration = new Declaration( identifier, new PatternExtractor( objectType ), this, isInternalFact ); this.declarations = new HashMap<String, Declaration>( 2 ); // default to avoid immediate resize this.declarations.put( this.declaration.getIdentifier(), this.declaration ); } else { this.declaration = null; } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { objectType = (ObjectType) in.readObject(); constraints = (List<Constraint>) in.readObject(); declaration = (Declaration) in.readObject(); declarations = (Map<String, Declaration>) in.readObject(); behaviors = (List<Behavior>) in.readObject(); index = in.readInt(); source = (PatternSource) in.readObject(); offset = in.readInt(); listenedProperties = (List<String>) in.readObject(); if ( source instanceof From ) { ((From)source).setResultPattern( this ); } } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( objectType ); out.writeObject( constraints ); out.writeObject( declaration ); out.writeObject( declarations ); out.writeObject( behaviors ); out.writeInt( index ); out.writeObject( source ); out.writeInt( offset ); out.writeObject(getListenedProperties()); } public void setClassObjectType(ClassObjectType objectType) { this.objectType = objectType; } public Declaration[] getRequiredDeclarations() { Set<Declaration> decl = new HashSet<Declaration>(); for( Constraint constr : this.constraints ) { for( Declaration d : constr.getRequiredDeclarations() ) { decl.add( d ); } } return decl.toArray( new Declaration[decl.size()] ); } - public Object clone() { + public Pattern clone() { final String identifier = (this.declaration != null) ? this.declaration.getIdentifier() : null; final Pattern clone = new Pattern( this.index, this.offset, this.objectType, identifier, this.declaration != null ? this.declaration.isInternalFact() : false ); clone.setListenedProperties( getListenedProperties() ); if ( this.getSource() != null ) { clone.setSource( (PatternSource) this.getSource().clone() ); if ( source instanceof From ) { ((From)clone.getSource()).setResultPattern( this ); } } if( this.declarations != null ) { for ( Declaration decl : this.declarations.values() ) { Declaration addedDeclaration = clone.addDeclaration( decl.getIdentifier() ); addedDeclaration.setReadAccessor( decl.getExtractor() ); addedDeclaration.setBindingName( decl.getBindingName() ); } } for ( Constraint constr : this.constraints ) { Constraint constraint = (Constraint) ((Constraint) constr).clone(); // we must update pattern references in cloned declarations Declaration[] oldDecl = ((Constraint) constr).getRequiredDeclarations(); Declaration[] newDecl = constraint.getRequiredDeclarations(); for ( int i = 0; i < newDecl.length; i++ ) { if ( newDecl[i].getPattern() == this ) { newDecl[i].setPattern( clone ); // we still need to call replace because there might be nested declarations to replace constraint.replaceDeclaration( oldDecl[i], newDecl[i] ); } } clone.addConstraint(constraint); } if ( behaviors != null ) { for ( Behavior behavior : this.behaviors ) { clone.addBehavior( behavior ); } } return clone; } public ObjectType getObjectType() { return this.objectType; } public void setObjectType(ObjectType objectType) { this.objectType = objectType; } public PatternSource getSource() { return source; } public void setSource(PatternSource source) { this.source = source; } public List<Constraint> getConstraints() { return Collections.unmodifiableList( this.constraints ); } public void addConstraint(Constraint constraint) { if ( this.constraints == Collections.EMPTY_LIST ) { this.constraints = new ArrayList( 1 ); } if ( constraint.getType().equals( Constraint.ConstraintType.UNKNOWN ) ) { this.setConstraintType( (MutableTypeConstraint) constraint ); } this.constraints.add( constraint ); } public void removeConstraint(Constraint constraint) { this.constraints.remove( constraint ); } public List<MvelConstraint> getCombinableConstraints() { List<MvelConstraint> combinableConstraints = new ArrayList<MvelConstraint>(); for (Constraint constraint : constraints) { if (constraint instanceof MvelConstraint && !((MvelConstraint)constraint).isUnification() && !((MvelConstraint)constraint).isIndexable() && constraint.getType() == ConstraintType.BETA) { // don't combine alpha nodes to allow nodes sharing combinableConstraints.add((MvelConstraint)constraint); } } return combinableConstraints; } public Declaration addDeclaration(final String identifier) { Declaration declaration = this.declarations != null ? (Declaration) this.declarations.get( identifier ) : null; if ( declaration == null ) { declaration = new Declaration( identifier, null, this, true ); addDeclaration(declaration); } return declaration; } public void addDeclaration(final Declaration decl) { if ( this.declarations == null ) { this.declarations = new HashMap<String, Declaration>( 2 ); // default to avoid immediate resize } this.declarations.put( decl.getIdentifier(), decl ); } public boolean isBound() { return (this.declaration != null); } public Declaration getDeclaration() { return this.declaration; } public int getIndex() { return this.index; } /** * The offset of the fact related to this pattern * inside the tuple * * @return the offset */ public int getOffset() { return this.offset; } public void setOffset(final int offset) { this.offset = offset; } public Map<String, Declaration> getInnerDeclarations() { return (this.declarations != null) ? this.declarations : Collections.EMPTY_MAP; } public Map<String, Declaration> getOuterDeclarations() { return (this.declarations != null) ? this.declarations : Collections.EMPTY_MAP; } public Declaration resolveDeclaration(final String identifier) { return (this.declarations != null) ? this.declarations.get( identifier ) : null; } public String toString() { return "Pattern type='" + ((this.objectType == null) ? "null" : this.objectType.toString()) + "', index='" + this.index + "', offset='" + this.getOffset() + "', identifer='" + ((this.declaration == null) ? "" : this.declaration.toString()) + "'"; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + this.constraints.hashCode(); result = PRIME * result + ((this.declaration == null) ? 0 : this.declaration.hashCode()); result = PRIME * result + this.index; result = PRIME * result + ((this.objectType == null) ? 0 : this.objectType.hashCode()); result = PRIME * result + ((this.behaviors == null) ? 0 : this.behaviors.hashCode()); result = PRIME * result + this.offset; result = PRIME * result + ((this.source == null) ? 0 : this.source.hashCode()); return result; } public boolean equals(final Object object) { if ( this == object ) { return true; } if ( object == null || getClass() != object.getClass() ) { return false; } final Pattern other = (Pattern) object; if ( !this.constraints.equals( other.constraints ) ) { return false; } if ( this.behaviors != other.behaviors || (this.behaviors != null && !this.behaviors.equals( other.behaviors )) ) { return false; } if ( this.declaration == null ) { if ( other.declaration != null ) { return false; } } else if ( !this.declaration.equals( other.declaration ) ) { return false; } if ( this.index != other.index ) { return false; } if ( !this.objectType.equals( other.objectType ) ) { return false; } if ( this.offset != other.offset ) { return false; } return (this.source == null) ? other.source == null : this.source.equals( other.source ); } public List getNestedElements() { return this.source != null ? Collections.singletonList( this.source ) : Collections.EMPTY_LIST; } public boolean isPatternScopeDelimiter() { return true; } /** * @param constraint */ private void setConstraintType(final MutableTypeConstraint constraint) { final Declaration[] declarations = constraint.getRequiredDeclarations(); boolean isAlphaConstraint = true; for ( int i = 0; isAlphaConstraint && i < declarations.length; i++ ) { if ( !declarations[i].isGlobal() && declarations[i].getPattern() != this ) { isAlphaConstraint = false; } } ConstraintType type = isAlphaConstraint ? ConstraintType.ALPHA : ConstraintType.BETA; constraint.setType( type ); } /** * @return the behaviors */ public List<Behavior> getBehaviors() { if ( this.behaviors == null ) { return Collections.emptyList(); } return this.behaviors; } /** * @param behaviors the behaviors to set */ public void setBehaviors(List<Behavior> behaviors) { this.behaviors = behaviors; } public void addBehavior(Behavior behavior) { if ( this.behaviors == null ) { this.behaviors = new ArrayList<Behavior>(); } this.behaviors.add( behavior ); } public List<String> getListenedProperties() { return listenedProperties; } public void setListenedProperties(List<String> listenedProperties) { this.listenedProperties = listenedProperties; } } diff --git a/drools-core/src/main/java/org/drools/rule/constraint/MvelConstraint.java b/drools-core/src/main/java/org/drools/rule/constraint/MvelConstraint.java index e5abc3d79f..951bfbcf2e 100644 --- a/drools-core/src/main/java/org/drools/rule/constraint/MvelConstraint.java +++ b/drools-core/src/main/java/org/drools/rule/constraint/MvelConstraint.java @@ -1,611 +1,612 @@ package org.drools.rule.constraint; import org.drools.base.DroolsQuery; import org.drools.base.extractors.ArrayElementReader; import org.drools.base.mvel.MVELCompilationUnit; import org.drools.common.AbstractRuleBase; import org.drools.common.InternalFactHandle; import org.drools.common.InternalWorkingMemory; import org.drools.concurrent.ExecutorProviderFactory; import org.drools.core.util.AbstractHashTable.FieldIndex; import org.drools.core.util.BitMaskUtil; import org.drools.reteoo.LeftTuple; import org.drools.rule.ContextEntry; import org.drools.rule.Declaration; import org.drools.rule.IndexEvaluator; import org.drools.rule.IndexableConstraint; import org.drools.rule.MVELDialectRuntimeData; import org.drools.rule.MutableTypeConstraint; import org.drools.runtime.rule.Variable; import org.drools.spi.FieldValue; import org.drools.spi.InternalReadAccessor; import org.drools.util.CompositeClassLoader; import org.mvel2.ParserConfiguration; import org.drools.rule.constraint.ConditionAnalyzer.*; import org.mvel2.ParserContext; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExecutableStatement; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import static org.drools.core.util.ClassUtils.*; import static org.drools.core.util.StringUtils.extractFirstIdentifier; import static org.drools.core.util.StringUtils.skipBlanks; public class MvelConstraint extends MutableTypeConstraint implements IndexableConstraint { private static final boolean TEST_JITTING = false; private static final int JIT_THRESOLD = 20; // Integer.MAX_VALUE; private transient AtomicInteger invocationCounter = new AtomicInteger(1); private transient boolean jitted = false; private String packageName; private String expression; private boolean isIndexable; private Declaration[] declarations; private Declaration indexingDeclaration; private InternalReadAccessor extractor; private boolean isUnification; private boolean isDynamic; private FieldValue fieldValue; private MVELCompilationUnit compilationUnit; private transient volatile ConditionEvaluator conditionEvaluator; private transient volatile Condition analyzedCondition; public MvelConstraint() {} public MvelConstraint(String packageName, String expression, MVELCompilationUnit compilationUnit, boolean isIndexable, FieldValue fieldValue, InternalReadAccessor extractor) { this.packageName = packageName; this.expression = expression; this.compilationUnit = compilationUnit; this.isIndexable = isIndexable; this.declarations = new Declaration[0]; this.fieldValue = fieldValue; this.extractor = extractor; } public MvelConstraint(String packageName, String expression, Declaration[] declarations, MVELCompilationUnit compilationUnit, boolean isDynamic) { this.packageName = packageName; this.expression = expression; this.declarations = declarations; this.compilationUnit = compilationUnit; this.isDynamic = isDynamic; } public MvelConstraint(String packageName, String expression, Declaration[] declarations, MVELCompilationUnit compilationUnit, boolean isIndexable, Declaration indexingDeclaration, InternalReadAccessor extractor, boolean isUnification) { this.packageName = packageName; this.expression = expression; this.compilationUnit = compilationUnit; this.isIndexable = isIndexable && indexingDeclaration != null; this.declarations = declarations == null ? new Declaration[0] : declarations; this.indexingDeclaration = indexingDeclaration; this.extractor = extractor; this.isUnification = isUnification; } public String getPackageName() { return packageName; } public String getExpression() { return expression; } public boolean isUnification() { return isUnification; } public void unsetUnification() { isUnification = false; } public boolean isIndexable() { return isIndexable; } public FieldValue getField() { return fieldValue; } public boolean isAllowed(InternalFactHandle handle, InternalWorkingMemory workingMemory, ContextEntry context) { if (isUnification) { throw new UnsupportedOperationException( "Should not be called" ); } return evaluate(handle.getObject(), workingMemory, null); } public boolean isAllowedCachedLeft(ContextEntry context, InternalFactHandle handle) { if (isUnification) { if (((UnificationContextEntry)context).getVariable() != null) { return true; } context = ((UnificationContextEntry)context).getContextEntry(); } MvelContextEntry mvelContextEntry = (MvelContextEntry)context; return evaluate(handle.getObject(), mvelContextEntry.workingMemory, mvelContextEntry.leftTuple); } public boolean isAllowedCachedRight(LeftTuple tuple, ContextEntry context) { if (isUnification) { DroolsQuery query = ( DroolsQuery ) tuple.get( 0 ).getObject(); Variable v = query.getVariables()[ ((UnificationContextEntry)context).getReader().getIndex() ]; if (v != null) { return true; } context = ((UnificationContextEntry)context).getContextEntry(); } MvelContextEntry mvelContextEntry = (MvelContextEntry)context; return evaluate(mvelContextEntry.right, mvelContextEntry.workingMemory, tuple); } private boolean evaluate(Object object, InternalWorkingMemory workingMemory, LeftTuple leftTuple) { if (!jitted) { if (conditionEvaluator == null) { createMvelConditionEvaluator(workingMemory); if (TEST_JITTING && !isDynamic) { // Only for test purposes boolean mvelValue = forceJitEvaluator(object, workingMemory, leftTuple); } } if (!isDynamic && invocationCounter.getAndIncrement() == JIT_THRESOLD) { jitEvaluator(object, workingMemory, leftTuple); } } return conditionEvaluator.evaluate(object, workingMemory, leftTuple); } private void createMvelConditionEvaluator(InternalWorkingMemory workingMemory) { if (compilationUnit != null) { MVELDialectRuntimeData data = getMVELDialectRuntimeData(workingMemory); ExecutableStatement statement = (ExecutableStatement)compilationUnit.getCompiledExpression(data); ParserContext context = statement instanceof CompiledExpression ? ((CompiledExpression)statement).getParserContext() : new ParserContext(data.getParserConfiguration()); conditionEvaluator = new MvelConditionEvaluator(compilationUnit, context, statement, declarations); } else { conditionEvaluator = new MvelConditionEvaluator(getParserConfiguration(workingMemory), expression, declarations); } } private boolean forceJitEvaluator(Object object, InternalWorkingMemory workingMemory, LeftTuple leftTuple) { boolean mvelValue; try { mvelValue = conditionEvaluator.evaluate(object, workingMemory, leftTuple); } catch (ClassCastException cce) { mvelValue = false; } jitEvaluator(object, workingMemory, leftTuple); return mvelValue; } private void jitEvaluator(final Object object, final InternalWorkingMemory workingMemory, final LeftTuple leftTuple) { jitted = true; try { if (TEST_JITTING) { executeJitting(object, workingMemory, leftTuple); } else { ExecutorHolder.executor.execute(new Runnable() { public void run() { executeJitting(object, workingMemory, leftTuple); } }); } } catch (Throwable t) { throw new RuntimeException("Exception jitting: " + expression, t); } } private static class ExecutorHolder { private static final Executor executor = ExecutorProviderFactory.getExecutorProvider().getExecutor(); } private void executeJitting(Object object, InternalWorkingMemory workingMemory, LeftTuple leftTuple) { CompositeClassLoader classLoader = ((AbstractRuleBase)workingMemory.getRuleBase()).getRootClassLoader(); if (analyzedCondition == null) { analyzedCondition = ((MvelConditionEvaluator) conditionEvaluator).getAnalyzedCondition(object, workingMemory, leftTuple); } conditionEvaluator = ASMConditionEvaluatorJitter.jitEvaluator(expression, analyzedCondition, declarations, classLoader, leftTuple); } public ContextEntry createContextEntry() { if (declarations.length == 0) return null; ContextEntry contextEntry = new MvelContextEntry(declarations); if (isUnification) { contextEntry = new UnificationContextEntry(contextEntry, declarations[0]); } return contextEntry; } public FieldIndex getFieldIndex() { // declaration's offset can be modified by the reteoo's PatternBuilder so modify the indexingDeclaration accordingly indexingDeclaration.getPattern().setOffset(declarations[0].getPattern().getOffset()); return new FieldIndex(extractor, indexingDeclaration, INDEX_EVALUATOR); } public InternalReadAccessor getFieldExtractor() { return extractor; } public Declaration[] getRequiredDeclarations() { return declarations; } public Declaration getIndexingDeclaration() { return indexingDeclaration; } public void replaceDeclaration(Declaration oldDecl, Declaration newDecl) { for (int i = 0; i < declarations.length; i++) { if (declarations[i].equals(oldDecl)) { if (compilationUnit != null) { compilationUnit.replaceDeclaration(declarations[i], newDecl); } declarations[i] = newDecl; break; } } if (indexingDeclaration != null && indexingDeclaration.equals(oldDecl)) { indexingDeclaration = newDecl; } } // Slot specific public long getListenedPropertyMask(List<String> settableProperties) { if (conditionEvaluator == null) { return calculateMaskFromExpression(settableProperties); } if (analyzedCondition == null) { analyzedCondition = ((MvelConditionEvaluator) conditionEvaluator).getAnalyzedCondition(); } return calculateMask(analyzedCondition, settableProperties); } private long calculateMaskFromExpression(List<String> settableProperties) { long mask = 0; String[] simpleExpressions = expression.split("\\Q&&\\E|\\Q||\\E"); for (String simpleExpression : simpleExpressions) { String propertyName = getPropertyNameFromSimpleExpression(simpleExpression); if (propertyName.length() == 0) { continue; } if (propertyName.equals("this")) { return Long.MAX_VALUE; } int pos = settableProperties.indexOf(propertyName); if (pos < 0 && Character.isUpperCase(propertyName.charAt(0))) { propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); pos = settableProperties.indexOf(propertyName); } if (pos >= 0) { // Ignore not settable properties mask = BitMaskUtil.set(mask, pos); } } return mask; } private String getPropertyNameFromSimpleExpression(String simpleExpression) { StringBuilder propertyNameBuilder = new StringBuilder(); int cursor = extractFirstIdentifier(simpleExpression, propertyNameBuilder, 0); String propertyName = propertyNameBuilder.toString(); if (propertyName.equals("this")) { cursor = skipBlanks(simpleExpression, cursor); if (simpleExpression.charAt(cursor) != '.') { return "this"; } propertyNameBuilder = new StringBuilder(); extractFirstIdentifier(simpleExpression, propertyNameBuilder, cursor); propertyName = propertyNameBuilder.toString(); } return propertyName; } private long calculateMask(Condition condition, List<String> settableProperties) { if (condition instanceof SingleCondition) { return calculateMask((SingleCondition) condition, settableProperties); } long mask = 0L; for (Condition c : ((CombinedCondition)condition).getConditions()) { mask |= calculateMask(c, settableProperties); } return mask; } private long calculateMask(SingleCondition condition, List<String> settableProperties) { String propertyName = getFirstInvokedPropertyName(condition.getLeft()); if (propertyName == null) { return Long.MAX_VALUE; } int pos = settableProperties.indexOf(propertyName); if (pos < 0) { throw new RuntimeException("Unknown property: " + propertyName); } return 1L << pos; } private String getFirstInvokedPropertyName(Expression expression) { if (!(expression instanceof EvaluatedExpression)) { return null; } List<Invocation> invocations = ((EvaluatedExpression)expression).invocations; Invocation invocation = invocations.get(0); if (invocation instanceof MethodInvocation) { Method method = ((MethodInvocation)invocation).getMethod(); if (method == null && invocations.size() > 1) { invocation = invocations.get(1); if (invocation instanceof MethodInvocation) { method = ((MethodInvocation)invocation).getMethod(); } else if (invocation instanceof FieldAccessInvocation) { return ((FieldAccessInvocation)invocation).getField().getName(); } } return getter2property(method.getName()); } if (invocation instanceof FieldAccessInvocation) { return ((FieldAccessInvocation)invocation).getField().getName(); } return null; } // Externalizable public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(packageName); out.writeObject(expression); out.writeObject(declarations); out.writeObject(indexingDeclaration); out.writeObject(extractor); out.writeBoolean(isIndexable); out.writeBoolean(isUnification); out.writeBoolean(isDynamic); out.writeObject(fieldValue); out.writeObject(compilationUnit); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); packageName = (String)in.readObject(); expression = (String)in.readObject(); declarations = (Declaration[]) in.readObject(); indexingDeclaration = (Declaration) in.readObject(); extractor = (InternalReadAccessor) in.readObject(); isIndexable = in.readBoolean(); isUnification = in.readBoolean(); isDynamic = in.readBoolean(); fieldValue = (FieldValue) in.readObject(); compilationUnit = (MVELCompilationUnit) in.readObject(); } public boolean isTemporal() { return false; } public Object clone() { MvelConstraint clone = new MvelConstraint(); clone.setType(getType()); clone.packageName = packageName; clone.expression = expression; clone.isIndexable = isIndexable; - clone.declarations = declarations; + clone.declarations = Arrays.copyOf(declarations, declarations.length); clone.indexingDeclaration = indexingDeclaration; clone.extractor = extractor; clone.isUnification = isUnification; clone.isDynamic = isDynamic; clone.conditionEvaluator = conditionEvaluator; - clone.compilationUnit = compilationUnit; + clone.compilationUnit = compilationUnit != null ? compilationUnit.clone() : null; return clone; } public int hashCode() { return expression.hashCode(); } public boolean equals(final Object object) { if ( this == object ) { return true; } if ( object == null || object.getClass() != MvelConstraint.class ) { return false; } MvelConstraint other = (MvelConstraint) object; if (!expression.equals(other.expression)) { return false; } if (declarations.length != other.declarations.length) { return false; } for (int i = 0; i < declarations.length; i++) { if ( !declarations[i].getExtractor().equals( other.declarations[i].getExtractor() ) ) { return false; } } return true; } @Override public String toString() { return expression; } private ParserConfiguration getParserConfiguration(InternalWorkingMemory workingMemory) { return getMVELDialectRuntimeData(workingMemory).getParserConfiguration(); } private MVELDialectRuntimeData getMVELDialectRuntimeData(InternalWorkingMemory workingMemory) { return ((MVELDialectRuntimeData)workingMemory.getRuleBase().getPackage(packageName).getDialectRuntimeRegistry().getDialectData( "mvel" )); } // MvelArrayContextEntry public static class MvelContextEntry implements ContextEntry { protected ContextEntry next; protected LeftTuple leftTuple; protected Object right; protected Declaration[] declarations; protected transient InternalWorkingMemory workingMemory; public MvelContextEntry() { } public MvelContextEntry(Declaration[] declarations) { this.declarations = declarations; } public ContextEntry getNext() { return this.next; } public void setNext(final ContextEntry entry) { this.next = entry; } public void updateFromTuple(InternalWorkingMemory workingMemory, LeftTuple leftTuple) { this.leftTuple = leftTuple; this.workingMemory = workingMemory; } public void updateFromFactHandle(InternalWorkingMemory workingMemory, InternalFactHandle handle) { this.workingMemory = workingMemory; right = handle.getObject(); } public void resetTuple() { leftTuple = null; } public void resetFactHandle() { workingMemory = null; right = null; } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(leftTuple); out.writeObject(right); out.writeObject(declarations); out.writeObject(next); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { leftTuple = (LeftTuple)in.readObject(); right = in.readObject(); declarations = (Declaration[])in.readObject(); next = (ContextEntry)in.readObject(); } } public static class UnificationContextEntry implements ContextEntry { private ContextEntry contextEntry; private Declaration declaration; private Variable variable; private ArrayElementReader reader; public UnificationContextEntry() { } public UnificationContextEntry(ContextEntry contextEntry, Declaration declaration) { this.contextEntry = contextEntry; this.declaration = declaration; reader = ( ArrayElementReader ) this.declaration.getExtractor(); } public ContextEntry getContextEntry() { return this.contextEntry; } public ArrayElementReader getReader() { return reader; } public ContextEntry getNext() { return this.contextEntry.getNext(); } public void resetFactHandle() { this.contextEntry.resetFactHandle(); } public void resetTuple() { this.contextEntry.resetTuple(); this.variable = null; } public void setNext(ContextEntry entry) { this.contextEntry.setNext( entry ); } public void updateFromFactHandle(InternalWorkingMemory workingMemory, InternalFactHandle handle) { this.contextEntry.updateFromFactHandle( workingMemory, handle ); } public void updateFromTuple(InternalWorkingMemory workingMemory, LeftTuple tuple) { DroolsQuery query = ( DroolsQuery ) tuple.get( 0 ).getObject(); Variable v = query.getVariables()[ this.reader.getIndex() ]; if ( v == null ) { // if there is no Variable, handle it as a normal constraint this.variable = null; this.contextEntry.updateFromTuple( workingMemory, tuple ); } else { this.variable = v; } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.contextEntry = (ContextEntry) in.readObject(); this.declaration = ( Declaration ) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( this.contextEntry ); out.writeObject( this.declaration ); } public Variable getVariable() { return this.variable; } } public static final IndexEvaluator INDEX_EVALUATOR = new PlainIndexEvaluator(); public static class PlainIndexEvaluator implements IndexEvaluator { public boolean evaluate(InternalWorkingMemory workingMemory, final InternalReadAccessor extractor1, final Object object1, final InternalReadAccessor extractor2, final Object object2) { final Object value1 = extractor1.getValue( workingMemory, object1 ); final Object value2 = extractor2.getValue( workingMemory, object2 ); if (value1 == null) { return value2 == null; } if (value1 instanceof String) { return value1.equals(value2.toString()); } return value1.equals( value2 ); } } }
false
false
null
null
diff --git a/src/name/davidfischer/civilopedia/helpers/CivilopediaHtmlHelper.java b/src/name/davidfischer/civilopedia/helpers/CivilopediaHtmlHelper.java index 4bb70ab..c1f6518 100644 --- a/src/name/davidfischer/civilopedia/helpers/CivilopediaHtmlHelper.java +++ b/src/name/davidfischer/civilopedia/helpers/CivilopediaHtmlHelper.java @@ -1,70 +1,71 @@ package name.davidfischer.civilopedia.helpers; import java.util.HashMap; import java.util.Iterator; import java.util.regex.Pattern; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; public final class CivilopediaHtmlHelper { private static final char DELIMETER = '$'; private static final String [][] REPLACEMENTS = new String [][] { new String [] {"[TAB]", ""}, new String [] {"[NEWLINE]", "<br />"}, new String [] {"[COLOR_POSITIVE_TEXT]", "<em class='COLOR_POSITIVE_TEXT'>"}, new String [] {"[COLOR_CYAN]", "<em class='COLOR_CYAN'>"}, new String [] {"[ENDCOLOR]", "</em>"}, }; private CivilopediaHtmlHelper() { // Intentionally left empty } /** * Render the passed HTML `template` with the `params`. * * @param template the HTML to escape with params * @param params key/value pairs to apply HTML escaping * @return the escaped HTML output */ public static String format(String template, HashMap<String, String> params) { String [] searchList = new String [params.size()]; String key, val; String [] replacementList = new String [params.size()]; if (null != params) { int index = 0; Iterator<String> iter = params.keySet().iterator(); while (iter.hasNext()) { key = iter.next(); val = CivilopediaHtmlHelper.civilopediaFormatter(StringEscapeUtils.escapeHtml4(params.get(key))); searchList[index] = DELIMETER + key + DELIMETER; replacementList[index] = val; index += 1; } } return StringUtils.replaceEach(template, searchList, replacementList); } /** * Should be run after HTML escaping. * @param html * @return a copy of `html` with Civilopedia specific replacements performed */ public static String civilopediaFormatter(String html) { // This method could be more performant by pre-allocating two // arrays since they never change, but then the code is harder // to maintain. String [] searchList = new String [REPLACEMENTS.length]; String [] replacementList = new String [REPLACEMENTS.length]; + String result = html; // Replace icons - html = html.replaceAll(Pattern.quote("[") + "(ICON_[A-Z0-9_]+)" + Pattern.quote("]"), "<span class='icon $1'></span>"); + result = result.replaceAll(Pattern.quote("[") + "(ICON_[A-Z0-9_]+)" + Pattern.quote("]"), "<span class='icon $1'></span>"); for (int i = 0; i < CivilopediaHtmlHelper.REPLACEMENTS.length; i += 1) { searchList[i] = CivilopediaHtmlHelper.REPLACEMENTS[i][0]; replacementList[i] = CivilopediaHtmlHelper.REPLACEMENTS[i][1]; } - return StringUtils.replaceEach(html, searchList, replacementList); + return StringUtils.replaceEach(result, searchList, replacementList); } }
false
false
null
null
diff --git a/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java b/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java index 9d4986506..c05d5f9ff 100644 --- a/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java +++ b/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java @@ -1,1141 +1,1143 @@ /* * Copyright 2010 Ning, Inc. * * Ning 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 com.ning.http.client.providers.netty; import com.ning.http.client.AsyncHandler; import com.ning.http.client.AsyncHandler.STATE; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.AsyncHttpProvider; import com.ning.http.client.AsyncHttpProviderConfig; import com.ning.http.client.ByteArrayPart; import com.ning.http.client.ConnectionsPool; import com.ning.http.client.Cookie; import com.ning.http.client.FilePart; import com.ning.http.client.FluentCaseInsensitiveStringsMap; import com.ning.http.client.FluentStringsMap; import com.ning.http.client.HttpResponseBodyPart; import com.ning.http.client.HttpResponseHeaders; import com.ning.http.client.HttpResponseStatus; import com.ning.http.client.MaxRedirectException; import com.ning.http.client.Part; import com.ning.http.client.PerRequestConfig; import com.ning.http.client.ProgressAsyncHandler; import com.ning.http.client.ProxyServer; import com.ning.http.client.Realm; import com.ning.http.client.Request; import com.ning.http.client.RequestBuilder; import com.ning.http.client.Response; import com.ning.http.client.StringPart; import com.ning.http.client.logging.LogManager; import com.ning.http.client.logging.Logger; import com.ning.http.multipart.ByteArrayPartSource; import com.ning.http.multipart.MultipartRequestEntity; import com.ning.http.multipart.PartSource; import com.ning.http.util.AuthenticatorUtils; import com.ning.http.util.SslUtils; import com.ning.http.util.UTF8UrlEncoder; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferOutputStream; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureProgressListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.DefaultFileRegion; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.FileRegion; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.CookieEncoder; import org.jboss.netty.handler.codec.http.DefaultCookie; import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer; import org.jboss.netty.handler.codec.http.DefaultHttpRequest; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpChunkTrailer; import org.jboss.netty.handler.codec.http.HttpClientCodec; import org.jboss.netty.handler.codec.http.HttpContentDecompressor; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpVersion; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.handler.stream.ChunkedFile; import org.jboss.netty.handler.stream.ChunkedWriteHandler; import org.jboss.netty.handler.timeout.IdleState; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.HashedWheelTimer; import javax.net.ssl.SSLEngine; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.URI; import java.nio.channels.ClosedChannelException; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import static org.jboss.netty.channel.Channels.pipeline; public class NettyAsyncHttpProvider extends IdleStateHandler implements AsyncHttpProvider<HttpResponse> { private final static String HTTP_HANDLER = "httpHandler"; private final static String SSL_HANDLER = "sslHandler"; private final static Logger log = LogManager.getLogger(NettyAsyncHttpProvider.class); private final ClientBootstrap plainBootstrap; private final ClientBootstrap secureBootstrap; private final static int MAX_BUFFERED_BYTES = 8192; private final AsyncHttpClientConfig config; private final AtomicBoolean isClose = new AtomicBoolean(false); private final NioClientSocketChannelFactory socketChannelFactory; private final ChannelGroup openChannels = new DefaultChannelGroup("asyncHttpClient"); private final ConnectionsPool<String, Channel> connectionsPool; public NettyAsyncHttpProvider(AsyncHttpClientConfig config) { super(new HashedWheelTimer(), 0, 0, config.getIdleConnectionTimeoutInMs(), TimeUnit.MILLISECONDS); socketChannelFactory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), config.executorService()); plainBootstrap = new ClientBootstrap(socketChannelFactory); secureBootstrap = new ClientBootstrap(socketChannelFactory); this.config = config; // This is dangerous as we can't catch a wrong typed ConnectionsPool ConnectionsPool<String, Channel> cp = (ConnectionsPool<String, Channel>) config.getConnectionPool(); if (cp == null) { cp = new NettyConnectionsPool(config); } this.connectionsPool = cp; AsyncHttpProviderConfig<?, ?> providerConfig = config.getAsyncHttpProviderConfig(); if (providerConfig != null && NettyAsyncHttpProviderConfig.class.isAssignableFrom(providerConfig.getClass())) { configureNetty(NettyAsyncHttpProviderConfig.class.cast(providerConfig)); } } void configureNetty(NettyAsyncHttpProviderConfig providerConfig) { for (Entry<String, Object> entry : providerConfig.propertiesSet()) { plainBootstrap.setOption(entry.getKey(), entry.getValue()); secureBootstrap.setOption(entry.getKey(), entry.getValue()); } } void configure(final ConnectListener<?> cl) { plainBootstrap.setPipelineFactory(new ChannelPipelineFactory() { /* @Override */ public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast(HTTP_HANDLER, new HttpClientCodec()); if (config.isCompressionEnabled()) { pipeline.addLast("inflater", new HttpContentDecompressor()); } pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this); return pipeline; } }); secureBootstrap.setPipelineFactory(new ChannelPipelineFactory() { /* @Override */ public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); try { pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine())); } catch (Throwable ex) { cl.future().abort(ex); } pipeline.addLast(HTTP_HANDLER, new HttpClientCodec()); if (config.isCompressionEnabled()) { pipeline.addLast("inflater", new HttpContentDecompressor()); } pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this); return pipeline; } }); } private Channel lookupInCache(URI uri) { Channel channel = connectionsPool.removeConnection(getBaseUrl(uri)); if (channel != null) { if (log.isDebugEnabled()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Using cached Channel %s", uri, channel)); } /** * The Channel will eventually be closed by Netty and will becomes invalid. * We might suffer a memory leak if we don't scan for closed channel. The * AsyncHttpClientConfig.reaper() will always make sure those are cleared. */ if (channel.isOpen()) { channel.setReadable(true); } else { return null; } try { // Always make sure the channel who got cached support the proper protocol. It could // only occurs when a HttpMethod.CONNECT is used agains a proxy that require upgrading from http to // https. return verifyChannelPipeline(channel, uri.getScheme()); } catch (Exception ex) { if (log.isDebugEnabled()) { log.warn(ex); } } } return null; } private SSLEngine createSSLEngine() throws IOException, GeneralSecurityException { SSLEngine sslEngine = config.getSSLEngineFactory().newSSLEngine(); if (sslEngine == null) { sslEngine = SslUtils.getSSLEngine(); } return sslEngine; } private Channel verifyChannelPipeline(Channel channel, String scheme) throws IOException, GeneralSecurityException { if (channel.getPipeline().get(SSL_HANDLER) != null && "http".equalsIgnoreCase(scheme)) { channel.getPipeline().remove(SSL_HANDLER); } else if (channel.getPipeline().get(HTTP_HANDLER) != null && "http".equalsIgnoreCase(scheme)) { return channel; } else if (channel.getPipeline().get(SSL_HANDLER) == null && "https".equalsIgnoreCase(scheme)) { channel.getPipeline().addFirst(SSL_HANDLER, new SslHandler(createSSLEngine())); } return channel; } protected final <T> void executeRequest(final Channel channel, final AsyncHttpClientConfig config, final NettyResponseFuture<T> future, final HttpRequest nettyRequest) throws ConnectException { if (!channel.isConnected()) { String url = channel.getRemoteAddress() != null ? channel.getRemoteAddress().toString() : null; if (url == null) { try { url = future.getURI().toString(); } catch (MalformedURLException e) { // ignored } } throw new ConnectException(String.format("[" + Thread.currentThread().getName() + "] Connection refused to %s", url)); } channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(future); channel.write(nettyRequest).addListener(new ProgressListener(true, future.getAsyncHandler())); if (future.getRequest().getFile() != null) { final File file = future.getRequest().getFile(); RandomAccessFile raf; long fileLength = 0; try { raf = new RandomAccessFile(file, "r"); fileLength = raf.length(); ChannelFuture writeFuture; if (channel.getPipeline().get(SslHandler.class) != null) { writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192)); writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler())); } else { final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = channel.write(region); writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler()) { public void operationComplete(ChannelFuture cf) { region.releaseExternalResources(); super.operationComplete(cf); } }); } } catch (IOException ex) { throw new IllegalStateException(ex); } } try { future.touch(); int delay = requestTimeout(config, future.getRequest().getPerRequestConfig()); if (delay != -1) { future.setReaperFuture(config.reaper().scheduleAtFixedRate(new Runnable() { public void run() { if (future.hasExpired()) { if (log.isDebugEnabled()) { log.debug("Request Timeout expired for " + future); } future.abort(new TimeoutException("Request timed out.")); markChannelNotReadable(channel.getPipeline().getContext(NettyAsyncHttpProvider.class)); } } }, 0, delay, TimeUnit.MILLISECONDS)); } } catch (RejectedExecutionException ex) { future.abort(ex); } } protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri, boolean allowConnect) throws IOException { String method = request.getReqType(); if (allowConnect && ((request.getProxyServer() != null || config.getProxyServer() != null) && "https".equalsIgnoreCase(uri.getScheme()))) { method = HttpMethod.CONNECT.toString(); } return construct(config, request, new HttpMethod(method), uri); } protected final static URI createUri(String u) { URI uri = URI.create(u); final String scheme = uri.getScheme().toLowerCase(); if (scheme == null || !scheme.equals("http") && !scheme.equals("https")) { throw new IllegalArgumentException("The URI scheme, of the URI " + u + ", must be equal (ignoring case) to 'http'"); } String path = uri.getPath(); if (path == null) { throw new IllegalArgumentException("The URI path, of the URI " + uri + ", must be non-null"); } else if (path.length() > 0 && path.charAt(0) != '/') { throw new IllegalArgumentException("The URI path, of the URI " + uri + ". must start with a '/'"); } else if (path.length() == 0) { return URI.create(u + "/"); } return uri; } @SuppressWarnings("deprecation") private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri) throws IOException { String host = uri.getHost(); if (request.getVirtualHost() != null) { host = request.getVirtualHost(); } HttpRequest nettyRequest; if (m.equals(HttpMethod.CONNECT)) { uri = URI.create(new StringBuilder(uri.getHost()) .append(":") .append(getPort(uri)).toString()); nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, uri.toString()); } else if (config.getProxyServer() != null || request.getProxyServer() != null) { nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, uri.toString()); } else { StringBuilder path = new StringBuilder(uri.getRawPath()); if (uri.getQuery() != null) { path.append("?").append(uri.getRawQuery()); } nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString()); } if (uri.getPort() == -1) { nettyRequest.setHeader(HttpHeaders.Names.HOST, host); } else { nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort()); } if (!m.equals(HttpMethod.CONNECT)) { FluentCaseInsensitiveStringsMap h = request.getHeaders(); if (h != null) { for (String name : h.keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : h.get(name)) { nettyRequest.addHeader(name, value); } } } } if (config.isCompressionEnabled()) { nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } } Realm realm = request.getRealm(); if (realm != null && realm.getUsePreemptiveAuth()) { switch (realm.getAuthScheme()) { case BASIC: nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm)); break; case DIGEST: if (realm.getNonce() != null && !realm.getNonce().equals("")) { try { nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm)); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } } break; default: throw new IllegalStateException(String.format("[" + Thread.currentThread().getName() + "] Invalid Authentication %s", realm.toString())); } } String ka = config.getKeepAlive() ? "keep-alive" : "close"; nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, ka); ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer(); if (proxyServer != null) { nettyRequest.setHeader("Proxy-Connection", ka); if (proxyServer.getPrincipal() != null) { nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer)); } } // Add default accept headers. if (request.getHeaders().getFirstValue("Accept") == null) { nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*"); } if (config.getUserAgent() != null) { nettyRequest.setHeader("User-Agent", config.getUserAgent()); } if (request.getCookies() != null && !request.getCookies().isEmpty()) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } String reqType = request.getReqType(); if ("POST".equals(reqType) || "PUT".equals(reqType)) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0"); if (request.getByteData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().length())); nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8")); } else if (request.getStreamData() != null) { int[] lengthWrapper = new int[1]; byte[] bytes = readFully(request.getStreamData(), lengthWrapper); int length = lengthWrapper[0]; nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length)); nettyRequest.setContent(ChannelBuffers.copiedBuffer(bytes, 0, length)); } else if (request.getParams() != null) { StringBuilder sb = new StringBuilder(); for (final Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes("UTF-8"))); if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } MultipartRequestEntity mre = createMultipartRequestEntity(request.getParts(), request.getParams()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght); mre.writeRequest(new ChannelBufferOutputStream(b)); nettyRequest.setContent(b); } else if (request.getEntityWriter() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght); request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b)); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex()); nettyRequest.setContent(b); } else if (request.getFile() != null) { File file = request.getFile(); if (file.isHidden() || !file.exists() || !file.isFile()) { throw new IOException(String.format("[" + Thread.currentThread().getName() + "] File %s is not a file, is hidden or doesn't exist", file.getAbsolutePath())); } nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, new RandomAccessFile(file, "r").length()); } } return nettyRequest; } public void close() { isClose.set(true); connectionsPool.destroy(); openChannels.close(); this.releaseExternalResources(); config.reaper().shutdown(); config.executorService().shutdown(); socketChannelFactory.releaseExternalResources(); plainBootstrap.releaseExternalResources(); secureBootstrap.releaseExternalResources(); } /* @Override */ public Response prepareResponse(final HttpResponseStatus status, final HttpResponseHeaders headers, final Collection<HttpResponseBodyPart> bodyParts) { return new NettyAsyncResponse(status, headers, bodyParts); } /* @Override */ public <T> Future<T> execute(final Request request, final AsyncHandler<T> asyncHandler) throws IOException { return doConnect(request, asyncHandler, null); } private <T> void execute(final Request request, final NettyResponseFuture<T> f) throws IOException { doConnect(request, f.getAsyncHandler(), f); } private <T> Future<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f) throws IOException { if (isClose.get()) { throw new IOException("Closed"); } URI uri = createUri(request.getUrl()); Channel channel = lookupInCache(uri); if (channel != null && channel.isOpen()) { if (channel.isConnected()) { HttpRequest nettyRequest = buildRequest(config, request, uri, false); if (f == null) { f = new NettyResponseFuture<T>(uri, request, asyncHandler, nettyRequest, requestTimeout(config, request.getPerRequestConfig()), this); } else { f.setNettyRequest(nettyRequest); } f.setState(NettyResponseFuture.STATE.POOLED); try { executeRequest(channel, config, f, nettyRequest); return f; } catch (ConnectException ex) { // The connection failed because the channel got remotly closed // Let continue the normal processing. connectionsPool.removeAllConnections(channel); } } else { connectionsPool.removeAllConnections(channel); } } if (!connectionsPool.canCacheConnection()) { throw new IOException("Too many connections"); } ConnectListener<T> c = new ConnectListener.Builder<T>(config, request, asyncHandler, f, this).build(); ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer() ; boolean useSSl = uri.getScheme().compareToIgnoreCase("https") == 0 && (proxyServer == null || !proxyServer.getProtocolAsString().equals("https")); configure(c); ChannelFuture channelFuture; ClientBootstrap bootstrap = useSSl ? secureBootstrap : plainBootstrap; try { if (proxyServer == null) { channelFuture = bootstrap.connect(new InetSocketAddress(uri.getHost(), getPort(uri))); } else { channelFuture = bootstrap.connect(new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort())); } bootstrap.setOption("connectTimeout", config.getConnectionTimeoutInMs()); } catch (Throwable t) { log.error(t); c.future().abort(t.getCause()); return c.future(); } channelFuture.addListener(c); openChannels.add(channelFuture.getChannel()); return c.future(); } protected static int requestTimeout(AsyncHttpClientConfig config, PerRequestConfig perRequestConfig) { int result; if (perRequestConfig != null) { int prRequestTimeout = perRequestConfig.getRequestTimeoutInMs(); result = (prRequestTimeout != 0 ? prRequestTimeout : config.getRequestTimeoutInMs()); } else { result = config.getRequestTimeoutInMs(); } return result; } @Override protected void channelIdle(ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception { NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment(); connectionsPool.removeAllConnections(ctx.getChannel()); future.abort(new IOException("No response received. Connection timed out after " + config.getIdleConnectionTimeoutInMs())); closeChannel(ctx); } private void closeChannel(ChannelHandlerContext ctx) { ctx.setAttachment(new DiscardEvent()); ctx.getChannel().close(); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { // Discard in memory bytes if the HttpContent.interrupt() has been invoked. if (ctx.getAttachment() instanceof DiscardEvent) { ctx.getChannel().setReadable(false); return; } else if (!(ctx.getAttachment() instanceof NettyResponseFuture<?>)) { // The IdleStateHandler times out and he is calling us. // We already closed the channel in IdleStateHandler#channelIdle // so we have nothing to do return; } final NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment(); future.touch(); HttpRequest nettyRequest = future.getNettyRequest(); AsyncHandler<?> handler = future.getAsyncHandler(); try { if (e.getMessage() instanceof HttpResponse) { HttpResponse response = (HttpResponse) e.getMessage(); // Required if there is some trailing headers. future.setHttpResponse(response); int statusCode = response.getStatus().getCode(); String ka = response.getHeader(HttpHeaders.Names.CONNECTION); future.setKeepAlive(ka == null || ka.toLowerCase().equals("keep-alive")); String wwwAuth = response.getHeader(HttpHeaders.Names.WWW_AUTHENTICATE); Request request = future.getRequest(); if (statusCode == 401 && wwwAuth != null && future.getRequest().getRealm() != null && !future.getAndSetAuth(true)) { Realm realm = new Realm.RealmBuilder().clone(request.getRealm()) .parseWWWAuthenticateHeader(wwwAuth) .setUri(URI.create(request.getUrl()).getPath()) .setMethodName(request.getReqType()) .setScheme(request.getRealm().getAuthScheme()) .setUsePreemptiveAuth(true) .build(); if (log.isDebugEnabled()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Sending authentication to %s", request.getUrl())); } //Cache our current connection so we don't have to re-open it. markAsDoneAndCacheConnection(future, ctx, false); RequestBuilder builder = new RequestBuilder(future.getRequest()); execute(builder.setRealm(realm).build(), future); return; } String proxyAuth = response.getHeader(HttpHeaders.Names.PROXY_AUTHENTICATE); if (statusCode == 407 && proxyAuth != null && future.getRequest().getRealm() != null && !future.getAndSetAuth(true)) { if (log.isDebugEnabled()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Sending proxy authentication to %s", request.getUrl())); } //Cache our current connection so we don't have to re-open it. markAsDoneAndCacheConnection(future, ctx, false); execute(future.getRequest(), future); return; } if (future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT) && statusCode == 200) { if (log.isDebugEnabled()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Connected to %s", request.getUrl())); } //Cache our current connection so we don't have to re-open it. markAsDoneAndCacheConnection(future, ctx, false); RequestBuilder builder = new RequestBuilder(future.getRequest()); try { upgradeProtocol(ctx.getChannel().getPipeline(), (request.getUrl())); } catch (Throwable ex) { future.abort(ex); } execute(builder.build(), future); return; } boolean redirectEnabled = (request.isRedirectEnabled() || config.isRedirectEnabled()); if (redirectEnabled && (statusCode == 302 || statusCode == 301)) { if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) { String location = response.getHeader(HttpHeaders.Names.LOCATION); if (location.startsWith("/")) { location = getBaseUrl(future.getURI()) + location; } if (!location.equals(future.getURI().toString())) { URI uri = createUri(location); if (location.startsWith("https")) { upgradeProtocol(ctx.getChannel().getPipeline(), "https"); } RequestBuilder builder = new RequestBuilder(future.getRequest()); future.setURI(uri); markChannelNotReadable(ctx); String newUrl = uri.toString(); if (log.isDebugEnabled()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Redirecting to %s", newUrl)); } execute(builder.setUrl(newUrl).build(), future); return; } } else { throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects()); } } if (log.isDebugEnabled()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Status: %s", response.getStatus())); log.debug(String.format("[" + Thread.currentThread().getName() + "] Version: %s", response.getProtocolVersion())); log.debug("\""); if (!response.getHeaderNames().isEmpty()) { for (String name : response.getHeaderNames()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Header: %s = %s", name, response.getHeaders(name))); } log.debug("\""); } } if (!future.getAndSetStatusReceived(true) && updateStatusAndInterrupt(handler, new ResponseStatus(future.getURI(), response, this))) { finishUpdate(future, ctx); return; } else if (updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(), response, this))) { finishUpdate(future, ctx); return; } else if (!response.isChunked()) { if (response.getContent().readableBytes() != 0) { updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), response, this)); } finishUpdate(future, ctx); return; } if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) { markAsDoneAndCacheConnection(future, ctx, true); } } else if (e.getMessage() instanceof HttpChunk) { HttpChunk chunk = (HttpChunk) e.getMessage(); if (handler != null) { if (chunk.isLast() || updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), null, this, chunk))) { if (chunk instanceof DefaultHttpChunkTrailer) { updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(), future.getHttpResponse(), this, (HttpChunkTrailer) chunk)); } finishUpdate(future, ctx); } } } } catch (Exception t) { try { future.abort(t); } finally { finishUpdate(future, ctx); throw t; } } } private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException { if (p.get(HTTP_HANDLER) != null) { p.remove(HTTP_HANDLER); } if (scheme.startsWith("https")) { if (p.get(SSL_HANDLER) == null) { p.addFirst(HTTP_HANDLER, new HttpClientCodec()); p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine())); } else { p.addAfter(SSL_HANDLER, HTTP_HANDLER, new HttpClientCodec()); } } else { p.addFirst(HTTP_HANDLER, new HttpClientCodec()); } } public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (log.isDebugEnabled()) { log.debug(String.format("[" + Thread.currentThread().getName() + "] Channel state: %s", e.getState())); } connectionsPool.removeAllConnections(ctx.getChannel()); if (!isClose.get() && ctx.getAttachment() instanceof NettyResponseFuture<?>) { NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment(); // Cleaning a broken connection. if (Boolean.class.isAssignableFrom(e.getValue().getClass()) && !Boolean.class.cast(e.getValue())) { if (remotelyClosed(ctx.getChannel(), future)) { return; } } if (future != null && !future.isDone() && !future.isCancelled()) { try { future.getAsyncHandler().onThrowable(new IOException("No response received. Connection timed out")); } catch (Throwable t) { log.error(t); } } } - ctx.sendUpstream(e); + super.channelClosed(ctx,e); } private static boolean remotelyClosed(Channel channel, NettyResponseFuture<?> future) { if (future == null || future.getState() == NettyResponseFuture.STATE.POOLED) { if (NettyResponseFuture.class.isAssignableFrom( channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment().getClass())) { NettyResponseFuture<?> f = (NettyResponseFuture<?>) channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment(); f.setState(NettyResponseFuture.STATE.RECONNECTED); try { f.provider().execute(f.getRequest(),f); return true; } catch (IOException iox) { f.setState(NettyResponseFuture.STATE.CLOSED); f.abort(iox); log.error(iox); } } } if (future.getState() != NettyResponseFuture.STATE.NEW) { return true; } return false; } private void markAsDoneAndCacheConnection(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx, boolean releaseFuture) throws MalformedURLException { if (future.getKeepAlive()) { connectionsPool.addConnection(getBaseUrl(future.getURI()), ctx.getChannel()); } if (releaseFuture) { future.done(); - } else if (!future.getKeepAlive()) { - closeChannel(ctx); + + if (!future.getKeepAlive()) { + closeChannel(ctx); + } } } private String getBaseUrl(URI uri) { String url = uri.getScheme() + "://" + uri.getAuthority(); int port = uri.getPort(); if (port == -1) { port = getPort(uri); url += ":" + port; } return url; } private static int getPort(URI uri) { int port = uri.getPort(); if (port == -1) port = uri.getScheme().equals("http") ? 80 : 443; return port; } private void finishUpdate(NettyResponseFuture<?> future, ChannelHandlerContext ctx) throws IOException { markChannelNotReadable(ctx); markAsDoneAndCacheConnection(future, ctx, true); } private static void markChannelNotReadable(ChannelHandlerContext ctx) { // Catch any unexpected exception when marking the channel. ctx.setAttachment(new DiscardEvent()); try { ctx.getChannel().setReadable(false); } catch (Exception ex) { log.debug(ex); } } @SuppressWarnings("unchecked") private final boolean updateStatusAndInterrupt(AsyncHandler handler, HttpResponseStatus c) throws Exception { return handler.onStatusReceived(c) != STATE.CONTINUE; } @SuppressWarnings("unchecked") private final boolean updateHeadersAndInterrupt(AsyncHandler handler, HttpResponseHeaders c) throws Exception { return handler.onHeadersReceived(c) != STATE.CONTINUE; } @SuppressWarnings("unchecked") private final boolean updateBodyAndInterrupt(AsyncHandler handler, HttpResponseBodyPart c) throws Exception { return handler.onBodyPartReceived(c) != STATE.CONTINUE; } //Simple marker for stopping publishing bytes. private final static class DiscardEvent { } //Simple marker for closed events private final static class ClosedEvent { } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel channel = e.getChannel(); Throwable cause = e.getCause(); if (log.isDebugEnabled()) { log.debug("Fatal I/O exception: ", cause); } if (ctx.getAttachment() instanceof NettyResponseFuture<?>) { NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment(); if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) { // We will recover from a badly cached connection. return; } // Windows only. if (cause != null && cause.getMessage() != null && cause.getMessage().equals("An established connection was aborted by the software in your host machine")) { if (log.isDebugEnabled()) { log.debug(cause); } remotelyClosed(channel, null); return; } if (future != null) { try { future.abort(cause); } catch (Throwable t) { log.error(t); } } } } private final static int computeAndSetContentLength(Request request, HttpRequest r) { int lenght = (int) request.getLength(); if (lenght == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) { lenght = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH)); } if (lenght != -1) { r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(lenght)); } return lenght; } /** * This is quite ugly as our internal names are duplicated, but we build on top of HTTP Client implementation. * * @param params * @param methodParams * @return * @throws java.io.FileNotFoundException */ private final static MultipartRequestEntity createMultipartRequestEntity(List<Part> params, FluentStringsMap methodParams) throws FileNotFoundException { com.ning.http.multipart.Part[] parts = new com.ning.http.multipart.Part[params.size()]; int i = 0; for (Part part : params) { if (part instanceof StringPart) { parts[i] = new com.ning.http.multipart.StringPart(part.getName(), ((StringPart) part).getValue(), "UTF-8"); } else if (part instanceof FilePart) { parts[i] = new com.ning.http.multipart.FilePart(part.getName(), ((FilePart) part).getFile(), ((FilePart) part).getMimeType(), ((FilePart) part).getCharSet()); } else if (part instanceof ByteArrayPart) { PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(), ((ByteArrayPart) part).getData()); parts[i] = new com.ning.http.multipart.FilePart(part.getName(), source, ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet()); } else if (part == null) { throw new NullPointerException("Part cannot be null"); } else { throw new IllegalArgumentException(String.format("[" + Thread.currentThread().getName() + "] Unsupported part type for multipart parameter %s", part.getName())); } ++i; } return new MultipartRequestEntity(parts, methodParams); } // TODO: optimize; better use segmented-buffer to avoid reallocs (expand-by-doubling) private static byte[] readFully(InputStream in, int[] lengthWrapper) throws IOException { // just in case available() returns bogus (or -1), allocate non-trivial chunk byte[] b = new byte[Math.max(512, in.available())]; int offset = 0; while (true) { int left = b.length - offset; int count = in.read(b, offset, left); if (count < 0) { // EOF break; } offset += count; if (count == left) { // full buffer, need to expand b = doubleUp(b); } } // wish Java had Tuple return type... lengthWrapper[0] = offset; return b; } private static byte[] doubleUp(byte[] b) { // TODO: in Java 1.6, we would use Arrays.copyOf(), but for now we only rely on 1.5: int len = b.length; byte[] b2 = new byte[len + len]; System.arraycopy(b, 0, b2, 0, len); return b2; } private static class ProgressListener implements ChannelFutureProgressListener { private final boolean notifyHeaders; private final AsyncHandler asyncHandler; public ProgressListener(boolean notifyHeaders, AsyncHandler asyncHandler) { this.notifyHeaders = notifyHeaders; this.asyncHandler = asyncHandler; } public void operationComplete(ChannelFuture cf) { // The write operation failed. If the channel was cached, it means it got asynchronously closed. // Let's retry a second time. Throwable cause = cf.getCause(); if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) { if (log.isDebugEnabled()) { log.debug(cf.getCause()); } remotelyClosed(cf.getChannel(), null); return; } if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) { if (notifyHeaders) { ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted(); } else { ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted(); } } } public void operationProgressed(ChannelFuture cf, long amount, long current, long total) { if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) { ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteProgess(amount, current, total); } } } }
false
false
null
null
diff --git a/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java b/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java index cdbc17d..50092d4 100644 --- a/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java +++ b/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java @@ -1,195 +1,195 @@ /* * Copyright (C) 2003-2007 Kepler Project. * * 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 org.keplerproject.ldt.core.luadoc; import java.util.HashMap; import java.util.Map; import org.keplerproject.ldt.core.ILuaEntry; import org.keplerproject.ldt.core.lua.modules.LuaModuleLoader; import org.keplerproject.luajava.JavaFunction; import org.keplerproject.luajava.LuaException; import org.keplerproject.luajava.LuaObject; import org.keplerproject.luajava.LuaState; import org.keplerproject.luajava.LuaStateFactory; import org.keplerproject.luajava.luafilesystem.JLuaFileSystem; /** * Runs a luadoc engine to generate entries. * * @author jasonsantos * @version $Id$ */ public class LuadocGenerator { private static LuadocGenerator singleton; protected Map<String, ILuaEntry> luaEntryIndex; public LuadocGenerator() { super(); luaEntryIndex = new HashMap<String, ILuaEntry>(); } public static LuadocGenerator getInstance() { if (singleton == null) singleton = new LuadocGenerator(); return singleton; } // register the java functions to create the entries public Map<String, ILuaEntry> generate(String fileName) { final Map<String, ILuaEntry> m = new HashMap<String, ILuaEntry>(); try { LuaState L = LuaStateFactory.newLuaState(); L.openLibs(); JLuaFileSystem.register(L); LuaModuleLoader.register(L); L.pushJavaFunction(new JavaFunction(L) { @Override public int execute() throws LuaException { // String t = getParam(1).toString(); LuaObject fileOrModuleName = getParam(2); LuaObject entryName = getParam(3); LuaObject entryType = getParam(4); LuaObject entrySummary = getParam(5); LuaObject entryDescription = getParam(6); LuaObject entryComment = getParam(7); LuaObject entryCode = getParam(8); LuadocEntry e = new LuadocEntry(); e.setModule(fileOrModuleName.toString()); e.setEntryType(entryType.toString()); e.setName(entryName.toString()); e.setSummary(entrySummary.toString()); e.setDescription(entryDescription.toString()); e.setComment(entryComment.toString()); e.setCode(entryCode.toString()); m.put(entryName.toString(), e); return 0; } }); L.setGlobal("addDocumentationEntry"); int result = L.LdoString("require 'lfs' " + "\n" + "require 'luadoc' " + "\n" + "local files = {'" + fileName + "'}" + "\n" - + "require 'luadoc.config'" - + "local options = luadoc.config\n" + + "local options = require 'luadoc.config'" + + "\n" + "module ('loopback.doclet', package.seeall)" + "\n" + "t = {}" + "\n" + "function start(doc)" + "\n" + "local fileOrModuleName = ''" + "\n" + "r = function(d)" + "\n" + "for k, v in pairs(d) do" + "\n" + "if type(v)=='table' then" + "\n" + "if v.class=='function' then" + "\n" + "addDocumentationEntry(" + "fileOrModuleName, " + "v.name, " + "v.class, " + "v.summary," + "v.description," + "table.concat(v.comment, '\\n')," + "table.concat(v.code, '\\n')" + ")" + "\n" + "elseif v.type == 'file' or v.type == 'module' then" + "\n" + "fileOrModuleName = v.name" + "\n" + "end" + "\n" + "r(v)" + "\n" + "end" + "\n" + "end" + "\n" + "end" + "\n" + "r(doc)" + "end" + "\n" + "options.doclet = 'loopback.doclet'" + "\n" + "luadoc.main(files, options)"); if (result != 0) { String s = L.toString(-1); System.out.println(s); } L.close(); return m; } catch (LuaException e) { } // collect the documentation blocks, indexed by name // load the documentation blocks into the resulting map return null; } public Map<String, ILuaEntry> getLuaEntryIndex() { return luaEntryIndex; } public String getDocumentationText(String token) { LuadocEntry l = (LuadocEntry) getLuaEntryIndex().get(token); String doc = null; if (l != null) { // TODO: enhance the summary with HTML formatting doc = l.getComment(); // TODO: enhance the non-summary value with module information if (doc == null || doc.length() == 0) doc = l.getCode(); if (doc == null || doc.length() == 0) doc = l.getName(); } return doc; } }
true
true
public Map<String, ILuaEntry> generate(String fileName) { final Map<String, ILuaEntry> m = new HashMap<String, ILuaEntry>(); try { LuaState L = LuaStateFactory.newLuaState(); L.openLibs(); JLuaFileSystem.register(L); LuaModuleLoader.register(L); L.pushJavaFunction(new JavaFunction(L) { @Override public int execute() throws LuaException { // String t = getParam(1).toString(); LuaObject fileOrModuleName = getParam(2); LuaObject entryName = getParam(3); LuaObject entryType = getParam(4); LuaObject entrySummary = getParam(5); LuaObject entryDescription = getParam(6); LuaObject entryComment = getParam(7); LuaObject entryCode = getParam(8); LuadocEntry e = new LuadocEntry(); e.setModule(fileOrModuleName.toString()); e.setEntryType(entryType.toString()); e.setName(entryName.toString()); e.setSummary(entrySummary.toString()); e.setDescription(entryDescription.toString()); e.setComment(entryComment.toString()); e.setCode(entryCode.toString()); m.put(entryName.toString(), e); return 0; } }); L.setGlobal("addDocumentationEntry"); int result = L.LdoString("require 'lfs' " + "\n" + "require 'luadoc' " + "\n" + "local files = {'" + fileName + "'}" + "\n" + "require 'luadoc.config'" + "local options = luadoc.config\n" + "module ('loopback.doclet', package.seeall)" + "\n" + "t = {}" + "\n" + "function start(doc)" + "\n" + "local fileOrModuleName = ''" + "\n" + "r = function(d)" + "\n" + "for k, v in pairs(d) do" + "\n" + "if type(v)=='table' then" + "\n" + "if v.class=='function' then" + "\n" + "addDocumentationEntry(" + "fileOrModuleName, " + "v.name, " + "v.class, " + "v.summary," + "v.description," + "table.concat(v.comment, '\\n')," + "table.concat(v.code, '\\n')" + ")" + "\n" + "elseif v.type == 'file' or v.type == 'module' then" + "\n" + "fileOrModuleName = v.name" + "\n" + "end" + "\n" + "r(v)" + "\n" + "end" + "\n" + "end" + "\n" + "end" + "\n" + "r(doc)" + "end" + "\n" + "options.doclet = 'loopback.doclet'" + "\n" + "luadoc.main(files, options)"); if (result != 0) { String s = L.toString(-1); System.out.println(s); } L.close(); return m; } catch (LuaException e) { } // collect the documentation blocks, indexed by name // load the documentation blocks into the resulting map return null; }
public Map<String, ILuaEntry> generate(String fileName) { final Map<String, ILuaEntry> m = new HashMap<String, ILuaEntry>(); try { LuaState L = LuaStateFactory.newLuaState(); L.openLibs(); JLuaFileSystem.register(L); LuaModuleLoader.register(L); L.pushJavaFunction(new JavaFunction(L) { @Override public int execute() throws LuaException { // String t = getParam(1).toString(); LuaObject fileOrModuleName = getParam(2); LuaObject entryName = getParam(3); LuaObject entryType = getParam(4); LuaObject entrySummary = getParam(5); LuaObject entryDescription = getParam(6); LuaObject entryComment = getParam(7); LuaObject entryCode = getParam(8); LuadocEntry e = new LuadocEntry(); e.setModule(fileOrModuleName.toString()); e.setEntryType(entryType.toString()); e.setName(entryName.toString()); e.setSummary(entrySummary.toString()); e.setDescription(entryDescription.toString()); e.setComment(entryComment.toString()); e.setCode(entryCode.toString()); m.put(entryName.toString(), e); return 0; } }); L.setGlobal("addDocumentationEntry"); int result = L.LdoString("require 'lfs' " + "\n" + "require 'luadoc' " + "\n" + "local files = {'" + fileName + "'}" + "\n" + "local options = require 'luadoc.config'" + "\n" + "module ('loopback.doclet', package.seeall)" + "\n" + "t = {}" + "\n" + "function start(doc)" + "\n" + "local fileOrModuleName = ''" + "\n" + "r = function(d)" + "\n" + "for k, v in pairs(d) do" + "\n" + "if type(v)=='table' then" + "\n" + "if v.class=='function' then" + "\n" + "addDocumentationEntry(" + "fileOrModuleName, " + "v.name, " + "v.class, " + "v.summary," + "v.description," + "table.concat(v.comment, '\\n')," + "table.concat(v.code, '\\n')" + ")" + "\n" + "elseif v.type == 'file' or v.type == 'module' then" + "\n" + "fileOrModuleName = v.name" + "\n" + "end" + "\n" + "r(v)" + "\n" + "end" + "\n" + "end" + "\n" + "end" + "\n" + "r(doc)" + "end" + "\n" + "options.doclet = 'loopback.doclet'" + "\n" + "luadoc.main(files, options)"); if (result != 0) { String s = L.toString(-1); System.out.println(s); } L.close(); return m; } catch (LuaException e) { } // collect the documentation blocks, indexed by name // load the documentation blocks into the resulting map return null; }
diff --git a/core/src/main/java/com/github/jamescarter/hexahop/core/json/StateJson.java b/core/src/main/java/com/github/jamescarter/hexahop/core/json/StateJson.java index bd2632b..5853fee 100644 --- a/core/src/main/java/com/github/jamescarter/hexahop/core/json/StateJson.java +++ b/core/src/main/java/com/github/jamescarter/hexahop/core/json/StateJson.java @@ -1,128 +1,128 @@ package com.github.jamescarter.hexahop.core.json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.github.jamescarter.hexahop.core.level.Location; import com.github.jamescarter.hexahop.core.level.Tile; import com.github.jamescarter.hexahop.core.player.Direction; import playn.core.Json.Array; import playn.core.Json.Object; import playn.core.Json.Writer; import playn.core.PlayN; public class StateJson<T> { public static final String STORAGE_KEY_MAP = "mapProgress"; private HashMap<Integer, List<T>> baseGridMap = new HashMap<Integer, List<T>>(); private HashMap<Integer, List<Tile>> gridStatusMap = new HashMap<Integer, List<Tile>>(); private boolean hasStatus = false; private int par; private Location start; public StateJson(Class<T> type, Object baseJsonObj, String storageStatusKey) { String statusJsonString = PlayN.storage().getItem(storageStatusKey); if (statusJsonString == null) { statusJsonString = "{}"; } else { hasStatus = true; } Object statusJsonObj = PlayN.json().parse(statusJsonString); Array baseStartArray = baseJsonObj.getArray("start"); Array baseGridArray = baseJsonObj.getArray("grid"); Array statusGridArray = statusJsonObj.getArray("grid"); par = baseJsonObj.getInt("par"); start = new Location(baseStartArray.getInt(0), baseStartArray.getInt(1)); for (int row=0; row<baseGridArray.length(); row++) { Array baseValueArray = baseGridArray.getArray(row); Array statusValueArray = null; if (statusGridArray != null) { statusValueArray = statusGridArray.getArray(row); } List<T> baseValueList = new ArrayList<T>(); List<Tile> statusValueList = new ArrayList<Tile>(); for (int i=0; i<baseValueArray.length(); i++) { Integer baseValue = baseValueArray.getInt(i); if (baseValue == 0) { baseValueList.add(null); } else { if (type == Tile.class) { - baseValueList.add(type.cast(Tile.getTile(baseValue))); + baseValueList.add((T) Tile.getTile(baseValue)); } else { - baseValueList.add((T) type.cast(baseValue)); + baseValueList.add((T) baseValue); } } if (statusValueArray == null) { statusValueList.add(null); } else { statusValueList.add(Tile.getTile(statusValueArray.getInt(i))); } } baseGridMap.put(row, baseValueList); gridStatusMap.put(row, statusValueList); } } public HashMap<Integer, List<T>> getBaseGridMap() { return baseGridMap; } public HashMap<Integer, List<Tile>> getGridStatusMap() { return gridStatusMap; } public int par() { return par; } public Location start() { return start; } public boolean hasStatus() { return hasStatus; } public List<Direction> getMoveList() { // TODO: return new ArrayList<Direction>(); } public static void store(HashMap<Integer, List<Tile>> gridStatusMap, String storageStatusKey) { Writer writer = PlayN.json().newWriter(); Writer gridWriter = writer.object().array("grid"); for (int row=0; row<gridStatusMap.size(); row++) { List<Tile> rowTiles = gridStatusMap.get(row); Writer rowWriter = gridWriter.array(); for (Tile tile : rowTiles) { if (tile == null) { rowWriter.value(0); } else { rowWriter.value(tile.id()); } } rowWriter.end(); } gridWriter.end(); writer.end(); PlayN.storage().setItem(storageStatusKey, writer.write()); } } diff --git a/core/src/main/java/com/github/jamescarter/hexahop/core/level/Level.java b/core/src/main/java/com/github/jamescarter/hexahop/core/level/Level.java index d55a792..979367b 100644 --- a/core/src/main/java/com/github/jamescarter/hexahop/core/level/Level.java +++ b/core/src/main/java/com/github/jamescarter/hexahop/core/level/Level.java @@ -1,194 +1,194 @@ package com.github.jamescarter.hexahop.core.level; import static playn.core.PlayN.assets; import static playn.core.PlayN.graphics; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.github.jamescarter.hexahop.core.grid.GridLoader; import com.github.jamescarter.hexahop.core.grid.LevelTileGrid; import com.github.jamescarter.hexahop.core.grid.TileGrid; import com.github.jamescarter.hexahop.core.json.StateJson; import com.github.jamescarter.hexahop.core.player.Direction; import com.github.jamescarter.hexahop.core.player.Player; import com.github.jamescarter.hexahop.core.screen.MapScreen; import playn.core.Keyboard.Event; import playn.core.ImageLayer; import playn.core.Keyboard; import playn.core.Layer; import playn.core.PlayN; import playn.core.Pointer; public class Level extends GridLoader { private static final ImageLayer bgLayer = graphics().createImageLayer(assets().getImage("images/gradient.png")); private Location location; private List<Direction> moveList = new ArrayList<Direction>(); private LevelTileGrid levelTileGrid; private int par; private Player player; public Level(Location location, String levelJsonString) { this.location = location; StateJson<Tile> levelJson = new StateJson<Tile>( Tile.class, PlayN.json().parse(levelJsonString), - null + "level-" + location.col() + "x" + location.row() ); par = levelJson.par(); player = new Player(levelJson.start()); HashMap<Integer, List<Tile>> gridStatusMap; if (levelJson.hasStatus()) { moveList = levelJson.getMoveList(); gridStatusMap = levelJson.getGridStatusMap(); } else { // if no status was found, set the same as the level gridStatusMap = levelJson.getBaseGridMap(); } levelTileGrid = new LevelTileGrid(levelJson.getBaseGridMap(), gridStatusMap); } public int par() { return par; } @Override public void load() { super.load(); getGridLayer().add(player); // Center grid layer getGridLayer().setTranslation( ((640 - (getTileGrid().cols() * 46)) / 2) - 10, ((480 - (getTileGrid().rows() * 36)) / 2) - 36 ); PlayN.pointer().setListener(new Pointer.Adapter() { @Override public void onPointerStart(Pointer.Event event) { // Offset clicked location based on where the levelLayer is centered Direction direction = player.getDirection( event.x() - getGridLayer().tx(), event.y() - getGridLayer().ty() ); move(direction); } }); PlayN.keyboard().setListener(new Keyboard.Adapter() { @Override public void onKeyDown(Event event) { switch(event.key()) { case U: case Z: undo(); break; case UP: case W: move(Direction.NORTH); break; case DOWN: case S: move(Direction.SOUTH); break; case Q: move(Direction.NORTH_WEST); break; case E: move(Direction.NORTH_EAST); break; case A: move(Direction.SOUTH_WEST); break; case D: move(Direction.SOUTH_EAST); break; default: } } }); } private void move(Direction direction) { if (levelTileGrid.canMove(player.location(), direction)) { moveList.add(direction); deactivateTile(player.location()); player.move(direction, false); // TODO: levelTileGrid.activateTile(player.location()); if (levelTileGrid.complete()) { new MapScreen(location).load(); } } } /** * Undo the last move. * @return true if there are more moves to undo, otherwise false. */ private boolean undo() { if (moveList.isEmpty()) { return false; } Direction direction = moveList.remove(moveList.size() - 1); player.move(direction, true); restoreTile(player.location()); return true; } private void deactivateTile(Location location) { if (levelTileGrid.deactivateTile(player.location())) { getLayer(location).setVisible(false); } } private void restoreTile(Location location) { getLayer(location).setVisible(true); levelTileGrid.restoreTile(player.location()); } private Layer getLayer(Location location) { int colPosition = getColPosition(location.col(), 0); int rowPosition = getRowPosition(location.row(), location.col(), 0); for (int i=0; i<getGridLayer().size(); i++) { Layer layer = getGridLayer().get(i); if (layer instanceof ImageLayer) { if (layer.tx() == colPosition && layer.ty() == rowPosition) { return layer; } } } return null; } @Override public TileGrid<Tile> getTileGrid() { return levelTileGrid; } @Override public Layer getBackgroundLayer() { return bgLayer; } } \ No newline at end of file diff --git a/core/src/main/java/com/github/jamescarter/hexahop/core/screen/MapScreen.java b/core/src/main/java/com/github/jamescarter/hexahop/core/screen/MapScreen.java index ca5b34d..4fba533 100644 --- a/core/src/main/java/com/github/jamescarter/hexahop/core/screen/MapScreen.java +++ b/core/src/main/java/com/github/jamescarter/hexahop/core/screen/MapScreen.java @@ -1,129 +1,141 @@ package com.github.jamescarter.hexahop.core.screen; import static playn.core.PlayN.assets; import static playn.core.PlayN.graphics; import java.util.HashMap; import java.util.List; import playn.core.Color; import playn.core.ImageLayer; import playn.core.Layer; import playn.core.PlayN; import playn.core.Pointer; import playn.core.Surface; import playn.core.SurfaceLayer; import com.github.jamescarter.hexahop.core.callback.LevelLoadCallback; import com.github.jamescarter.hexahop.core.grid.GridLoader; import com.github.jamescarter.hexahop.core.grid.MapTileGrid; import com.github.jamescarter.hexahop.core.grid.TileGrid; import com.github.jamescarter.hexahop.core.json.StateJson; import com.github.jamescarter.hexahop.core.level.Location; import com.github.jamescarter.hexahop.core.level.Tile; public class MapScreen extends GridLoader { private static final ImageLayer bgLayer = graphics().createImageLayer(assets().getImage("images/map_top.png")); private MapTileGrid mapTileGrid; public MapScreen() { this(null); } public MapScreen(Location completedLevelLocation) { String mapJsonString; try { mapJsonString = assets().getTextSync("levels/map.json"); } catch (Exception e) { e.printStackTrace(); return; } StateJson<Integer> mapJson = new StateJson<Integer>( Integer.class, PlayN.json().parse( mapJsonString ), StateJson.STORAGE_KEY_MAP ); HashMap<Integer, List<Tile>> gridStatusMap = mapJson.getGridStatusMap(); if (!mapJson.hasStatus()) { Location start = mapJson.start(); gridStatusMap.get(start.row()).set(start.col(), Tile.INCOMPLETE); } mapTileGrid = new MapTileGrid(mapJson.getBaseGridMap(), gridStatusMap); if (completedLevelLocation != null) { mapTileGrid.unlockConnected(completedLevelLocation); StateJson.store(gridStatusMap, StateJson.STORAGE_KEY_MAP); } } @Override public void load() { SurfaceLayer lineLayer = graphics().createSurfaceLayer(1000, 480); Surface surface = lineLayer.surface(); surface.setFillColor(Color.rgb(39, 23, 107)); boolean addLineLayer = false; // draw lines between connections for (int row=0; row<getTileGrid().rows(); row++) { List<Tile> tileList = getTileGrid().rowTileList(row); for (int col=0; col<tileList.size(); col++) { if (tileList.get(col) != null) { for (Location toLocation : mapTileGrid.connectedTo(new Location(col, row))) { addLineLayer = true; surface.drawLine( getColPosition(col, 32), getRowPosition(row, col, 38), getColPosition(toLocation.col(), 32), getRowPosition(toLocation.row(), toLocation.col(), 38), 2 ); } } } } if (addLineLayer) { add(lineLayer); } super.load(); PlayN.pointer().setListener(new Pointer.Adapter() { @Override public void onPointerStart(Pointer.Event event) { int x = (int) ((event.x() - getGridLayer().tx()) / 64); int y = (int) ((event.y() - getGridLayer().ty()) / 64); Location location = new Location(x, y); // Make sure the level is activated before allowing the user to load it if (mapTileGrid.statusAt(new Location(x, y)) != null) { - Integer levelId = mapTileGrid.baseTileAt(location); - - assets().getText(String.format("levels/%03d.json", levelId), new LevelLoadCallback(location)); + assets().getText("levels/" + getLevelName(mapTileGrid.baseTileAt(location)) + ".json", new LevelLoadCallback(location)); } } }); } + private String getLevelName(int levelId) { + StringBuilder sb = new StringBuilder(); + + if (levelId < 10) { + sb.append("00"); + } else if (levelId < 100) { + sb.append("0"); + } + + sb.append(levelId); + + return sb.toString(); + } + @Override public TileGrid<Integer> getTileGrid() { return mapTileGrid; } @Override public Layer getBackgroundLayer() { return bgLayer; } }
false
false
null
null
diff --git a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/adapters/XSDTypeDefinitionAdapter.java b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/adapters/XSDTypeDefinitionAdapter.java index 4ca019ea9..88ef71bed 100644 --- a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/adapters/XSDTypeDefinitionAdapter.java +++ b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/adapters/XSDTypeDefinitionAdapter.java @@ -1,66 +1,67 @@ /******************************************************************************* * Copyright (c) 2001, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.xsd.ui.internal.adapters; import org.eclipse.emf.ecore.EObject; import org.eclipse.gef.commands.Command; +import org.eclipse.wst.xsd.ui.internal.adt.design.editparts.model.IActionProvider; import org.eclipse.wst.xsd.ui.internal.adt.facade.IType; import org.eclipse.xsd.XSDNamedComponent; import org.eclipse.xsd.XSDSchema; import org.eclipse.xsd.XSDTypeDefinition; -public abstract class XSDTypeDefinitionAdapter extends XSDBaseAdapter implements IType +public abstract class XSDTypeDefinitionAdapter extends XSDBaseAdapter implements IType, IActionProvider { public XSDTypeDefinition getXSDTypeDefinition() { return (XSDTypeDefinition)target; } public String getName() { if (getXSDTypeDefinition().eContainer() instanceof XSDSchema) { return getXSDTypeDefinition().getName(); } else { EObject o = getXSDTypeDefinition().eContainer(); if (o instanceof XSDNamedComponent) { XSDNamedComponent ed = (XSDNamedComponent)o; return "(" + ed.getName() + "Type)"; //$NON-NLS-1$ //$NON-NLS-2$ } } return null; } public String getQualifier() { return getXSDTypeDefinition().getTargetNamespace(); } public IType getSuperType() { XSDTypeDefinition td = getXSDTypeDefinition().getBaseType(); return td != null ? (IType)XSDAdapterFactory.getInstance().adapt(td) : null; } public Command getUpdateNameCommand(String newName) { // TODO Auto-generated method stub return null; } public boolean isComplexType() { return false; } }
false
false
null
null
diff --git a/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/OrderEvents.java b/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/OrderEvents.java index c2742386e..435ac443c 100644 --- a/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/OrderEvents.java +++ b/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/OrderEvents.java @@ -1,1770 +1,1770 @@ /* * Copyright (c) 2006 - 2009 Open Source Strategies, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Honest Public License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Honest Public License for more details. * * You should have received a copy of the Honest Public License * along with this program; if not, write to Funambol, * 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA */ /******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ /* This file has been modified by Open Source Strategies, Inc. */ package org.opentaps.common.order; import java.math.BigDecimal; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javolution.util.FastList; import javolution.util.FastMap; import net.sf.jasperreports.engine.data.JRMapCollectionDataSource; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilFormatOut; import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.order.order.OrderReadHelper; import org.ofbiz.order.shoppingcart.CartItemModifyException; import org.ofbiz.order.shoppingcart.ItemNotFoundException; import org.ofbiz.order.shoppingcart.ShoppingCart; import org.ofbiz.order.shoppingcart.ShoppingCartEvents; import org.ofbiz.order.shoppingcart.ShoppingCartItem; import org.ofbiz.order.shoppingcart.shipping.ShippingEvents; import org.ofbiz.party.party.PartyHelper; import org.ofbiz.product.config.ProductConfigWrapper; import org.ofbiz.product.store.ProductStoreSurveyWrapper; import org.ofbiz.product.store.ProductStoreWorker; import org.ofbiz.security.Security; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceUtil; import org.opentaps.common.order.shoppingcart.OpentapsShippingEstimateWrapper; import org.opentaps.common.order.shoppingcart.OpentapsShoppingCart; import org.opentaps.common.order.shoppingcart.OpentapsShoppingCartHelper; import org.opentaps.common.party.PartyContactHelper; import org.opentaps.common.party.PartyNotFoundException; import org.opentaps.common.party.PartyReader; import org.opentaps.common.util.UtilAccountingTags; import org.opentaps.common.util.UtilCommon; import org.opentaps.common.util.UtilConfig; import org.opentaps.common.util.UtilDate; import org.opentaps.common.util.UtilMessage; import org.opentaps.domain.DomainsDirectory; import org.opentaps.domain.DomainsLoader; import org.opentaps.domain.base.entities.ContactMech; import org.opentaps.domain.base.entities.OrderContactMech; import org.opentaps.domain.base.entities.OrderHeaderNoteView; import org.opentaps.domain.base.entities.OrderTerm; import org.opentaps.domain.base.entities.PostalAddress; import org.opentaps.domain.base.entities.SupplierProduct; import org.opentaps.domain.billing.payment.Payment; import org.opentaps.domain.order.Order; import org.opentaps.domain.order.OrderAdjustment; import org.opentaps.domain.order.OrderItemShipGroup; import org.opentaps.domain.order.OrderRepositoryInterface; import org.opentaps.domain.organization.AccountingTagConfigurationForOrganizationAndUsage; import org.opentaps.domain.party.PartyRepositoryInterface; import org.opentaps.domain.purchasing.PurchasingRepositoryInterface; import org.opentaps.foundation.entity.EntityNotFoundException; import org.opentaps.foundation.infrastructure.Infrastructure; import org.opentaps.foundation.infrastructure.InfrastructureException; import org.opentaps.foundation.infrastructure.User; import org.opentaps.foundation.repository.RepositoryException; /** * Common order events such as destroying the cart, etc. * */ public final class OrderEvents { private OrderEvents() { } private static final String MODULE = OrderEvents.class.getName(); private static final String PURCHASING_LABEL = "PurchasingUiLabels"; /** * Custom cart destroy method to avoid null pointer exception with ShoppingCartEvent.destroyCart(). * The reson is because ShoppingCartEvent.destroyCart() uses clearCart(), which * is bad logic: The clearCart() method calls getCartObject(), which will create a cart if * none is found, thus leading to a situation where an empty cart is created and then destroyed * when there is no cart to begin with. Normally this would be fine except that creating a cart * requires that productStoreId be in the session. If it isn't, then a null pointer exception occurs. * It's probably a good idea to fix the cart system to handle this issue. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @param applicationName a <code>String</code> value * @return a <code>String</code> value */ public static String destroyCart(HttpServletRequest request, HttpServletResponse response, String applicationName) { HttpSession session = request.getSession(true); // set the product store in session to avoid null pointer crash String productStoreId = (String) session.getAttribute("productStoreId"); if (productStoreId == null) { productStoreId = UtilConfig.getPropertyValue(applicationName, applicationName + ".order.productStoreId"); if (productStoreId != null) { session.setAttribute("productStoreId", productStoreId); } else { Debug.logWarning("No productStoreId found in " + applicationName + ".properties -- this could cause problems", MODULE); return "success"; } } // erase the tracking code session.removeAttribute("trackingCodeId"); // call the legacy method return ShoppingCartEvents.destroyCart(request, response); } /** * Custom add order item method. This is a simplification of ShoppingCartEvents.addToCart() which validates * fields specific to the order form presented in crmsfa. It also detects whether a configurable or virtual * product with variants is submitted, then redirects user to a page where the configuration and variants * can be selected. If the entered product does not match anything, this will redirect to a lookup page. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value */ @SuppressWarnings("unchecked") public static String addOrderItem(HttpServletRequest request, HttpServletResponse response) { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); HttpSession session = request.getSession(true); TimeZone timeZone = UtilCommon.getTimeZone(request); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); OpentapsShoppingCart cart = getCart(request); if (cart == null) { Debug.logWarning("Cart is not defined, unable to add order items.", MODULE); UtilMessage.addInternalError(request); return "error"; } Locale locale = cart.getLocale(); String productId = UtilCommon.getParameter(request, "productId"); if (productId == null) { productId = UtilCommon.getParameter(request, "add_product_id"); // some legacy forms use this if (productId == null) { UtilMessage.addRequiredFieldError(request, "productId"); return "error"; } } // find Product match using comprehensive search GenericValue product = null; try { Map results = dispatcher.runSync("getProductByComprehensiveSearch", UtilMisc.toMap("productId", productId)); if (ServiceUtil.isError(results) || ServiceUtil.isFailure(results)) { return UtilMessage.createAndLogEventError(request, results, locale, MODULE); } product = (GenericValue) results.get("product"); productId = (String) results.get("productId"); } catch (GenericServiceException e) { return UtilMessage.createAndLogEventError(request, e, locale, MODULE); } // still no product, send to lookup request if (product == null) { return "findMatchingProducts"; } // if the product is configurable or virtual, send user to appropriate page if ("AGGREGATED".equals(product.get("productTypeId"))) { return "configureProduct"; } else if ("Y".equals(product.get("isVirtual"))) { return "chooseVariantProduct"; } // validate quantity double quantity = 0; String quantityString = UtilCommon.getParameter(request, "quantity"); if (quantityString == null) { UtilMessage.addRequiredFieldError(request, "quantity"); return "error"; } try { quantity = Double.parseDouble(quantityString); } catch (NumberFormatException e) { UtilMessage.addFieldError(request, "quantity", "OpentapsFieldError_BadDoubleFormat"); return "error"; } // validate the desired delivery date Timestamp shipBeforeDate = null; String shipBeforeDateString = UtilCommon.getParameter(request, "shipBeforeDate"); if (shipBeforeDateString != null) { try { shipBeforeDate = UtilDateTime.getDayEnd(UtilDateTime.stringToTimeStamp(shipBeforeDateString, UtilDate.getDateFormat(locale), timeZone, locale), timeZone, locale); } catch (ParseException e) { UtilMessage.addFieldError(request, "shipBeforeDate", UtilMessage.expandLabel("OpentapsFieldError_BadDateFormat", locale, UtilMisc.toMap("format", UtilDate.getDateFormat(locale)))); return "error"; } } // build the attributes map Map attributes = FastMap.newInstance(); // validate the accounting tags Map tags = new HashMap<String, String>(); UtilAccountingTags.addTagParameters(request, tags); try { DomainsLoader domainLoader = new DomainsLoader(new Infrastructure(dispatcher), new User(userLogin)); DomainsDirectory dd = domainLoader.loadDomainsDirectory(); OrderRepositoryInterface orderRepository = dd.getOrderDomain().getOrderRepository(); List<AccountingTagConfigurationForOrganizationAndUsage> missings = orderRepository.validateTagParameters(cart, tags, UtilAccountingTags.TAG_PARAM_PREFIX, productId); if (!missings.isEmpty()) { for (AccountingTagConfigurationForOrganizationAndUsage missingTag : missings) { UtilMessage.addError(request, "OpentapsError_ServiceErrorRequiredTagNotFound", UtilMisc.toMap("tagName", missingTag.getDescription())); UtilMessage.addRequiredFieldError(request, missingTag.getPrefixedName(UtilAccountingTags.TAG_PARAM_PREFIX)); } return "error"; } // get the validated accounting tags and set them as cart item attributes UtilAccountingTags.addTagParameters(tags, attributes); } catch (GeneralException e) { Debug.logError(e, MODULE); return "error"; } String comments = request.getParameter("comments"); attributes.put("itemComment", comments); String isPromo = UtilCommon.getParameter(request, "isPromo"); boolean isPromoItem = "Y".equals(isPromo); if (isPromoItem) { attributes.put("customPromo", "Y"); } // handle surveys List<GenericValue> surveys = ProductStoreWorker.getProductSurveys(cart.getDelegator(), cart.getProductStoreId(), productId, "CART_ADD"); if (surveys != null && surveys.size() > 0) { // check if a survey was submitted String surveyResponseId = (String) request.getAttribute("surveyResponseId"); if (UtilValidate.isNotEmpty(surveyResponseId)) { // if it is then we pass it to the addOrIncreaseItem method as an attribute attributes.put("surveyResponses", UtilMisc.toList(surveyResponseId)); } else { // set up a surveyAction and surveyWrapper, then redirect to survey ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(surveys.get(0), cart.getOrderPartyId(), UtilHttp.getParameterMap(request)); request.setAttribute("surveyWrapper", wrapper); request.setAttribute("surveyAction", "addOrderItemSurvey"); return "survey"; } } // determine order item type based on ProductOrderItemType String itemType = null; try { itemType = UtilOrder.getOrderItemTypeId(product.getString("productTypeId"), cart.getOrderType(), cart.getDelegator()); } catch (GenericEntityException e) { return UtilMessage.createAndLogEventError(request, e, locale, MODULE); } // add the item to the cart using the simplest method try { addItemToOrder(cart, productId, null, quantity, null, null, null, shipBeforeDate, null, null, attributes, null, null, itemType, null, null, request); } catch (GeneralException e) { Debug.logError(e, "Failed to add product [" + productId + "] to cart: " + e.getMessage(), MODULE); UtilMessage.addError(request, "OpentapsError_CannotAddItem", UtilMisc.toMap("message", e.getMessage())); return "error"; } return "success"; } /** Add an item to the order of shopping cart, or if already there, increase the quantity. * @param cart a <code>ShoppingCart</code> value * @param productId a <code>String</code> value * @param selectedAmountDbl a <code>Double</code> value * @param quantity a <code>double</code> value * @param reservStart a <code>Timestamp</code> value * @param reservLengthDbl a <code>Double</code> value * @param reservPersonsDbl a <code>Double</code> value * @param shipBeforeDate a <code>Timestamp</code> value * @param shipAfterDate a <code>Timestamp</code> value * @param features a <code>Map</code> value * @param attributes a <code>Map</code> value * @param prodCatalogId a <code>String</code> value * @param configWrapper a <code>ProductConfigWrapper</code> value * @param itemType a <code>String</code> value * @param itemGroupNumber a <code>String</code> value * @param parentProductId a <code>String</code> value * @param request a <code>HttpServletRequest</code> value * @return the index of the item in the cart * @throws CartItemModifyException if an exception occur * @throws ItemNotFoundException if an exception occur * @throws RepositoryException if an exception occur * @throws InfrastructureException if an exception occur * @throws GenericServiceException if an exception occur * @throws GenericEntityException if an exception occur */ @SuppressWarnings("unchecked") public static int addItemToOrder(ShoppingCart cart, String productId, Double selectedAmountDbl, double quantity, Timestamp reservStart, Double reservLengthDbl, Double reservPersonsDbl, Timestamp shipBeforeDate, Timestamp shipAfterDate, Map features, Map attributes, String prodCatalogId, ProductConfigWrapper configWrapper, String itemType, String itemGroupNumber, String parentProductId, HttpServletRequest request) throws CartItemModifyException, ItemNotFoundException, RepositoryException, InfrastructureException, GenericServiceException, GenericEntityException { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); Locale locale = UtilHttp.getLocale(request); if (cart.getOrderType().equals("PURCHASE_ORDER")) { // check if exist the SupplierProudct, if not then add new SupplierProduct DomainsLoader domainLoader = new DomainsLoader(request); PurchasingRepositoryInterface purchasingRepository = domainLoader.loadDomainsDirectory().getPurchasingDomain().getPurchasingRepository(); SupplierProduct supplierProduct = purchasingRepository.getSupplierProduct(cart.getPartyId(), productId, new BigDecimal(quantity), cart.getCurrency()); if (supplierProduct == null) { // create a supplier product GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); supplierProduct = new SupplierProduct(); supplierProduct.setProductId(productId); supplierProduct.setSupplierProductId(productId); supplierProduct.setPartyId(cart.getPartyId()); supplierProduct.setMinimumOrderQuantity(BigDecimal.ZERO); supplierProduct.setLastPrice(BigDecimal.ZERO); supplierProduct.setCurrencyUomId(cart.getCurrency()); supplierProduct.setAvailableFromDate(UtilDateTime.nowTimestamp()); supplierProduct.setComments(UtilProperties.getMessage(PURCHASING_LABEL, "PurchOrderCreateSupplierProductByUserLogin", UtilMisc.toMap("userLoginId", userLogin.getString("userLoginId")), locale)); //use purchasingRepository to create new SupplierProduct purchasingRepository.createSupplierProduct(supplierProduct); Debug.logInfo("created for purchase order entry by " + userLogin.getString("userLoginId") + ", productId is [" + productId + "], partyId is [" + cart.getPartyId() + "]", MODULE); } } //using old ofbiz code to add order item BigDecimal selectedAmount = null; if (selectedAmountDbl != null) { selectedAmount = BigDecimal.valueOf(selectedAmountDbl); } BigDecimal quantityBd = BigDecimal.valueOf(quantity); BigDecimal reservLength = null; if (reservLengthDbl != null) { reservLength = BigDecimal.valueOf(reservLengthDbl); } BigDecimal reservPersons = null; if (reservPersonsDbl != null) { reservPersons = BigDecimal.valueOf(reservPersonsDbl); } int index = cart.addOrIncreaseItem(productId, selectedAmount, quantityBd, reservStart, reservLength, reservPersons, shipBeforeDate, shipAfterDate, features, attributes, prodCatalogId, configWrapper, itemType, itemGroupNumber, parentProductId, dispatcher); return index; } /** * Custom append item to order method. * This is a wrapper for the edit order screen that checks for a survey if necessary. * Then the controller should be set to call the opentaps.appendOrderItem service on success. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value */ @SuppressWarnings("unchecked") public static String appendItemToOrder(HttpServletRequest request, HttpServletResponse response) { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); Locale locale = UtilHttp.getLocale(request); String orderId = UtilCommon.getParameter(request, "orderId"); if (orderId == null) { UtilMessage.addRequiredFieldError(request, "orderId"); return "error"; } OrderReadHelper orh = new OrderReadHelper(delegator, orderId); String productId = UtilCommon.getParameter(request, "productId"); if (productId == null) { UtilMessage.addRequiredFieldError(request, "productId"); return "error"; } // find Product match using comprehensive search try { Map results = dispatcher.runSync("getProductByComprehensiveSearch", UtilMisc.toMap("productId", productId)); if (ServiceUtil.isError(results) || ServiceUtil.isFailure(results)) { return UtilMessage.createAndLogEventError(request, results, locale, MODULE); } productId = (String) results.get("productId"); } catch (GenericServiceException e) { return UtilMessage.createAndLogEventError(request, e, locale, MODULE); } // handle surveys List<GenericValue> surveys = ProductStoreWorker.getProductSurveys(delegator, orh.getProductStoreId(), productId, "CART_ADD"); if (surveys != null && surveys.size() > 0) { // check if a survey was submitted String surveyResponseId = (String) request.getAttribute("surveyResponseId"); if (UtilValidate.isEmpty(surveyResponseId)) { // set up a surveyAction and surveyWrapper, then redirect to survey ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(surveys.get(0), orh.getPlacingParty().getString("partyId"), UtilHttp.getParameterMap(request)); request.setAttribute("surveyWrapper", wrapper); request.setAttribute("surveyAction", "appendItemToOrderSurvey"); return "survey"; } } return "success"; } /** * Gets the <code>OpentapsShoppingCart</code> shopping cart from the session, or null if it did not exist. * @param request a <code>HttpServletRequest</code> value * @return a <code>ShoppingCart</code> value */ public static OpentapsShoppingCart getCart(HttpServletRequest request) { HttpSession session = request.getSession(true); // if one already exists, return it ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingCart"); if (cart == null) { return null; } if (cart instanceof OpentapsShoppingCart) { return (OpentapsShoppingCart) cart; } else { OpentapsShoppingCart opentapsCart = new OpentapsShoppingCart(cart); session.setAttribute("shoppingCart", opentapsCart); return opentapsCart; } } /** * Gets the <code>OpentapsShoppingCart</code> shopping cart from the session, or create it. * * @param request a <code>HttpServletRequest</code> value * @return a <code>ShoppingCart</code> value */ public static ShoppingCart getOrInitializeCart(HttpServletRequest request) { HttpSession session = request.getSession(true); GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); // if one already exists, return it ShoppingCart cart = getCart(request); if (cart != null) { if (cart instanceof OpentapsShoppingCart) { return cart; } else { OpentapsShoppingCart opentapsCart = new OpentapsShoppingCart(cart); Debug.logWarning("Converting ShoppingCart -> OpentapsShoppingCart, reset name from [" + opentapsCart.getOrderName() + "] to [" + cart.getOrderName() + "]", MODULE); opentapsCart.setOrderName(cart.getOrderName()); return opentapsCart; } } // get or initialize the product store, first from session, then from request // I think (but am not sure) that once an item has been added, the productStoreId should be in session, so this prevents someone // from over-writing it with a URL parameter String productStoreId = (String) session.getAttribute("productStoreId"); if (productStoreId == null) { productStoreId = request.getParameter("productStoreId"); } GenericValue productStore = null; try { productStore = delegator.findByPrimaryKeyCache("ProductStore", UtilMisc.toMap("productStoreId", productStoreId)); } catch (GenericEntityException e) { Debug.logError(e, MODULE); return null; } if (productStore == null) { throw new IllegalArgumentException("Product Store with ID [" + productStoreId + "] not found."); } session.setAttribute("productStoreId", productStoreId); // initialize a new cart String webSiteId = null; String billFromVendorPartyId = productStore.getString("payToPartyId"); String currencyUomId = productStore.getString("defaultCurrencyUomId"); String billToCustomerPartyId = request.getParameter("partyId"); OpentapsShoppingCart opentapsCart = new OpentapsShoppingCart(delegator, productStoreId, webSiteId, UtilHttp.getLocale(request), currencyUomId, billToCustomerPartyId, billFromVendorPartyId); opentapsCart.setOrderPartyId(billToCustomerPartyId); // this is the actual partyId used by cart system opentapsCart.setOrderType("SALES_ORDER"); session.setAttribute("shoppingCart", opentapsCart); // set sales channel first from request parameter, then from product store if (UtilValidate.isNotEmpty(request.getParameter("salesChannelEnumId"))) { opentapsCart.setChannelType(request.getParameter("salesChannelEnumId")); } else if ((productStore != null) && (UtilValidate.isNotEmpty(productStore.getString("defaultSalesChannelEnumId")))) { opentapsCart.setChannelType(productStore.getString("defaultSalesChannelEnumId")); } // erase any pre-existing tracking code session.removeAttribute("trackingCodeId"); return opentapsCart; } /** * Updates a ship group. * * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs */ public static String updateShipGroup(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException { return updateShipGroup(request, response, null); } /** * Updates a ship group. * * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @param shipWrapper an <code>OpentapsShippingEstimateWrapper</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs */ public static String updateShipGroup(HttpServletRequest request, HttpServletResponse response, OpentapsShippingEstimateWrapper shipWrapper) throws GenericEntityException { String shipGroupSeqIdStr = request.getParameter("shipGroupSeqId"); int shipGroupSeqId = Integer.parseInt(shipGroupSeqIdStr); String contactMechId = request.getParameter("contactMechId"); String carrierPartyId = request.getParameter("carrierPartyId"); String shipmentMethodTypeId = request.getParameter("shipmentMethodTypeId"); Boolean maySplit = new Boolean("Y".equals(request.getParameter("maySplit"))); Boolean isGift = new Boolean("Y".equals(request.getParameter("isGift"))); String shippingInstructions = request.getParameter("shippingInstructions"); String giftMessage = request.getParameter("giftMessage"); String shipBeforeDate = request.getParameter("shipBeforeDate"); String thirdPartyAccountNumber = request.getParameter("thirdPartyAccountNumber"); String thirdPartyPostalCode = request.getParameter("thirdPartyPostalCode"); String thirdPartyCountryCode = request.getParameter("thirdPartyCountryCode"); Boolean isCOD = new Boolean("Y".equals(request.getParameter("isCOD"))); GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); ShoppingCart cart = getOrInitializeCart(request); return updateShipGroup(dispatcher, delegator, cart, shipGroupSeqId, contactMechId, carrierPartyId, shipmentMethodTypeId, maySplit, isGift, shippingInstructions, giftMessage, shipBeforeDate, thirdPartyAccountNumber, thirdPartyPostalCode, thirdPartyCountryCode, isCOD, shipWrapper, UtilCommon.getTimeZone(request), UtilHttp.getLocale(request)); } /** * Describe <code>updateShipGroup</code> method here. * * @param dispatcher a <code>LocalDispatcher</code> value * @param delegator a <code>GenericDelegator</code> value * @param cart the <code>ShoppingCart</code> * @param shipGroupSeqId the ID of the ship group to update * @param contactMechId the shipping address to set * @param carrierPartyId the shipping carrier to set * @param shipmentMethodTypeId the shipment method type to set * @param maySplit the may split flag for the ship group, defaults to false * @param isGift the is gift flag for the ship group, defaults to false * @param shippingInstructions the shipping instructions to set for the ship group * @param giftMessage the gift message if is gift * @param shipBeforeDateString the date to ship before * @param thirdPartyAccountNumber the account number for third party shipping * @param thirdPartyPostalCode the postal code for third party shipping * @param thirdPartyCountryCode the country code for third party shipping * @param isCOD the is cash on delivery flag for the ship group * @param shipWrapper an <code>OpentapsShippingEstimateWrapper</code> value * @param timeZone a <code>TimeZone</code> value * @param locale a <code>Locale</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static String updateShipGroup(LocalDispatcher dispatcher, GenericDelegator delegator, ShoppingCart cart, int shipGroupSeqId, String contactMechId, String carrierPartyId, String shipmentMethodTypeId, Boolean maySplit, Boolean isGift, String shippingInstructions, String giftMessage, String shipBeforeDateString, String thirdPartyAccountNumber, String thirdPartyPostalCode, String thirdPartyCountryCode, Boolean isCOD, OpentapsShippingEstimateWrapper shipWrapper, TimeZone timeZone, Locale locale) throws GenericEntityException { if (UtilValidate.isEmpty(cart)) { Debug.logWarning("updateShipGroup: empty cart, nothing to do", MODULE); return "success"; } List cartShipGroups = cart.getShipGroups(); if (UtilValidate.isEmpty(cartShipGroups)) { Debug.logWarning("updateShipGroup: no shipping group, nothig to do", MODULE); return "success"; } ShoppingCart.CartShipInfo shipGroup = (ShoppingCart.CartShipInfo) cartShipGroups.get(shipGroupSeqId); if (UtilValidate.isEmpty(shipGroup)) { Debug.logWarning("updateShipGroup: empty shipGroup, nothing to do", MODULE); return "success"; } GenericValue productStore = delegator.findByPrimaryKey("ProductStore", UtilMisc.toMap("productStoreId", cart.getProductStoreId())); boolean noShipOnDropShipGroups = "Y".equals(productStore.get("noShipOnDropShipGroups")); cart.setItemShipGroupEstimate(BigDecimal.ZERO, shipGroupSeqId); Debug.logInfo("updateShipGroup: Setting shipping method [" + shipmentMethodTypeId + "] for shipping group [" + shipGroupSeqId + "]", MODULE); cart.setShipmentMethodTypeId(shipGroupSeqId, shipmentMethodTypeId); if (noShipOnDropShipGroups && UtilValidate.isNotEmpty(cart.getSupplierPartyId(shipGroupSeqId))) { cart.setCarrierPartyId(shipGroupSeqId, "_NA_"); cart.setShipmentMethodTypeId(shipGroupSeqId, "NO_SHIPPING"); } else if ("NO_SHIPPING".equals(shipmentMethodTypeId)) { if (!cart.shippingApplies()) { if (productStore.get("inventoryFacilityId") != null) { // Use the address of the productStore's facility List facilityMechPurps = delegator.findByAndCache("FacilityContactMechPurpose", UtilMisc.toMap("facilityId", productStore.get("inventoryFacilityId"), "contactMechPurposeTypeId", "SHIP_ORIG_LOCATION")); facilityMechPurps = EntityUtil.filterByDate(facilityMechPurps); if (UtilValidate.isNotEmpty(facilityMechPurps)) { contactMechId = EntityUtil.getFirst(facilityMechPurps).getString("contactMechId"); } } } cart.setCarrierPartyId(shipGroupSeqId, "_NA_"); } else { cart.setCarrierPartyId(shipGroupSeqId, carrierPartyId); } cart.setShippingContactMechId(shipGroupSeqId, contactMechId); cart.setMaySplit(shipGroupSeqId, UtilValidate.isNotEmpty(maySplit) ? maySplit : Boolean.FALSE); cart.setIsGift(shipGroupSeqId, UtilValidate.isNotEmpty(isGift) ? isGift : Boolean.FALSE); if (UtilValidate.isEmpty(shipGroup.carrierRoleTypeId)) { shipGroup.carrierRoleTypeId = "CARRIER"; } boolean isCodChanged = false; if (cart instanceof OpentapsShoppingCart) { OpentapsShoppingCart opentapsCart = (OpentapsShoppingCart) cart; // set or unset the third party billing account information // only if the account is supplied will postal code and country code be set // if the third party billing account is null then all will be cleared if (UtilValidate.isNotEmpty(thirdPartyAccountNumber)) { opentapsCart.setThirdPartyAccountNumber(shipGroupSeqId, thirdPartyAccountNumber); if (UtilValidate.isNotEmpty(thirdPartyPostalCode)) { opentapsCart.setThirdPartyPostalCode(shipGroupSeqId, thirdPartyPostalCode); } if (UtilValidate.isNotEmpty(thirdPartyCountryCode)) { opentapsCart.setThirdPartyCountryCode(shipGroupSeqId, thirdPartyCountryCode); } } else { opentapsCart.setThirdPartyAccountNumber(shipGroupSeqId, null); opentapsCart.setThirdPartyPostalCode(shipGroupSeqId, null); opentapsCart.setThirdPartyCountryCode(shipGroupSeqId, null); } boolean newIsCod = UtilValidate.isNotEmpty(isCOD) && isCOD.booleanValue(); if (opentapsCart.getCOD(shipGroupSeqId) != newIsCod) { isCodChanged = true; Debug.logInfo("Is COD changed, will force shipping estimate update", MODULE); opentapsCart.setCOD(shipGroupSeqId, newIsCod); } } cart.setShippingInstructions(shipGroupSeqId, UtilValidate.isNotEmpty(shippingInstructions) ? shippingInstructions : null); cart.setGiftMessage(shipGroupSeqId, UtilValidate.isNotEmpty(giftMessage) ? giftMessage : null); Timestamp newShipBeforeDate = null; if (UtilValidate.isNotEmpty(shipBeforeDateString)) { newShipBeforeDate = UtilDate.toTimestamp(shipBeforeDateString, timeZone, locale); if (UtilValidate.isEmpty(newShipBeforeDate)) { Debug.logError("Invalid shipBeforeDate [" + shipBeforeDateString + "] in OrderEvents.updateShipGroup() - ignoring", MODULE); } else { newShipBeforeDate = UtilDateTime.getDayEnd(newShipBeforeDate); } } if (UtilValidate.isEmpty(newShipBeforeDate)) { // If not overridden, set the shipGroup.shipBeforeDate to the earliest shipBeforeDate of the shipGroup's items newShipBeforeDate = getShipGroupShipBeforeDateByItem(cart, shipGroupSeqId); } cart.setShipBeforeDate(shipGroupSeqId, newShipBeforeDate); updateShipGroupShippingEstimate(dispatcher, delegator, cart, shipGroupSeqId, shipWrapper, isCodChanged); return "success"; } /** * Updates the shipping estimate for the given ship group in the cart. * * @param dispatcher a <code>LocalDispatcher</code> value * @param delegator a <code>GenericDelegator</code> value * @param cart a <code>ShoppingCart</code> value * @param shipGroupSeqId an <code>int</code> value * @param shipWrapper an <code>OpentapsShippingEstimateWrapper</code> value * @exception GenericEntityException if an error occurs */ public static void updateShipGroupShippingEstimate(LocalDispatcher dispatcher, GenericDelegator delegator, ShoppingCart cart, int shipGroupSeqId, OpentapsShippingEstimateWrapper shipWrapper) throws GenericEntityException { updateShipGroupShippingEstimate(dispatcher, delegator, cart, shipGroupSeqId, shipWrapper, false); } /** * Updates the shipping estimate for the given ship group in the cart. * * @param dispatcher a <code>LocalDispatcher</code> value * @param delegator a <code>GenericDelegator</code> value * @param cart a <code>ShoppingCart</code> value * @param shipGroupSeqId an <code>int</code> value * @param shipWrapper an <code>OpentapsShippingEstimateWrapper</code> value * @param force set to <code>true</code> to force the estimate re-calculation, else only updates it if the shipping address changed * @exception GenericEntityException if an error occurs */ public static void updateShipGroupShippingEstimate(LocalDispatcher dispatcher, GenericDelegator delegator, ShoppingCart cart, int shipGroupSeqId, OpentapsShippingEstimateWrapper shipWrapper, boolean force) throws GenericEntityException { if (shipWrapper == null && cart instanceof OpentapsShoppingCart) { shipWrapper = ((OpentapsShoppingCart) cart).getShipEstimateWrapper(shipGroupSeqId); } if (shipWrapper == null) { shipWrapper = new OpentapsShippingEstimateWrapper(dispatcher, cart, shipGroupSeqId); } if (UtilValidate.isNotEmpty(shipWrapper)) { // Update the address of the shipping estimate wrapper, if necessary - this will trigger an update of shipping estimates if (force || UtilValidate.isEmpty(shipWrapper.getShippingAddress()) || !shipWrapper.getShippingAddress().getString("contactMechId").equals(cart.getShippingContactMechId(shipGroupSeqId))) { GenericValue shippingAddress = null; if (UtilValidate.isNotEmpty(cart.getShippingContactMechId(shipGroupSeqId))) { shippingAddress = delegator.findByPrimaryKey("PostalAddress", UtilMisc.toMap("contactMechId", cart.getShippingContactMechId(shipGroupSeqId))); } shipWrapper.setShippingAddress(shippingAddress); } // Update the shipGroup shipping estimate - Double shipGroupEstimate = shipWrapper.getShippingEstimate(cart.getShipmentMethodTypeId(shipGroupSeqId), cart.getCarrierPartyId(shipGroupSeqId)); + BigDecimal shipGroupEstimate = shipWrapper.getShippingEstimate(cart.getShipmentMethodTypeId(shipGroupSeqId), cart.getCarrierPartyId(shipGroupSeqId)); if (UtilValidate.isNotEmpty(shipGroupEstimate)) { - cart.setItemShipGroupEstimate(BigDecimal.valueOf(shipGroupEstimate), shipGroupSeqId); + cart.setItemShipGroupEstimate(shipGroupEstimate, shipGroupSeqId); } if (cart instanceof OpentapsShoppingCart) { ((OpentapsShoppingCart) cart).setShipEstimateWrapper(shipGroupSeqId, shipWrapper); } } } /** * Updates the shipping estimate for all the ship groups in the cart. * * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs */ public static String updateCartShippingEstimates(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException { ShoppingCart cart = getOrInitializeCart(request); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); Debug.logInfo("updateCartShippingEstimates", MODULE); int shipGroups = cart.getShipGroupSize(); for (int i = 0; i < shipGroups; i++) { updateShipGroupShippingEstimate(dispatcher, delegator, cart, i, null); } return "success"; } /** * Gets the ship before date for the given ship group. * * @param cart a <code>ShoppingCart</code> value * @param shipGroupSeqId an <code>int</code> value * @return a <code>Timestamp</code> value */ @SuppressWarnings("unchecked") public static Timestamp getShipGroupShipBeforeDateByItem(ShoppingCart cart, int shipGroupSeqId) { Timestamp shipBeforeDate = null; Map shipItems = cart.getShipGroupItems(shipGroupSeqId); if (UtilValidate.isEmpty(shipItems)) { return shipBeforeDate; } Iterator siit = shipItems.keySet().iterator(); while (siit.hasNext()) { ShoppingCartItem item = (ShoppingCartItem) siit.next(); Timestamp itemShipBeforeDate = item.getShipBeforeDate(); if (UtilValidate.isEmpty(shipBeforeDate) || (UtilValidate.isNotEmpty(itemShipBeforeDate) && itemShipBeforeDate.before(shipBeforeDate))) { shipBeforeDate = item.getShipBeforeDate(); } } return shipBeforeDate; } /** * Gets the list of estimates for the given ship group of the cart. * * @param request a <code>HttpServletRequest</code> value * @param shipGroupSeqId an <code>int</code> value * @return a <code>List</code> value */ @SuppressWarnings("unchecked") public static List getCartShipEstimates(HttpServletRequest request, int shipGroupSeqId) { List shipEstimates = new ArrayList(); ShoppingCart cart = getOrInitializeCart(request); if (UtilValidate.isEmpty(cart)) { return shipEstimates; } if (UtilValidate.isEmpty(cart.getShipGroups())) { return shipEstimates; } LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); OpentapsShippingEstimateWrapper shipWrapper = null; if (cart instanceof OpentapsShoppingCart) { shipWrapper = ((OpentapsShoppingCart) cart).getShipEstimateWrapper(shipGroupSeqId); } if (shipWrapper == null) { shipWrapper = new OpentapsShippingEstimateWrapper(dispatcher, cart, shipGroupSeqId); } shipEstimates = getCartShipEstimates(request, cart, shipWrapper); return shipEstimates; } /** * Gets the list of estimates for each shipment method of the cart. * * @param request a <code>HttpServletRequest</code> value * @param cart a <code>ShoppingCart</code> value * @param shipWrapper an <code>OpentapsShippingEstimateWrapper</code> value * @return a <code>List</code> value */ @SuppressWarnings("unchecked") public static List getCartShipEstimates(HttpServletRequest request, ShoppingCart cart, OpentapsShippingEstimateWrapper shipWrapper) { GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); List shipEstimates = new ArrayList(); if (UtilValidate.isEmpty(cart)) { return shipEstimates; } if (UtilValidate.isEmpty(cart.getShipGroups())) { return shipEstimates; } List carrierShipmentMethods = shipWrapper.getShippingMethods(); Iterator csmit = carrierShipmentMethods.iterator(); while (csmit.hasNext()) { GenericValue carrierShipmentMethod = (GenericValue) csmit.next(); String carrierPartyId = carrierShipmentMethod.getString("partyId"); String shipmentMethodTypeId = carrierShipmentMethod.getString("shipmentMethodTypeId"); // skip no shipment method since this is accounted for in UI if ("NO_SHIPPING".equals(shipmentMethodTypeId)) { continue; } GenericValue method = null; try { method = carrierShipmentMethod.getRelatedOne("ShipmentMethodType"); } catch (GenericEntityException e) { continue; } if (method == null) { continue; } // If there's no estimate and the carrier party is someone meaningful, don't add it // to the map - that way the UI can maintain a list of available shipping methods. if (!"_NA_".equals(carrierPartyId) && !shipWrapper.getAllEstimates().containsKey(carrierShipmentMethod)) { continue; } Map shipEstimateMap = UtilMisc.toMap("carrierPartyId", carrierPartyId, "shipmentMethodTypeId", shipmentMethodTypeId, "description", carrierShipmentMethod.getString("description")); String carrierPartyName = PartyHelper.getPartyName(delegator, carrierPartyId, false); shipEstimateMap.put("carrierName", carrierPartyName); shipEstimateMap.put("userDescription", carrierShipmentMethod.get("userDescription")); - Double shipEstimate = shipWrapper.getShippingEstimate(shipmentMethodTypeId, carrierPartyId); + BigDecimal shipEstimate = shipWrapper.getShippingEstimate(shipmentMethodTypeId, carrierPartyId); if (!"_NA_".equals(carrierPartyId) && shipEstimate != null && shipEstimate.doubleValue() <= 0.0) { shipEstimate = null; // if a carrier estimate is 0, then avoid entering the shipEstimate so the UI can print Calculated Offline } if (shipEstimate != null) { String shipEstimateString = UtilFormatOut.formatCurrency(shipEstimate.doubleValue(), cart.getCurrency(), UtilHttp.getLocale(request)); shipEstimateMap.put("shipEstimate", shipEstimateString); shipEstimateMap.put("shipEstimateDouble", shipEstimate); } shipEstimates.add(shipEstimateMap); } return shipEstimates; } /** * Performs validation on the current Shipping Method Type and Shipping Address. * Normally this runs before switching to the Review Order page, and on error it displays * the crmsfaQuickCheckout page. * Validates that the shipping method is in ProductStoreShipmentMeth and that the * shipping address is not empty. * Note that the shipping options can still be changed later on the viewOrder page, this * won't be validated by this method then. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs */ public static String validateOrderShippingOptions(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException { GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); ShoppingCart cart = getOrInitializeCart(request); int shipGroups = cart.getShipGroupSize(); String productStoreId = cart.getProductStoreId(); String shipmentMethodTypeId; GenericValue shippingAddress; List<GenericValue> productStoreShipmentMeths = null; for (int i = 0; i < shipGroups; i++) { shipmentMethodTypeId = cart.getShipmentMethodTypeId(i); Debug.logInfo("shipGroup[" + i + "] has shipment method type = " + shipmentMethodTypeId, MODULE); if (UtilValidate.isEmpty(shipmentMethodTypeId)) { Debug.logError("No shipment method defined.", MODULE); UtilMessage.addError(request, "OpentapsError_ShippingMethodOrAddressMissing"); return "error"; } else { try { productStoreShipmentMeths = delegator.findByAnd("ProductStoreShipmentMeth", UtilMisc.toMap("productStoreId", productStoreId, "shipmentMethodTypeId", shipmentMethodTypeId)); } catch (GenericEntityException e) { Debug.logError(e.toString(), MODULE); productStoreShipmentMeths = null; } } // check if there is was a shipping method and it was valid for the cart product store if (UtilValidate.isEmpty(productStoreShipmentMeths)) { Debug.logError("The shipment method type [" + shipmentMethodTypeId + "] is not valid for the product store [" + productStoreId + "].", MODULE); UtilMessage.addError(request, "OpentapsError_ShippingMethodInvalid", UtilMisc.toMap("shipmentMethodTypeId", shipmentMethodTypeId, "productStoreId", productStoreId)); return "error"; } // now validate the shipping address // allows _NA_ for address unknown too if (!"_NA_".equals(cart.getShippingContactMechId())) { shippingAddress = cart.getShippingAddress(i); Debug.logInfo("shipGroup[" + i + "] shipping address = " + shippingAddress, MODULE); if (UtilValidate.isEmpty(shippingAddress)) { Debug.logError("No shipping address defined.", MODULE); UtilMessage.addError(request, "OpentapsError_ShippingMethodOrAddressMissing"); return "error"; } } } return "success"; } /** * Wrapper to support only update a postal address that is associated to an order and not to a party. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs * @exception GenericServiceException if an error occurs */ @SuppressWarnings("unchecked") public static String updatePostalAddress(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException, GenericServiceException { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); HttpSession session = request.getSession(); // validation for (String required : Arrays.asList("address1", "city", "postalCode")) { if (UtilValidate.isEmpty(UtilCommon.getParameter(request, required))) { UtilMessage.addError(request, "CrmError_MissingAddressFields"); return "error"; } } // check if we should only associate to the order (and not associate to the party) Boolean orderOnly = "Y".equals(UtilCommon.getParameter(request, "onlyForOrder")); // check if an orderId is given (shipGroupSeqId and oldContactMechId are also given to call updateOrderItemShipGroup) String orderId = UtilCommon.getParameter(request, "orderId"); // shipGroupSeqId may be null if we are creating a new ship group String shipGroupSeqId = UtilCommon.getParameter(request, "shipGroupSeqId"); Boolean applyToCart = false; String serviceName; if (!orderOnly) { // as a safety, only change the cart if the donePage is crmsfaQuickCheckout, so we are sure to be in the checkout process // TODO: Make a checkout postal address create/update screen that doesn't reuse the other postal address screens, so we don't need to check against this parameter applyToCart = "crmsfaQuickCheckout".equals(UtilCommon.getParameter(request, "donePage")); serviceName = "updatePartyPostalAddress"; } else { if (UtilValidate.isNotEmpty(orderId)) { Debug.logInfo("Only updating the Contact Mech for the current order [" + orderId + "]", MODULE); } else { applyToCart = true; Debug.logInfo("Only updating the Contact Mech for the cart", MODULE); } serviceName = "updatePostalAddress"; } // prepare the parameters for the service Map result; ModelService modelService = dispatcher.getDispatchContext().getModelService(serviceName); Map input = modelService.makeValid(UtilHttp.getParameterMap(request), "IN"); input.put("userLogin", session.getAttribute("userLogin")); // call the service try { result = dispatcher.runSync(serviceName, input); if (ServiceUtil.isError(result) || ServiceUtil.isFailure(result)) { Debug.logError(serviceName + " error", MODULE); // needed to bounce back the error messages to the UI ServiceUtil.getMessages(request, result, null); return "error"; } } catch (GenericServiceException e) { Debug.logError(e, MODULE); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } String contactMechId = (String) result.get("contactMechId"); // apply to order if the id was given if (UtilValidate.isNotEmpty(orderId) && UtilValidate.isNotEmpty(shipGroupSeqId)) { Debug.logInfo("Applying contactMech [" + contactMechId + "] to the order [" + orderId + "]", MODULE); // prepare the parameters for the service updateOrderItemShipGroup modelService = dispatcher.getDispatchContext().getModelService("updateOrderContactMech"); input = modelService.makeValid(UtilHttp.getParameterMap(request), "IN"); input.put("userLogin", session.getAttribute("userLogin")); input.put("contactMechId", contactMechId); // call the service updateOrderItemShipGroup try { result = dispatcher.runSync("updateOrderContactMech", input); if (ServiceUtil.isError(result) || ServiceUtil.isFailure(result)) { Debug.logError("updateOrderContactMech error", MODULE); // needed to bounce back the error messages to the UI ServiceUtil.getMessages(request, result, null); return "error"; } } catch (GenericServiceException e) { Debug.logError(e, MODULE); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } } else if (UtilValidate.isNotEmpty(orderId) && UtilValidate.isEmpty(shipGroupSeqId)) { // put the new contactMechId in the session as we did not assign it session.setAttribute("newContactMechId", contactMechId); } else if (applyToCart) { // check if it is a SHIPPING_LOCATION Boolean isShippingLocation = false; if (!orderOnly) { String partyId = UtilCommon.getParameter(request, "partyId"); // find "SHIPPING_LOCATION" PartyContactMechPurpose with valid date List purposes = null; try { purposes = EntityUtil.filterByDate(delegator.findByAnd("PartyContactMechPurpose", UtilMisc.toMap("partyId", partyId, "contactMechId", contactMechId, "contactMechPurposeTypeId", "SHIPPING_LOCATION")), true); } catch (GenericEntityException e) { Debug.logWarning(e, MODULE); } if (UtilValidate.isNotEmpty(purposes)) { isShippingLocation = true; } } // apply to cart if it is a Shipping address or if it is an order only contact mech (because then the purpose is not set) if (orderOnly || isShippingLocation) { Debug.logInfo("Applying contactMech [" + contactMechId + "] to the cart", MODULE); ShoppingCart cart = getOrInitializeCart(request); cart.setShippingContactMechId(contactMechId); updateCartShippingEstimates(request, response); } } // bounce back the success message to the UI ServiceUtil.getMessages(request, result, null); return "success"; } /** * Wrapper for createPostalAddressAndPurpose calling the ofbiz service createPartyPostalAddress * and updating the cart shipping address. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs * @exception GenericServiceException if an error occurs */ @SuppressWarnings("unchecked") public static String createPartyPostalAddress(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException, GenericServiceException { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); HttpSession session = request.getSession(); // validation for (String required : Arrays.asList("address1", "city", "postalCode")) { if (UtilValidate.isEmpty(UtilCommon.getParameter(request, required))) { UtilMessage.addError(request, "CrmError_MissingAddressFields"); return "error"; } } // check if an orderId is given (shipGroupSeqId and oldContactMechId are also given to call updateOrderItemShipGroup) String orderId = UtilCommon.getParameter(request, "orderId"); // shipGroupSeqId may be null if we are creating a new ship group String shipGroupSeqId = UtilCommon.getParameter(request, "shipGroupSeqId"); // if so, check if we should only associate to the order (and not associate to the party) Boolean orderOnly = "Y".equals(UtilCommon.getParameter(request, "onlyForOrder")); Boolean applyToCart = false; String serviceName; if (!orderOnly) { // as a safety, only change the cart if the donePage is crmsfaQuickCheckout, so we are sure to be in the checkout process // TODO: Make a checkout postal address create/update screen that doesn't reuse the other postal address screens, so we don't need to check against this parameter applyToCart = "crmsfaQuickCheckout".equals(UtilCommon.getParameter(request, "donePage")); serviceName = "createPartyPostalAddress"; } else { if (UtilValidate.isNotEmpty(orderId)) { Debug.logInfo("Only creating the Contact Mech for the current order [" + orderId + "]", MODULE); } else { applyToCart = true; Debug.logInfo("Only creating the Contact Mech for the cart", MODULE); } serviceName = "createPostalAddress"; } // prepare the parameters for the service Map result; ModelService modelService = dispatcher.getDispatchContext().getModelService(serviceName); Map input = modelService.makeValid(UtilHttp.getParameterMap(request), "IN"); input.put("userLogin", session.getAttribute("userLogin")); // call the service try { result = dispatcher.runSync(serviceName, input); if (ServiceUtil.isError(result) || ServiceUtil.isFailure(result)) { Debug.logError(serviceName + " error", MODULE); // needed to bounce back the error messages to the UI ServiceUtil.getMessages(request, result, null); return "error"; } } catch (GenericServiceException e) { Debug.logError(e, MODULE); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } String contactMechId = (String) result.get("contactMechId"); // apply to order if the order id and shipGroupSeqId were given if (UtilValidate.isNotEmpty(orderId) && UtilValidate.isNotEmpty(shipGroupSeqId)) { Debug.logInfo("Applying contactMech [" + contactMechId + "] to the order [" + orderId + "]", MODULE); // prepare the parameters for the service updateOrderItemShipGroup modelService = dispatcher.getDispatchContext().getModelService("updateOrderItemShipGroup"); input = modelService.makeValid(UtilHttp.getParameterMap(request), "IN"); input.put("userLogin", session.getAttribute("userLogin")); input.put("contactMechId", contactMechId); // call the service updateOrderItemShipGroup try { result = dispatcher.runSync("updateOrderItemShipGroup", input); if (ServiceUtil.isError(result) || ServiceUtil.isFailure(result)) { Debug.logError("updateOrderItemShipGroup error", MODULE); // needed to bounce back the error messages to the UI ServiceUtil.getMessages(request, result, null); return "error"; } } catch (GenericServiceException e) { Debug.logError(e, MODULE); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } } else if (UtilValidate.isNotEmpty(orderId) && UtilValidate.isEmpty(shipGroupSeqId)) { // put the new contactMechId in the session as we did not assign it session.setAttribute("newContactMechId", contactMechId); } else if (applyToCart) { // apply to cart if it is a Shipping address if ("SHIPPING_LOCATION".equals(request.getParameter("contactMechPurposeTypeId"))) { Debug.logInfo("Applying contactMech [" + contactMechId + "] to the order [" + orderId + "]", MODULE); ShoppingCart cart = getOrInitializeCart(request); cart.setShippingContactMechId(contactMechId); updateCartShippingEstimates(request, response); } } else if ("SHIPPING_LOCATION".equals(request.getParameter("contactMechPurposeTypeId"))) { Debug.logInfo("Done page was not crmsfaQuickCheckout, did not applied the new shipping address to the current cart.", MODULE); } // bounce back the "address created successfully" message to the UI ServiceUtil.getMessages(request, result, null); return "success"; } /** * Updates the items in the shopping cart. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return the event response string */ @SuppressWarnings("unchecked") public static String modifyCart(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); ShoppingCart cart = ShoppingCartEvents.getCartObject(request); Locale locale = UtilHttp.getLocale(request); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); Security security = (Security) request.getAttribute("security"); OpentapsShoppingCartHelper cartHelper = new OpentapsShoppingCartHelper(dispatcher, cart); String controlDirective; Map result; // not used yet: Locale locale = UtilHttp.getLocale(request); Map paramMap = UtilHttp.getParameterMap(request); String removeSelectedFlag = request.getParameter("removeSelected"); String[] selectedItems = request.getParameterValues("selectedItem"); boolean removeSelected = ("true".equals(removeSelectedFlag) && selectedItems != null && selectedItems.length > 0); result = cartHelper.modifyCart(security, userLogin, paramMap, removeSelected, selectedItems, locale); controlDirective = processResult(result, request); // Determine where to send the browser if (controlDirective.equals(ERROR)) { return "error"; } else { return "success"; } } private static final String NO_ERROR = "noerror"; private static final String NON_CRITICAL_ERROR = "noncritical"; private static final String ERROR = "error"; /** * This should be called to translate the error messages of the * <code>ShoppingCartHelper</code> to an appropriately formatted * <code>String</code> in the request object and indicate whether * the result was an error or not and whether the errors were * critical or not. * * @param result the result returned from the <code>ShoppingCartHelper</code> * @param request the servlet request instance to set the error messages in * @return one of NON_CRITICAL_ERROR, ERROR or NO_ERROR. */ @SuppressWarnings("unchecked") private static String processResult(Map result, HttpServletRequest request) { // Check for errors StringBuffer errMsg = new StringBuffer(); if (result.containsKey(ModelService.ERROR_MESSAGE_LIST)) { List errorMsgs = (List) result.get(ModelService.ERROR_MESSAGE_LIST); Iterator iterator = errorMsgs.iterator(); errMsg.append("<ul>"); while (iterator.hasNext()) { errMsg.append("<li>"); errMsg.append(iterator.next()); errMsg.append("</li>"); } errMsg.append("</ul>"); } else if (result.containsKey(ModelService.ERROR_MESSAGE)) { errMsg.append(result.get(ModelService.ERROR_MESSAGE)); request.setAttribute("_ERROR_MESSAGE_", errMsg.toString()); } // See whether there was an error if (errMsg.length() > 0) { request.setAttribute("_ERROR_MESSAGE_", errMsg.toString()); if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)) { return NON_CRITICAL_ERROR; } else { return ERROR; } } else { return NO_ERROR; } } /** * Prepare jasper parameters for running order report. * @param dl a <code>DomainsLoader</code> value * @param delegator a <code>GenericDelegator</code> value * @param dispatcher a <code>LocalDispatcher</code> value * @param userLogin a <code>GenericValue</code> value * @param locale a <code>Locale</code> value * @param orderId a <code>String</code> value * @param organizationPartyId a <code>String</code> value * @return the event response <code>String</code> * @throws GenericServiceException if an error occurs * @throws GenericEntityException if an error occurs * @throws PartyNotFoundException if an error occurs * @throws RepositoryException if an error occurs * @throws EntityNotFoundException if an error occurs */ @SuppressWarnings("unchecked") public static Map prepareOrderReportParameters(DomainsLoader dl, GenericDelegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, Locale locale, String orderId, String organizationPartyId) throws GenericServiceException, GenericEntityException, PartyNotFoundException, RepositoryException, EntityNotFoundException { Map<String, Object> parameters = FastMap.newInstance(); // placeholder for report parameters Map<String, Object> jrParameters = FastMap.newInstance(); // prepare company information Map<String, Object> organizationInfo = UtilCommon.getOrganizationHeaderInfo(organizationPartyId, delegator); jrParameters.putAll(organizationInfo); PartyReader pr = new PartyReader(organizationPartyId, delegator); jrParameters.put("website", pr.getWebsite()); jrParameters.put("primaryPhone", PartyContactHelper.getTelecomNumberByPurpose(organizationPartyId, "PRIMARY_PHONE", true, delegator)); jrParameters.put("primaryFax", PartyContactHelper.getTelecomNumberByPurpose(organizationPartyId, "FAX_NUMBER", true, delegator)); DomainsDirectory domains = dl.loadDomainsDirectory(); OrderRepositoryInterface orderRepository = domains.getOrderDomain().getOrderRepository(); PartyRepositoryInterface partyRepository = domains.getPartyDomain().getPartyRepository(); // load order object and put it to report parameters Order order = orderRepository.getOrderById(orderId); jrParameters.put("order", order); List<Map<String, Object>> reportData = new FastList<Map<String, Object>>(); // retrieve order item info and pass it to JR, add as report data for (org.opentaps.domain.order.OrderItem orderItem : order.getOrderItems()) { BigDecimal orderSubTotal = orderItem.isCancelled() ? new BigDecimal("0.0") : orderItem.getSubTotal(); Map<String, Object> reportLine = new FastMap<String, Object>(); if (orderItem.getProductId() != null) { reportLine.put("productId", orderItem.getProductId()); } if (orderItem.getOrderItemTypeId() != null) { reportLine.put("orderItemTypeId", orderItem.getOrderItemTypeId()); } reportLine.put("itemDescription", orderItem.getItemDescription()); reportLine.put("orderQuantity", orderItem.getOrderedQuantity()); reportLine.put("orderUnitPrice", orderItem.getUnitPrice()); reportLine.put("orderSubTotal", orderSubTotal); reportLine.put("adjustmentsAmount", orderItem.getOtherAdjustmentsAmount()); // put it into report data collection reportData.add(reportLine); } // retrieve supplier postal address for purchasing order and pass it to JR if (order.isPurchaseOrder() && order.getBillFromVendor() != null) { PostalAddress supplierAddress = partyRepository.getSupplierPostalAddress(order.getBillFromVendor()); if (supplierAddress != null) { jrParameters.put("supplierAddress", supplierAddress); } } // retrieve contact mech info and pass it to JR List<Map<String, Object>> orderContactMechList = FastList.newInstance(); for (OrderContactMech orderContactMech : order.getOrderContactMeches()) { Map<String, Object> contactMechLine = FastMap.newInstance(); ContactMech contactMech = orderContactMech.getContactMech(); if (contactMech.getContactMechTypeId().equals("POSTAL_ADDRESS") && contactMech.getPostalAddress() != null) { String contactMechPurposeType = orderContactMech.getContactMechPurposeType().getDescription(); contactMechLine.putAll(contactMech.getPostalAddress().toMap()); if (orderContactMech.getContactMechPurposeType() != null) { contactMechLine.put("contactMechPurposeType", contactMechPurposeType); } orderContactMechList.add(contactMechLine); } } if (UtilValidate.isNotEmpty(orderContactMechList)) { // if orderContactMechList not empty, then pass it to JR jrParameters.put("orderContactMechList", new JRMapCollectionDataSource(orderContactMechList)); } // retrieve shipping group info and pass it to JR List<Map<String, Object>> shipGroupList = FastList.newInstance(); for (OrderItemShipGroup shipGroup : order.getShipGroups()) { Map<String, Object> shipGroupLine = FastMap.newInstance(); String carrierName = org.opentaps.common.party.PartyHelper.getPartyName(shipGroup.getCarrierParty()); if (carrierName != null) { shipGroupLine.put("carrierName", carrierName); } if (shipGroup.getShipmentMethodType() != null) { shipGroupLine.put("shipmentMethodType", shipGroup.getShipmentMethodType().getDescription()); } shipGroupList.add(shipGroupLine); } if (UtilValidate.isNotEmpty(shipGroupList)) { // if shipGroupList not empty, then pass it to JR jrParameters.put("shipGroupList", new JRMapCollectionDataSource(shipGroupList)); } // retrieve order terms info and pass it to JR List<Map<String, Object>> orderTermList = FastList.newInstance(); for (OrderTerm orderTerm : order.getOrderTerms()) { Map<String, Object> orderTermLine = FastMap.newInstance(); orderTermLine.putAll(orderTerm.toMap()); if (orderTerm.getTermType() != null) { orderTermLine.put("termType", orderTerm.getTermType().getDescription()); } orderTermList.add(orderTermLine); } if (UtilValidate.isNotEmpty(orderTermList)) { // if orderTermList not empty, then pass it to JR jrParameters.put("orderTermList", new JRMapCollectionDataSource(orderTermList)); } // retrieve shipping adjustment info and pass it to JR List<Map<String, Object>> shipAdjustmentList = FastList.newInstance(); for (OrderAdjustment adj : order.getShippingAdjustments()) { BigDecimal adjustmentAmount = adj.calculateAdjustment(order); if (adjustmentAmount.doubleValue() != 0d) { Map<String, Object> adjLine = FastMap.newInstance(); adjLine.put("description", adj.getDescription()); adjLine.put("adjustmentAmount", adjustmentAmount); if (adj.getOrderAdjustmentType() != null) { adjLine.put("adjustmentType", adj.getOrderAdjustmentType().getDescription()); } shipAdjustmentList.add(adjLine); } } if (UtilValidate.isNotEmpty(shipAdjustmentList)) { // if shipAdjustmentList not empty, then pass it to JR jrParameters.put("shipAdjustmentList", new JRMapCollectionDataSource(shipAdjustmentList)); } // retrieve other adjustments such as promotions information and pass it to JR List<Map<String, Object>> otherAdjustmentList = FastList.newInstance(); for (OrderAdjustment adj : order.getNonShippingAdjustments()) { BigDecimal adjustmentAmount = adj.calculateAdjustment(order); if (adjustmentAmount.doubleValue() != 0d) { Map<String, Object> adjLine = FastMap.newInstance(); adjLine.put("description", adj.getDescription()); adjLine.put("adjustmentAmount", adjustmentAmount); if (adj.getOrderAdjustmentType() != null) { adjLine.put("adjustmentType", adj.getOrderAdjustmentType().getDescription()); } otherAdjustmentList.add(adjLine); } } if (UtilValidate.isNotEmpty(otherAdjustmentList)) { // if otherAdjustmentList not empty, then pass it to JR jrParameters.put("otherAdjustmentList", new JRMapCollectionDataSource(otherAdjustmentList)); } // retrieve order notes information and pass it to JR List<Map<String, Object>> notesList = FastList.newInstance(); for (OrderHeaderNoteView note : order.getNotes()) { Map<String, Object> noteLine = FastMap.newInstance(); //if have note content if (note.getInternalNote() != null && !note.getInternalNote().equals("Y")) { noteLine.putAll(note.toMap()); Map notePartyNameResult = dispatcher.runSync("getPartyNameForDate", UtilMisc.toMap("partyId", note.getNoteParty(), "compareDate", note.getNoteDateTime(), "lastNameFirst", "Y", "userLogin", userLogin)); if (ServiceUtil.isError(notePartyNameResult) || ServiceUtil.isFailure(notePartyNameResult)) { throw new GenericServiceException(ServiceUtil.getErrorMessage(notePartyNameResult)); } String fullName = (String) notePartyNameResult.get("fullName"); noteLine.put("fullName", fullName); notesList.add(noteLine); } } if (UtilValidate.isNotEmpty(notesList)) { // if notesList not empty, then pass it to JR jrParameters.put("notesList", new JRMapCollectionDataSource(notesList)); } // retrieve order payment information and pass it to JR List<Map<String, Object>> paymentsList = FastList.newInstance(); for (Payment payment : order.getPayments()) { Map<String, Object> paymentLine = FastMap.newInstance(); paymentLine.put("amountApplied", payment.getAmount()); paymentLine.put("effectiveDate", payment.getEffectiveDate()); paymentLine.put("paymentRefNum", payment.getPaymentRefNum()); if (payment.getPaymentMethod() != null && payment.getPaymentMethod().isCreditCard() && payment.getCreditCard() != null) { //payment method is credit card, just display last four number String maskNums = ""; for (int i = 0; i < payment.getCreditCard().getCardNumber().length() - 4; i++) { maskNums += "*"; } maskNums += payment.getCreditCard().getCardNumber().substring(payment.getCreditCard().getCardNumber().length() - 4); String creditCardInfo = payment.getCreditCard().getCardType() + " " + maskNums + " " + payment.getCreditCard().getExpireDate(); paymentLine.put("method", creditCardInfo); } else { paymentLine.put("method", payment.getPaymentMethodType().getDescription()); } paymentsList.add(paymentLine); } if (UtilValidate.isNotEmpty(paymentsList)) { // if paymentsList not empty, then pass it to JR jrParameters.put("paymentsList", new JRMapCollectionDataSource(paymentsList)); } JRMapCollectionDataSource jrDataSource = new JRMapCollectionDataSource(reportData); parameters.put("jrDataSource", jrDataSource); parameters.put("jrParameters", jrParameters); return parameters; } /** * Prepare data and parameters for running order report. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return the event response <code>String</code> */ @SuppressWarnings("unchecked") public static String prepareOrderReport(HttpServletRequest request, HttpServletResponse response) { GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); Locale locale = UtilHttp.getLocale(request); String orderId = UtilCommon.getParameter(request, "orderId"); String organizationPartyId = (String) request.getSession().getAttribute("organizationPartyId"); if (UtilValidate.isEmpty(organizationPartyId)) { //check if include organizationPartyId, else throw a event error organizationPartyId = UtilCommon.getParameter(request, "organizationPartyId"); if (UtilValidate.isEmpty(organizationPartyId)) { organizationPartyId = UtilConfig.getPropertyValue("opentaps", "organizationPartyId"); if (UtilValidate.isEmpty(organizationPartyId)) { UtilMessage.createAndLogEventError(request, "OpentapsError_CannotPrintOrderOrganizationPartyId", UtilMisc.toMap("orderId", orderId), locale, MODULE); } } } try { // get parameter for jasper DomainsLoader dl = new DomainsLoader(request); Map jasperParameters = prepareOrderReportParameters(dl, delegator, dispatcher, userLogin, locale, orderId, organizationPartyId); request.setAttribute("jrParameters", jasperParameters.get("jrParameters")); request.setAttribute("jrDataSource", jasperParameters.get("jrDataSource")); } catch (GenericEntityException e) { UtilMessage.createAndLogEventError(request, e, locale, MODULE); } catch (GenericServiceException e) { UtilMessage.createAndLogEventError(request, e, locale, MODULE); } catch (PartyNotFoundException e) { UtilMessage.createAndLogEventError(request, e, locale, MODULE); } catch (EntityNotFoundException e) { UtilMessage.createAndLogEventError(request, e, locale, MODULE); } catch (RepositoryException e) { UtilMessage.createAndLogEventError(request, e, locale, MODULE); } catch (InfrastructureException e) { UtilMessage.createAndLogEventError(request, e, locale, MODULE); } return "success"; } /** * From Ofbiz <code>ShippingEvents</code>, but also account for the COD surcharge. * * @param dispatcher a <code>LocalDispatcher</code> value * @param delegator a <code>GenericDelegator</code> value * @param orh an <code>OrderReadHelper</code> value * @param shipGroupSeqId a <code>String</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getShipEstimate(LocalDispatcher dispatcher, GenericDelegator delegator, OrderReadHelper orh, String shipGroupSeqId) { // check for shippable items if (!orh.shippingApplies()) { Map responseResult = ServiceUtil.returnSuccess(); responseResult.put("shippingTotal", BigDecimal.ZERO); return responseResult; } GenericValue shipGroup = orh.getOrderItemShipGroup(shipGroupSeqId); String shipmentMethodTypeId = shipGroup.getString("shipmentMethodTypeId"); String carrierRoleTypeId = shipGroup.getString("carrierRoleTypeId"); String carrierPartyId = shipGroup.getString("carrierPartyId"); String supplierPartyId = shipGroup.getString("supplierPartyId"); GenericValue shipAddr = orh.getShippingAddress(shipGroupSeqId); if (shipAddr == null) { return UtilMisc.toMap("shippingTotal", BigDecimal.ZERO); } String contactMechId = shipAddr.getString("contactMechId"); // check if need to add the COD surcharge boolean isCod = false; try { List<GenericValue> codPaymentPrefs = delegator.findByAnd("OrderPaymentPreference", UtilMisc.toList(EntityCondition.makeCondition("orderId", orh.getOrderId()), EntityCondition.makeCondition("paymentMethodTypeId", "EXT_COD"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"))); isCod = UtilValidate.isNotEmpty(codPaymentPrefs); } catch (GeneralException e) { return ServiceUtil.returnError("A problem occurred while getting the order payment preferences."); } Debug.logInfo("getShipEstimate: order [" + orh.getOrderId() + "] isCod = " + isCod, MODULE); return getShipGroupEstimate(dispatcher, delegator, orh.getOrderTypeId(), shipmentMethodTypeId, carrierPartyId, carrierRoleTypeId, contactMechId, orh.getProductStoreId(), supplierPartyId, orh.getShippableItemInfo(shipGroupSeqId), orh.getShippableWeight(shipGroupSeqId), orh.getShippableQuantity(shipGroupSeqId), orh.getShippableTotal(shipGroupSeqId), isCod); } /** * From Ofbiz <code>ShippingEvents</code>, but also account for the COD surcharge. * * @param dispatcher a <code>LocalDispatcher</code> value * @param delegator a <code>GenericDelegator</code> value * @param cart a <code>ShoppingCart</code> value * @param groupNo an <code>int</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getShipGroupEstimate(LocalDispatcher dispatcher, GenericDelegator delegator, OpentapsShoppingCart cart, int groupNo) { // check for shippable items if (!cart.shippingApplies()) { Map responseResult = ServiceUtil.returnSuccess(); responseResult.put("shippingTotal", BigDecimal.ZERO); return responseResult; } String shipmentMethodTypeId = cart.getShipmentMethodTypeId(groupNo); String carrierPartyId = cart.getCarrierPartyId(groupNo); return getShipGroupEstimate(dispatcher, delegator, cart.getOrderType(), shipmentMethodTypeId, carrierPartyId, null, cart.getShippingContactMechId(groupNo), cart.getProductStoreId(), cart.getSupplierPartyId(groupNo), cart.getShippableItemInfo(groupNo), cart.getShippableWeight(groupNo), cart.getShippableQuantity(groupNo), cart.getShippableTotal(groupNo), cart.getCOD(groupNo)); } /** * From Ofbiz <code>ShippingEvents</code>, but also account for the COD surcharge. * * @param dispatcher a <code>LocalDispatcher</code> value * @param delegator a <code>GenericDelegator</code> value * @param orderTypeId a <code>String</code> value * @param shipmentMethodTypeId a <code>String</code> value * @param carrierPartyId a <code>String</code> value * @param carrierRoleTypeId a <code>String</code> value * @param shippingContactMechId a <code>String</code> value * @param productStoreId a <code>String</code> value * @param supplierPartyId a <code>String</code> value * @param itemInfo a <code>List</code> value * @param shippableWeight a <code>double</code> value * @param shippableQuantity a <code>double</code> value * @param shippableTotal a <code>double</code> value * @param isCod flag indicating cod surcharges should be added * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getShipGroupEstimate(LocalDispatcher dispatcher, GenericDelegator delegator, String orderTypeId, String shipmentMethodTypeId, String carrierPartyId, String carrierRoleTypeId, String shippingContactMechId, String productStoreId, String supplierPartyId, List itemInfo, BigDecimal shippableWeight, BigDecimal shippableQuantity, BigDecimal shippableTotal, boolean isCod) { String standardMessage = "A problem occurred calculating shipping. Fees will be calculated offline."; List errorMessageList = new ArrayList(); if (shipmentMethodTypeId == null || carrierPartyId == null) { if ("SALES_ORDER".equals(orderTypeId)) { errorMessageList.add("Please Select Your Shipping Method."); return ServiceUtil.returnError(errorMessageList); } else { return ServiceUtil.returnSuccess(); } } if (carrierRoleTypeId == null) { carrierRoleTypeId = "CARRIER"; } if (shippingContactMechId == null) { errorMessageList.add("Please Select Your Shipping Address."); return ServiceUtil.returnError(errorMessageList); } // if as supplier is associated, then we have a drop shipment and should use the origin shipment address of it String shippingOriginContactMechId = null; if (supplierPartyId != null) { try { GenericValue originAddress = ShippingEvents.getShippingOriginContactMech(delegator, supplierPartyId); if (originAddress == null) { return ServiceUtil.returnError("Cannot find the origin shipping address (SHIP_ORIG_LOCATION) for the supplier with ID [" + supplierPartyId + "]. Will not be able to calculate drop shipment estimate."); } shippingOriginContactMechId = originAddress.getString("contactMechId"); } catch (GeneralException e) { return ServiceUtil.returnError(standardMessage); } } // no shippable items; we won't change any shipping at all if (shippableQuantity.signum() == 0) { Map result = ServiceUtil.returnSuccess(); result.put("shippingTotal", BigDecimal.ZERO); return result; } // check for an external service call GenericValue storeShipMethod = ProductStoreWorker.getProductStoreShipmentMethod(delegator, productStoreId, shipmentMethodTypeId, carrierPartyId, carrierRoleTypeId); if (storeShipMethod == null) { errorMessageList.add("No applicable shipment method found."); return ServiceUtil.returnError(errorMessageList); } // the initial amount before manual estimates BigDecimal shippingTotal = BigDecimal.ZERO; // prepare the service invocation fields Map serviceFields = new HashMap(); serviceFields.put("initialEstimateAmt", shippingTotal); serviceFields.put("shippableTotal", shippableTotal); serviceFields.put("shippableQuantity", shippableQuantity); serviceFields.put("shippableWeight", shippableWeight); serviceFields.put("shippableItemInfo", itemInfo); serviceFields.put("productStoreId", productStoreId); serviceFields.put("carrierRoleTypeId", "CARRIER"); serviceFields.put("carrierPartyId", carrierPartyId); serviceFields.put("shipmentMethodTypeId", shipmentMethodTypeId); serviceFields.put("shippingContactMechId", shippingContactMechId); serviceFields.put("shippingOriginContactMechId", shippingOriginContactMechId); // call the external shipping service try { BigDecimal externalAmt = ShippingEvents.getExternalShipEstimate(dispatcher, storeShipMethod, serviceFields); if (externalAmt != null) { shippingTotal = shippingTotal.add(externalAmt); } } catch (GeneralException e) { return ServiceUtil.returnError(standardMessage); } // update the initial amount serviceFields.put("initialEstimateAmt", shippingTotal); // call the generic estimate service try { BigDecimal genericAmt = ShippingEvents.getGenericShipEstimate(dispatcher, storeShipMethod, serviceFields); if (genericAmt != null) { shippingTotal = shippingTotal.add(genericAmt); } } catch (GeneralException e) { return ServiceUtil.returnError(standardMessage); } // add COD surcharges if (isCod) { BigDecimal codSurcharge = storeShipMethod.getBigDecimal("codSurcharge"); if (UtilValidate.isNotEmpty(codSurcharge)) { shippingTotal = shippingTotal.add(codSurcharge); } } // return the totals Map responseResult = ServiceUtil.returnSuccess(); responseResult.put("shippingTotal", shippingTotal); return responseResult; } } diff --git a/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/shoppingcart/OpentapsShippingEstimateWrapper.java b/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/shoppingcart/OpentapsShippingEstimateWrapper.java index 1d24728ea..82448cfa7 100644 --- a/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/shoppingcart/OpentapsShippingEstimateWrapper.java +++ b/hot-deploy/opentaps-common/src/common/org/opentaps/common/order/shoppingcart/OpentapsShippingEstimateWrapper.java @@ -1,340 +1,340 @@ /* * Copyright (c) 2006 - 2009 Open Source Strategies, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Honest Public License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Honest Public License for more details. * * You should have received a copy of the Honest Public License * along with this program; if not, write to Funambol, * 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA */ /* Copyright (c) 2005-2006 Open Source Strategies, Inc. */ /* * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal 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. */ /* This file has been modified by Open Source Strategies, Inc. */ package org.opentaps.common.order.shoppingcart; import java.io.Serializable; import java.math.BigDecimal; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilNumber; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.order.shoppingcart.ShoppingCart; import org.ofbiz.order.shoppingcart.shipping.ShippingEvents; import org.ofbiz.product.store.ProductStoreWorker; import org.ofbiz.service.GenericDispatcher; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ServiceUtil; /** * This class replaces the OFBiz ShippingEstimateWrapper, which is still used by the Order and eCommerce applications and is * still possible to instantiate. * * @version $Rev$ */ public class OpentapsShippingEstimateWrapper implements Serializable { private static final String MODULE = OpentapsShippingEstimateWrapper.class.getName(); private static final int DECIMALS = UtilNumber.getBigDecimalScale("order.decimals"); private static final int ROUNDING = UtilNumber.getBigDecimalRoundingMode("order.rounding"); protected String dispatcherName = null; protected Map shippingEstimates = null; protected List shippingMethods = null; protected GenericValue shippingAddress = null; protected Map shippableItemFeatures = null; protected List shippableItemSizes = null; protected List shippableItemInfo = null; protected String productStoreId = null; protected BigDecimal shippableQuantity = BigDecimal.ZERO; protected BigDecimal shippableWeight = BigDecimal.ZERO; protected BigDecimal shippableTotal = BigDecimal.ZERO; protected Map availableCarrierServices = new HashMap(); protected ShoppingCart cart = null; protected int shipGroupSeqId = 0; protected String supplierPartyId = null; protected GenericValue shippingOriginAddress = null; public static OpentapsShippingEstimateWrapper getWrapper(LocalDispatcher dispatcher, ShoppingCart cart, int shipGroup) { return new OpentapsShippingEstimateWrapper(dispatcher, cart, shipGroup); } public OpentapsShippingEstimateWrapper(LocalDispatcher dispatcher, ShoppingCart cart, int shipGroup) { this.cart = cart; this.shipGroupSeqId = shipGroup; this.dispatcherName = dispatcher.getName(); this.shippableItemFeatures = cart.getFeatureIdQtyMap(shipGroup); this.shippableItemSizes = cart.getShippableSizes(shipGroup); this.shippableItemInfo = cart.getShippableItemInfo(shipGroup); this.shippableQuantity = cart.getShippableQuantity(shipGroup); this.shippableWeight = cart.getShippableWeight(shipGroup); this.shippableTotal = cart.getShippableTotal(shipGroup); this.shippingAddress = cart.getShippingAddress(shipGroup); this.productStoreId = cart.getProductStoreId(); this.supplierPartyId = cart.getSupplierPartyId(shipGroup); // load the drop ship origin address if (supplierPartyId != null) { try { this.shippingOriginAddress = ShippingEvents.getShippingOriginContactMech(cart.getDelegator(), supplierPartyId); } catch (GeneralException e) { Debug.logError("Cannot obtain origin shipping address for supplier [" + supplierPartyId + "] due to: " + e.getMessage(), MODULE); } } this.loadShippingMethods(); this.loadEstimates(); if (this.cart instanceof OpentapsShoppingCart) { ((OpentapsShoppingCart) this.cart).setShipEstimateWrapper(shipGroup, this); } } @SuppressWarnings("unchecked") protected void loadShippingMethods() { try { this.shippingMethods = ProductStoreWorker.getAvailableStoreShippingMethods(this.cart.getDelegator(), productStoreId, shippingAddress, shippableItemSizes, shippableItemFeatures, shippableWeight, shippableTotal); // Replace ProductStoreShipMethodView with extended ProductStoreShipMethAndCarrier records to make it easier to get the carrierServiceCodes if (UtilValidate.isNotEmpty(this.shippingMethods)) { List<GenericValue> prodStoreShipMethIds = EntityUtil.getFieldListFromEntityList(this.shippingMethods, "productStoreShipMethId", true); this.shippingMethods = this.cart.getDelegator().findByCondition("ProductStoreShipMethAndCarrier", EntityCondition.makeCondition("productStoreShipMethId", EntityOperator.IN, prodStoreShipMethIds), null, UtilMisc.toList("sequenceNumber")); } } catch (Throwable t) { Debug.logError(t, MODULE); } // Initialize the map of available services for each carrier. This starts out populated with every service code defined in the CarrierShipmentMethod records, // and will be trimmed by the loadEstimatesUPS() method and its siblings. List<String> carrierPartyIds = EntityUtil.getFieldListFromEntityList(this.shippingMethods, "partyId", true); for (String carrierPartyId : carrierPartyIds) { List<GenericValue> carrierProdStoreShipMethods = EntityUtil.filterByAnd(this.shippingMethods, UtilMisc.toMap("partyId", carrierPartyId)); carrierProdStoreShipMethods = EntityUtil.filterByCondition(carrierProdStoreShipMethods, EntityCondition.makeCondition("carrierServiceCode", EntityOperator.NOT_EQUAL, null)); availableCarrierServices.put(carrierPartyId, EntityUtil.getFieldListFromEntityList(carrierProdStoreShipMethods, "carrierServiceCode", true)); } } protected void loadEstimates() { this.shippingEstimates = new HashMap(); // Rate shop for all UPS methods loadEstimatesUPS(); // This is where we get all the other non-rate shop methods, USPS, etc., plus UPS methods without designated serviceName or carrierServiceCodes loadOtherEstimates(); addCodSurchargesToEstimates(); } /* * This method will loop through the List of shippingMethods and then fill in a shipping estimate for each one which does not already have a rate estimate. * The idea is to run this after any group rate shopping methods, such as the UPS Rate Shop, so that other shipping methods, such as USPS or any other rate-table * based method, would get a rate. * Note that this method is basically the old OFBiz loadEstimates, except that we check to make sure that a rate estimate is not already available first. */ @SuppressWarnings("unchecked") protected void loadOtherEstimates() { if (shippingMethods != null) { Iterator i = shippingMethods.iterator(); while (i.hasNext()) { GenericValue shipMethod = (GenericValue) i.next(); String shippingMethodTypeId = shipMethod.getString("shipmentMethodTypeId"); String carrierRoleTypeId = shipMethod.getString("roleTypeId"); String carrierPartyId = shipMethod.getString("partyId"); // Only calculate the shipment estimate if there is not already one if (shippingEstimates.containsKey(shipMethod)) { continue; } // Skip this estimate if the method has a carrierServiceCode that isn't available to the current origin/destination addresses String carrierServiceCode = shipMethod.getString("carrierServiceCode"); if (UtilValidate.isNotEmpty(carrierServiceCode)) { if (!availableCarrierServices.containsKey(carrierPartyId)) { continue; } if (UtilValidate.isEmpty(availableCarrierServices.get(carrierPartyId))) { continue; } if (!((List) availableCarrierServices.get(carrierPartyId)).contains(carrierServiceCode)) { continue; } } String shippingCmId = shippingAddress != null ? shippingAddress.getString("contactMechId") : null; Map estimateMap = ShippingEvents.getShipGroupEstimate(GenericDispatcher.getLocalDispatcher(this.dispatcherName, cart.getDelegator()), cart.getDelegator(), "SALES_ORDER", shippingMethodTypeId, carrierPartyId, carrierRoleTypeId, shippingCmId, productStoreId, supplierPartyId, shippableItemInfo, shippableWeight, shippableQuantity, shippableTotal, cart.getPartyId(), cart.getProductStoreShipMethId()); shippingEstimates.put(shipMethod, estimateMap.get("shippingTotal")); } } } /* * This method will use the UPS Rate Shop API to get estimates for all shipping methods. */ @SuppressWarnings("unchecked") protected void loadEstimatesUPS() { if (UtilValidate.isEmpty(this.shippingAddress)) { Debug.logInfo("Shipping Address in shopping cart is null", MODULE); return; } // Set up input map for upsRateEstimate Map input = UtilMisc.toMap("upsRateInquireMode", "Shop"); // triggers the mode of estimate we want input.put("shippableQuantity", this.shippableQuantity); input.put("shippableWeight", this.shippableWeight); input.put("productStoreId", this.productStoreId); input.put("carrierRoleTypeId", "CARRIER"); input.put("carrierPartyId", "UPS"); input.put("shippingContactMechId", this.shippingAddress.get("contactMechId")); if (this.shippingOriginAddress != null) { input.put("shippingOriginContactMechId", this.shippingOriginAddress.get("contactMechId")); } input.put("shippableItemInfo", this.shippableItemInfo); input.put("shipmentMethodTypeId", "XXX"); // Dummy value for required field that isn't necessary for rate shop requests input.put("shippableTotal", this.shippableTotal); try { // Results are the estimated amounts keyed to the carrierServiceCode Map results = GenericDispatcher.getLocalDispatcher(this.dispatcherName, this.cart.getDelegator()).runSync("upsRateEstimate", input); if (ServiceUtil.isError(results) || ServiceUtil.isFailure(results)) { Debug.logError(ServiceUtil.getErrorMessage(results), MODULE); return; } Map upsRateCodeMap = (Map) results.get("upsRateCodeMap"); // Populate the available UPS service codes for the wrapper with the codes returned availableCarrierServices.put("UPS", UtilMisc.toList(upsRateCodeMap.keySet())); // These are shipping methods which would have used upsRateEstimate, so we can populate them with the results from rate shop. // This is in case there are some UPS shipping methods which do not use the upsRateEstimate but use rate table, etc. List relevantShippingMethods = EntityUtil.filterByAnd(shippingMethods, UtilMisc.toMap("serviceName", "upsRateEstimate")); // Key each ProductStoreShipmentMethAndCarrier to the amount for the corresponding shipment method for (Iterator iter = relevantShippingMethods.iterator(); iter.hasNext();) { GenericValue m = (GenericValue) iter.next(); String carrierServiceCode = m.getString("carrierServiceCode"); // Skip if there's no service code or if the service isn't available if (UtilValidate.isEmpty(carrierServiceCode)) { continue; } if (!upsRateCodeMap.containsKey(carrierServiceCode)) { continue; } - Double amount = (Double) upsRateCodeMap.get(carrierServiceCode); + BigDecimal amount = (BigDecimal) upsRateCodeMap.get(carrierServiceCode); shippingEstimates.put(m, amount); } } catch (GenericServiceException e) { Debug.logError(e, MODULE); } } @SuppressWarnings("unchecked") protected void addCodSurchargesToEstimates() { if (cart != null && cart instanceof OpentapsShoppingCart && shippingEstimates != null) { OpentapsShoppingCart opentapsCart = (OpentapsShoppingCart) cart; if (opentapsCart.getCOD(shipGroupSeqId)) { Iterator eit = shippingEstimates.keySet().iterator(); while (eit.hasNext()) { GenericValue carrierShipmentMethod = (GenericValue) eit.next(); - Double codSurcharge = carrierShipmentMethod.getDouble("codSurcharge"); - Double estimate = (Double) shippingEstimates.get(carrierShipmentMethod); + BigDecimal codSurcharge = carrierShipmentMethod.getBigDecimal("codSurcharge"); + BigDecimal estimate = (BigDecimal) shippingEstimates.get(carrierShipmentMethod); if (UtilValidate.isNotEmpty(estimate) && UtilValidate.isNotEmpty(codSurcharge)) { - shippingEstimates.put(carrierShipmentMethod, new Double(estimate.doubleValue() + codSurcharge.doubleValue())); + shippingEstimates.put(carrierShipmentMethod, estimate.add(codSurcharge)); } } } } } @SuppressWarnings("unchecked") public List getShippingMethods() { return shippingMethods; } @SuppressWarnings("unchecked") public Map getAllEstimates() { return shippingEstimates; } - public Double getShippingEstimate(String shipmentMethodTypeId, String carrierPartyId) { + public BigDecimal getShippingEstimate(String shipmentMethodTypeId, String carrierPartyId) { GenericValue storeCarrierShipMethod = EntityUtil.getFirst(EntityUtil.filterByAnd(shippingMethods, UtilMisc.toMap("shipmentMethodTypeId", shipmentMethodTypeId, "partyId", carrierPartyId))); if (UtilValidate.isEmpty(storeCarrierShipMethod)) { return null; } BigDecimal est = (BigDecimal) shippingEstimates.get(storeCarrierShipMethod); if (UtilValidate.isEmpty(est)) { return null; } - BigDecimal estBd = new BigDecimal(est.doubleValue()).setScale(DECIMALS, ROUNDING); - return new Double(estBd.doubleValue()); + BigDecimal estBd = est.setScale(DECIMALS, ROUNDING); + return estBd; } - public Double getShippingEstimate(GenericValue storeCarrierShipMethod) { + public BigDecimal getShippingEstimate(GenericValue storeCarrierShipMethod) { if (UtilValidate.isEmpty(storeCarrierShipMethod)) { return null; } return getShippingEstimate(storeCarrierShipMethod.getString("shipmentMethodTypeId"), storeCarrierShipMethod.getString("partyId")); } public void setShippingAddress(GenericValue shippingAddress) { this.shippingAddress = shippingAddress; loadShippingMethods(); loadEstimates(); } public GenericValue getShippingAddress() { return this.shippingAddress; } }
false
false
null
null
diff --git a/src/edu/isi/pegasus/planner/parser/dax/DAXParser3.java b/src/edu/isi/pegasus/planner/parser/dax/DAXParser3.java index 5e60f6861..a75f2b61c 100644 --- a/src/edu/isi/pegasus/planner/parser/dax/DAXParser3.java +++ b/src/edu/isi/pegasus/planner/parser/dax/DAXParser3.java @@ -1,1353 +1,1353 @@ /* * * Copyright 2007-2008 University Of Southern California * * 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 edu.isi.pegasus.planner.parser.dax; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; - import org.xml.sax.SAXException; import edu.isi.pegasus.common.logging.LogManager; import edu.isi.pegasus.common.logging.LogManagerFactory; import edu.isi.pegasus.common.util.CondorVersion; import edu.isi.pegasus.common.util.Separator; import edu.isi.pegasus.common.util.Version; import edu.isi.pegasus.planner.catalog.classes.SysInfo; import edu.isi.pegasus.planner.catalog.site.classes.GridGateway; import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry; import edu.isi.pegasus.planner.catalog.transformation.classes.TCType; +import edu.isi.pegasus.planner.catalog.transformation.impl.Abstract; import edu.isi.pegasus.planner.classes.CompoundTransformation; import edu.isi.pegasus.planner.classes.DAGJob; import edu.isi.pegasus.planner.classes.DAXJob; import edu.isi.pegasus.planner.classes.Job; +import edu.isi.pegasus.planner.classes.Notifications; import edu.isi.pegasus.planner.classes.PCRelation; import edu.isi.pegasus.planner.classes.PegasusBag; import edu.isi.pegasus.planner.classes.PegasusFile; import edu.isi.pegasus.planner.classes.Profile; import edu.isi.pegasus.planner.classes.ReplicaLocation; import edu.isi.pegasus.planner.classes.PegasusFile.LINKAGE; -import edu.isi.pegasus.planner.classes.Notifications; import edu.isi.pegasus.planner.code.GridStartFactory; import edu.isi.pegasus.planner.dax.Executable; import edu.isi.pegasus.planner.dax.Invoke; import edu.isi.pegasus.planner.dax.MetaData; import edu.isi.pegasus.planner.dax.PFN; import edu.isi.pegasus.planner.dax.Executable.ARCH; import edu.isi.pegasus.planner.dax.Executable.OS; import edu.isi.pegasus.planner.dax.Invoke.WHEN; import edu.isi.pegasus.planner.namespace.Hints; import edu.isi.pegasus.planner.namespace.Pegasus; import edu.isi.pegasus.planner.parser.StackBasedXMLParser; /** * This class uses the Xerces SAX2 parser to validate and parse an XML * document conforming to the DAX Schema 3.2 * * @author Karan Vahi [email protected] * @version $Revision$ */ public class DAXParser3 extends StackBasedXMLParser implements DAXParser { /** * The "not-so-official" location URL of the Site Catalog Schema. */ public static final String SCHEMA_LOCATION = "http://pegasus.isi.edu/schema/dax-3.3.xsd"; /** * uri namespace */ public static final String SCHEMA_NAMESPACE = "http://pegasus.isi.edu/schema/DAX"; /** * Constant denoting an undefined site */ public static final String UNDEFINED_SITE = "undefined"; /* * Predefined Constant for dax version 3.2.0 */ public static final long DAX_VERSION_3_2_0 = CondorVersion.numericValue( "3.2.0" ); /* * Predefined Constant for dax version 3.2.0 */ public static final long DAX_VERSION_3_3_0 = CondorVersion.numericValue( "3.3.0" ); /** * Constant denoting default metadata type */ private String DEFAULT_METADATA_TYPE = "String"; /** * List of parents for a child node in the graph */ protected List<PCRelation> mParents; /** * Handle to the callback */ protected Callback mCallback; /** * A job prefix specifed at command line. */ protected String mJobPrefix; /** * The overloaded constructor. * * @param properties the <code>PegasusProperties</code> to be used. */ public DAXParser3( PegasusBag bag ) { super( bag ); mJobPrefix = ( bag.getPlannerOptions() == null ) ? null: bag.getPlannerOptions().getJobnamePrefix(); } /** * Set the DAXCallback for the parser to call out to. * * @param c the callback */ public void setDAXCallback( Callback c ){ this.mCallback = c; } /** * Retuns the DAXCallback for the parser * * @return the callback */ public Callback getDAXCallback( ){ return this.mCallback; } /** * The main method that starts the parsing. * * @param file the XML file to be parsed. */ public void startParser( String file ) { try { this.testForFile( file ); mParser.parse( file ); //sanity check if ( mDepth != 0 ){ throw new RuntimeException( "Invalid stack depth at end of parsing " + mDepth ); } } catch ( IOException ioe ) { mLogger.log( "IO Error :" + ioe.getMessage(), LogManager.ERROR_MESSAGE_LEVEL ); } catch ( SAXException se ) { if ( mLocator != null ) { mLogger.log( "Error in " + mLocator.getSystemId() + " at line " + mLocator.getLineNumber() + " at column " + mLocator.getColumnNumber() + " :" + se.getMessage() , LogManager.ERROR_MESSAGE_LEVEL); } } } /** * Returns the XML schema namespace that a document being parsed conforms * to. * * @return the schema namespace */ public String getSchemaNamespace( ){ return DAXParser3.SCHEMA_NAMESPACE; } /** * Returns the local path to the XML schema against which to validate. * * @return path to the schema */ public String getSchemaLocation() { // treat URI as File, yes, I know - I need the basename File uri = new File( DAXParser3.SCHEMA_LOCATION ); // create a pointer to the default local position File dax = new File( this.mProps.getSysConfDir(), uri.getName() ); return this.mProps.getDAXSchemaLocation( dax.getAbsolutePath() ); } /** * Composes the <code>SiteData</code> object corresponding to the element * name in the XML document. * * @param element the element name encountered while parsing. * @param names is a list of attribute names, as strings. * @param values is a list of attribute values, to match the key list. * * @return the relevant SiteData object, else null if unable to construct. * * @exception IllegalArgumentException if the element name is too short. */ public Object createObject( String element, List names, List values ){ if ( element == null || element.length() < 1 ){ throw new IllegalArgumentException("illegal element length"); } switch ( element.charAt(0) ) { // a adag argument case 'a': if ( element.equals( "adag" ) ) { //for now the adag element is just a map of //key value pair Map<String,String> m = new HashMap(); for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); m.put( name, value ); } sanityCheckOnVersion( m.get( "version" ) ); //put the call to the callback this.mCallback.cbDocument( m ); return m; }//end of element adag else if( element.equals( "argument" ) ){ return new Arguments(); } return null; //c child compound case 'c': if( element.equals( "child") ){ this.mParents = new LinkedList<PCRelation>(); PCRelation pc = new PCRelation(); String child = null; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "ref" ) ) { child = value; } } if( child == null ){ this.complain( element, "child", child ); return null; } pc.setChild( child ); return pc; } else if ( element.equals( "compound") ){ } return null; //d dag dax case 'd': if( element.equals( "dag" ) || element.equals( "dax" ) ){ Job j = new Job( ); //all jobs in the DAX are of type compute j.setUniverse( GridGateway.JOB_TYPE.compute.toString() ); j.setJobType( Job.COMPUTE_JOB ); String file = null; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "namespace" ) ) { j.setTXNamespace( value ); } else if( name.equals( "name" ) ){ j.setTXName( value ); } else if( name.equals( "version" ) ){ j.setTXVersion( value ); } else if( name.equals( "id" ) ){ j.setLogicalID( value ); } else if( name.equals( "file" ) ){ file = value; } else if( name.equals( "node-label" ) ){ this.attributeNotSupported( element, name, value ); } else { this.complain( element, name, value ); } } if( file == null ){ this.complain( element, "file", file ); return null; } PegasusFile pf = new PegasusFile( file ); pf.setLinkage( LINKAGE.INPUT ); if( element.equals( "dag" ) ){ DAGJob dagJob = new DAGJob( j ); dagJob.setDAGLFN( file ); dagJob.addInputFile( pf ); //the job should always execute on local site //for time being dagJob.hints.construct(Hints.EXECUTION_POOL_KEY, "local"); //also set the executable to be used dagJob.hints.construct(Hints.PFN_HINT_KEY, "/opt/condor/bin/condor-dagman"); //add default name and namespace information dagJob.setTransformation("condor", "dagman", null); dagJob.setDerivation("condor", "dagman", null); dagJob.level = -1; //dagman jobs are always launched without a gridstart dagJob.vdsNS.construct(Pegasus.GRIDSTART_KEY, GridStartFactory.GRIDSTART_SHORT_NAMES[GridStartFactory.NO_GRIDSTART_INDEX]); //set the internal primary id for job //dagJob.setName( constructJobID( dagJob ) ); dagJob.setName( dagJob.generateName( this.mJobPrefix) ); return dagJob; } else if (element.equals( "dax" ) ){ DAXJob daxJob = new DAXJob( j ); //the job should be tagged type pegasus daxJob.setTypeRecursive(); //the job should always execute on local site //for time being daxJob.hints.construct( Hints.EXECUTION_POOL_KEY, "local" ); //also set a fake executable to be used daxJob.hints.construct( Hints.PFN_HINT_KEY, "/tmp/pegasus-plan" ); //retrieve the extra attribute about the DAX daxJob.setDAXLFN( file ); daxJob.addInputFile( pf ); //add default name and namespace information daxJob.setTransformation( "pegasus", "pegasus-plan", Version.instance().toString() ); daxJob.setDerivation( "pegasus", "pegasus-plan", Version.instance().toString() ); daxJob.level = -1; //set the internal primary id for job //daxJob.setName( constructJobID( daxJob ) ); daxJob.setName( daxJob.generateName( this.mJobPrefix) ); return daxJob; } }//end of element job return null;//end of j //e executable case 'e': if( element.equals( "executable" ) ){ String namespace = null; String execName = null; String version = null; ARCH arch = null; OS os = null; String os_release = null; String os_version = null; String os_glibc = null; Boolean os_installed = true; // Default is installed for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "namespace" ) ) { namespace = value; } else if( name.equals( "name" ) ){ execName = value; } else if( name.equals( "version" ) ){ version = value; } else if( name.equals( "arch" ) ){ arch = Executable.ARCH.valueOf( value.toLowerCase() ); } else if( name.equals( "os" ) ){ os = Executable.OS.valueOf( value.toLowerCase() ); } else if( name.equals( "osrelease" ) ){ os_release = value; } else if( name.equals( "osversion" ) ){ os_version =value; } else if( name.equals( "glibc" ) ){ os_glibc = value; } else if( name.equals( "installed" ) ){ os_installed = Boolean.parseBoolean( value ); } } Executable executable = new Executable( namespace , execName ,version); executable.setArchitecture(arch); executable.setOS(os); executable.setOSRelease(os_release); executable.setOSVersion(os_version); executable.setGlibc(os_glibc); executable.setInstalled(os_installed); return executable; }//end of element executable return null; //end of e //f file case 'f': if( element.equals( "file" ) ){ //create a FileTransfer Object or shd it be ReplicaLocations? //FileTransfer ft = new FileTransfer(); ReplicaLocation rl = new ReplicaLocation(); for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "name" ) ) { //ft.setLFN( value ); rl.setLFN( value ); } else if( name.equals( "link" ) ){ //ignore dont need to do anything } else if( name.equals( "optional" ) ){ Boolean optional = Boolean.parseBoolean( value ); if( optional ){ //replica location object does not handle //optional attribute right now. // ft.setFileOptional(); } } else { this.complain( element, name, value ); } } return rl; }//end of element file return null; //end of f //i invoke case 'i': if( element.equals( "invoke" ) ){ String when = null; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "when" ) ) { when = value; this.log( element, name, value ); } else { this.complain( element, name, value ); } } if( when == null ){ this.complain( element, "when", when ); return null; } return new Invoke( WHEN.valueOf( when ) ); }//end of element invoke return null; //j job case 'j': if( element.equals( "job" ) ){ Job j = new Job( ); //all jobs in the DAX are of type compute j.setUniverse( GridGateway.JOB_TYPE.compute.toString() ); j.setJobType( Job.COMPUTE_JOB ); for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "namespace" ) ) { j.setTXNamespace( value ); } else if( name.equals( "name" ) ){ j.setTXName( value ); } else if( name.equals( "version" ) ){ j.setTXVersion( value ); } else if( name.equals( "id" ) ){ j.setLogicalID( value ); } else if( name.equals( "node-label" ) ){ this.attributeNotSupported( element, name, value ); } else { this.complain( element, name, value ); } } //set the internal primary id for job j.setName( constructJobID( j ) ); return j; }//end of element job return null;//end of j //m metadata case 'm': if( element.equals( "metadata" ) ){ String key = null; String type = DEFAULT_METADATA_TYPE; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "key" ) ) { key = value; this.log( element, name, value ); } else if ( name.equals( "type" ) ) { type = value; this.log( element, name, value ); } else { this.complain( element, name, value ); } } if( key == null ){ this.complain( element, "key", key ); } MetaData md = new MetaData( key, type ); return md; }//end of element metadata return null;//end of case m //p parent profile pfn case 'p': if( element.equals( "parent" ) ){ String parent = null; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "ref" ) ) { parent = value; } else if( name.equals( "edge-label" ) ){ this.attributeNotSupported( "parent", "edge-label", value); } else { this.complain( element, name, value ); } } if( parent == null ){ this.complain( element, "parent", parent ); return null; } return parent; } else if( element.equals( "profile" ) ){ Profile p = new Profile(); for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "namespace" ) ) { p.setProfileNamespace( value.toLowerCase() ); this.log( element, name, value ); } else if ( name.equals( "key" ) ) { p.setProfileKey( value ); this.log( element, name, value ); } else { this.complain( element, name, value ); } } return p; }//end of element profile else if( element.equals( "pfn" ) ){ String url = null; String site = UNDEFINED_SITE; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "url" ) ) { url = value; this.log( element, name, value ); } else if ( name.equals( "site" ) ) { site = value; this.log( element, name, value ); } else { this.complain( element, name, value ); } } if( url == null ){ this.complain( element, "url", url ); return null; } PFN pfn = new PFN( url, site ); return pfn; }//end of element pfn return null;//end of case p //s stdin stdout stderr case 's': if( element.equals( "stdin" ) || element.equals( "stdout" ) || element.equals( "stderr") ){ //we use DAX API File object for this String fileName = null; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "name" ) ) { fileName = value; this.log( element, name, value ); } else if ( name.equals( "link" ) ) { //we ignore as linkage is fixed for stdout|stderr|stdin this.log( element, name, value ); } else { this.complain( element, name, value ); } } if( fileName == null ){ this.complain( element, "name", fileName ); return null; } return new edu.isi.pegasus.planner.dax.File( fileName ); }//end of stdin|stdout|stderr return null;//end of case s //t transformation case 't': if( element.equals( "transformation" ) ){ String namespace = null,lname = null, version = null; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); if ( name.equals( "namespace" ) ) { namespace = value; } else if( name.equals( "name" ) ){ lname = value; } else if( name.equals( "version" ) ){ version = value; } } return new CompoundTransformation( namespace, lname, version ); } return null; //u uses case 'u': if( element.equals( "uses" ) ){ PegasusFile pf = new PegasusFile( ); String fName = null; String fNamespace = null; String fVersion = null; for ( int i=0; i < names.size(); ++i ) { String name = (String) names.get( i ); String value = (String) values.get( i ); /* * Name Type Use Default Fixed name xs:string required link LinkageType optional optional xs:boolean optional false register xs:boolean optional true transfer TransferType optional true namespace xs:string optional version VersionPattern optional exectuable xs:boolean optional false */ if ( name.equals( "name" ) ) { pf.setLFN( value ); fName = value; this.log( element, name, value ); } else if ( name.equals( "link" ) ) { pf.setLinkage( PegasusFile.LINKAGE.valueOf( value.toUpperCase() ) ); this.log( element, name, value ); } else if ( name.equals( "optional" ) ) { Boolean bValue = Boolean.parseBoolean( value ); if( bValue ){ pf.setFileOptional(); } this.log( element, name, value ); } else if( name.equals( "register") ){ Boolean bValue = Boolean.parseBoolean( value ); pf.setRegisterFlag( bValue ); } else if ( name.equals( "transfer" ) ) { pf.setTransferFlag( value ); this.log( element, name, value ); } else if ( name.equals( "namespace" ) ) { fNamespace = value; this.log( element, name, value ); } else if ( name.equals( "version" ) ) { fVersion = value; this.log( element, name, value ); } else if ( name.equals( "executable" ) ) { Boolean bValue = Boolean.parseBoolean( value ); if( bValue ){ pf.setType( PegasusFile.EXECUTABLE_FILE ); } this.log( element, name, value ); } else if ( name.equals( "size" ) ) { pf.setSize( value ); this.log( element, name, value ); } else { this.complain( element, name, value ); } } //if executable then update lfn to combo of namespace,name,version if( pf.getType() == PegasusFile.EXECUTABLE_FILE ){ pf.setLFN( Separator.combine(fNamespace, fName, fVersion) ); } return pf; }//end of uses return null;//end of case u default: return null; }//end of switch statement } /** * This method sets the relations between the currently finished XML * element(child) and its containing element in terms of Java objects. * Usually it involves adding the object to the parent's child object * list. * * @param childElement name is the the child element name * @param parent is a reference to the parent's Java object * @param child is the completed child object to connect to the parent * * @return true if the element was added successfully, false, if the * child does not match into the parent. */ public boolean setElementRelation( String childElement, Object parent, Object child ){ switch ( childElement.charAt( 0 ) ) { //a argument adag case 'a': if( child instanceof Arguments ){ Arguments a = (Arguments)child; a.addArgument( mTextContent.toString() ); if( parent instanceof Job ){ //argument appears in job element Job j = (Job)parent; j.setArguments( a.toString() ); return true; } } else if( child instanceof Map && parent == null){ //end of parsing reached mLogger.log( "End of last element </adag> reached ", LogManager.DEBUG_MESSAGE_LEVEL ); this.mCallback.cbDone(); return true; } return false; //c child case 'c': if( parent instanceof Map ){ if( child instanceof PCRelation ){ PCRelation pc = (PCRelation)child; //call the callback this.mCallback.cbParents( pc.getChild(), mParents); return true; } } return false; //d dax dag case 'd': if( parent instanceof Map ){ if( child instanceof DAGJob ){ //dag appears in adag element DAGJob dagJob = ( DAGJob )child; //call the callback function this.mCallback.cbJob(dagJob); return true; } else if( child instanceof DAXJob ){ //dag appears in adag element DAXJob daxJob = ( DAXJob )child; //call the callback function this.mCallback.cbJob( daxJob ); return true; } } return false; //f file case 'f': if( child instanceof ReplicaLocation ){ ReplicaLocation rl = ( ReplicaLocation )child; if( parent instanceof Map ){ //file appears in adag element // this.mReplicaStore.add( rl ); this.mCallback.cbFile( rl ); return true; } else if( parent instanceof Arguments ){ //file appears in the argument element Arguments a = (Arguments)parent; a.addArgument( mTextContent.toString() ); a.addArgument( rl ); return true; } } return false; //e executable case 'e': if( child instanceof Executable ){ if( parent instanceof Map ){ //executable appears in adag element Executable exec = (Executable)child; List<TransformationCatalogEntry> tceList = convertExecutableToTCE(exec); for(TransformationCatalogEntry tce : tceList){ - this.mCallback.cbExecutable(tce); + this.mCallback.cbExecutable(Abstract.modifyForFileURLS(tce)); } //moved the callback call to end of pfn //each new pfn is a new transformation //catalog entry //this.mCallback.cbExecutable( tce ); return true; } } return false; //i invoke case 'i': if( child instanceof Invoke ){ Invoke i = (Invoke)child; i.setWhat( mTextContent.toString().trim() ); if( parent instanceof Map ){ this.mCallback.cbWfInvoke(i); return true; } else if(parent instanceof DAXJob ){ //invoke appears in dax element DAXJob daxJob = (DAXJob)parent; daxJob.addNotification(i); return true; }else if(parent instanceof DAGJob ){ //invoke appears in dag element DAGJob dagJob = (DAGJob)parent; dagJob.addNotification(i); return true; }else if( parent instanceof Job ){ //invoke appears in job element Job job = (Job)parent; job.addNotification(i); return true; }else if(parent instanceof Executable ){ //invoke appears in executable element Executable exec = (Executable)parent; exec.addInvoke(i); return true; }else if(parent instanceof CompoundTransformation ){ //invoke appears in transformation element CompoundTransformation ct = (CompoundTransformation)parent; ct.addNotification(i); return true; } } return false; //j job case 'j': if( child instanceof Job && parent instanceof Map ){ //callback for Job this.mCallback.cbJob( (Job)child ); return true; } return false; //m metadata case 'm': if ( child instanceof MetaData ) { MetaData md = ( MetaData )child; md.setValue( mTextContent.toString().trim() ); //metadata appears in file element if( parent instanceof ReplicaLocation ){ unSupportedNestingOfElements( "file", "metadata" ); return true; } //metadata appears in executable element if( parent instanceof Executable ){ unSupportedNestingOfElements( "executable", "metadata" ); return true; } } return false; //p parent profile pfn case 'p': if( parent instanceof PCRelation ){ if( child instanceof String ){ //parent appears in child element String parentNode = ( String )child; PCRelation pc = (PCRelation) (( PCRelation )parent).clone(); pc.setParent( parentNode ); mParents.add( pc ); return true; } } else if ( child instanceof Profile ){ Profile p = ( Profile ) child; p.setProfileValue( mTextContent.toString().trim() ); mLogger.log( "Set Profile Value to " + p.getProfileValue(), LogManager.TRACE_MESSAGE_LEVEL ); if ( parent instanceof ReplicaLocation ) { //profile appears in file element unSupportedNestingOfElements( "file", "profile" ); return true; } else if ( parent instanceof Executable ) { //profile appears in executable element Executable exec = ( Executable)parent; exec.addProfiles(new edu.isi.pegasus.planner.dax.Profile(p.getProfileNamespace(),p.getProfileKey(),p.getProfileValue())); return true; } else if ( parent instanceof Job ){ //profile appears in the job element Job j = (Job)parent; j.addProfile( p ); return true; } } else if( child instanceof PFN ){ if ( parent instanceof ReplicaLocation ) { //pfn appears in file element ReplicaLocation rl = ( ReplicaLocation )parent; PFN pfn = ( PFN )child; rl.addPFN( pfn ); return true; } else if ( parent instanceof Executable){ //pfn appears in executable element Executable executable = (Executable)parent; PFN pfn = ( PFN )child; //tce.setResourceId( pfn.getSite() ); //tce.setPhysicalTransformation( pfn.getURL() ); executable.addPhysicalFile(pfn); //convert file url appropriately for installed executables //before returning //this.mCallback.cbExecutable( Abstract.modifyForFileURLS(tce) ); return true; } } return false; //s stdin stdout stderr case 's': if( parent instanceof Job ){ Job j = ( Job )parent; if( child instanceof edu.isi.pegasus.planner.dax.File ){ //stdin stdout stderr appear in job element edu.isi.pegasus.planner.dax.File f = ( edu.isi.pegasus.planner.dax.File )child; if( childElement.equals( "stdin" ) ){ j.setStdIn( f.getName() ); return true; } else if( childElement.equals( "stdout" ) ){ j.setStdOut( f.getName() ); return true; } if( childElement.equals( "stderr" ) ){ j.setStdErr( f.getName() ); return true; } } } return false; //t transformation case 't': if( parent instanceof Map ){ if( child instanceof CompoundTransformation ){ this.mCallback.cbCompoundTransformation( (CompoundTransformation)child ); return true; } return true; } return false; //u uses case 'u': if( child instanceof PegasusFile ){ PegasusFile pf = ( PegasusFile )child; if( parent instanceof Job ){ //uses appears in job Job j = ( Job )parent; if( pf.getLinkage().equals( LINKAGE.INPUT ) ){ j.addInputFile(pf); } else if( pf.getLinkage().equals( LINKAGE.OUTPUT ) ){ j.addOutputFile(pf); } else if( pf.getLinkage().equals( LINKAGE.INOUT ) ){ j.addInputFile(pf); j.addOutputFile(pf); } return true; } else if( parent instanceof CompoundTransformation ){ CompoundTransformation compound = (CompoundTransformation)parent; compound.addDependantFile( pf ); return true; } } return false; //default case default: return false; } } /** * Converts the executable into transformation catalog entries * @param executable executable object * @return transformation catalog entries */ public List<TransformationCatalogEntry> convertExecutableToTCE(Executable executable){ List<TransformationCatalogEntry> tceList = new ArrayList <TransformationCatalogEntry> (); TransformationCatalogEntry tce = null; for(PFN pfn : executable.getPhysicalFiles()){ tce = new TransformationCatalogEntry(executable.getNamespace(), executable.getName(), executable.getVersion()); SysInfo sysinfo = new SysInfo(); sysinfo.setArchitecture( SysInfo.Architecture.valueOf( executable.getArchitecture().toString().toLowerCase() ) ); sysinfo.setOS( SysInfo.OS.valueOf( executable.getOS().toString().toUpperCase() ) ); sysinfo.setOSRelease( executable.getOsRelease() ); sysinfo.setOSVersion( executable.getOsVersion() ); sysinfo.setGlibc( executable.getGlibc() ); tce.setSysInfo(sysinfo); tce.setType( executable.getInstalled() ? TCType.INSTALLED : TCType.STAGEABLE ); tce.setResourceId( pfn.getSite() ); tce.setPhysicalTransformation( pfn.getURL() ); Notifications notifications = new Notifications(); for(Invoke invoke : executable.getInvoke()){ notifications.add( new Invoke(invoke) ); } tce.addNotifications(notifications); for(edu.isi.pegasus.planner.dax.Profile profile : executable.getProfiles()){ tce.addProfile(new edu.isi.pegasus.planner.classes.Profile(profile.getNameSpace(),profile.getKey() , profile.getValue())); } tceList.add(tce); } return tceList; } /** * Returns the id for a job * * @param j the job * * @return the id. */ protected String constructJobID( Job j ){ //construct the jobname/primary key for job StringBuffer name = new StringBuffer(); //prepend a job prefix to job if required if (mJobPrefix != null) { name.append(mJobPrefix); } //append the name and id recevied from dax name.append(j.getTXName()); name.append("_"); name.append(j.getLogicalID()); return name.toString(); } /** * Sanity check on the version that this parser works on. * * @param version the version as specified in the DAX */ protected void sanityCheckOnVersion( String version ) { if( version == null ){ mLogger.log( "Version not specified in the adag element " , LogManager.WARNING_MESSAGE_LEVEL ); return ; } //add a 0 suffix String nversion = version + ".0"; if( CondorVersion.numericValue( nversion) < DAXParser3.DAX_VERSION_3_2_0 ){ StringBuffer sb = new StringBuffer(); sb.append( "DAXParser3 Unsupported DAX Version " ).append( version ). append( ". Set pegasus.schema.dax property to load the old DAXParser" ); throw new RuntimeException( sb.toString() ); } return; } /** * Private class to handle mix data content for arguments tags. * */ private class Arguments{ /** * Handle to a job arguments to handle mixed content. */ protected StringBuffer mBuffer; /** * The default constructor */ public Arguments(){ reset(); } /** * Resets the internal buffer */ public void reset() { mBuffer = new StringBuffer(); } /** * Adds text to the arguments string * * @param text the text to be added. */ public void addArgument( String text ){ mBuffer.append( text ); } /** * Adds filename to the arguments * * @param rl the ReplicaLocation object */ public void addArgument(ReplicaLocation rl) { mBuffer.append( " " ).append( rl.getLFN() ).append( " "); } /** * Adds a file name to the argument string * * @param file the file object. */ private void addArgument( edu.isi.pegasus.planner.dax.File file ){ mBuffer.append( " " ).append( file.getName() ).append( " " ); } /** * Our own implementation for ignorable whitespace. A String that holds the * contents of data passed as text by the underlying parser. The whitespaces * at the end are replaced by one whitespace. * * @param str The string that contains whitespaces. * * @return String corresponding to the trimmed version. * */ public String ignoreWhitespace(String str) { return ignoreWhitespace(str, mProps.preserveParserLineBreaks()); } /** * Our own implementation for ignorable whitespace. A String that holds the * contents of data passed as text by the underlying parser. The whitespaces * at the end are replaced by one whitespace. * * @param str The string that contains whitespaces. * * @return String corresponding to the trimmed version. * */ public String ignoreWhitespace(String str, boolean preserveLineBreak ){ boolean st = false; boolean end = false; int length = str.length(); boolean sN = false;//start with \n ; boolean eN = false;//end with \n if(length > 0){ sN = str.charAt(0) == '\n'; eN = str.charAt(length -1) == '\n'; //check for whitespace in the //starting if(str.charAt(0) == ' ' || str.charAt(0) == '\t' || str.charAt(0) == '\n'){ st = true; } //check for whitespace in the end if(str.length() > 1 && (str.charAt(length -1) == ' ' || str.charAt(length -1) == '\t' || str.charAt(length -1) == '\n')){ end = true; } //trim the string and add a single whitespace accordingly str = str.trim(); str = st == true ? ' ' + str:str; str = end == true ? str + ' ':str; if( preserveLineBreak ){ str = sN ? '\n' + str:str; str = eN ? str + '\n':str; } } return str; } /** * Returns the arguments as string * * @return the arguments */ public String toString(){ return this.ignoreWhitespace( mBuffer.toString() ); } } /** * * @param args */ public static void main( String[] args ){ LogManagerFactory.loadSingletonInstance().setLevel( 5 ); /*DAXParser3 parser = new DAXParser3( ); if (args.length == 1) { parser.startParser( args[0] ); } else { System.out.println("Usage: SiteCatalogParser <input site catalog xml file>"); }*/ } }
false
false
null
null
diff --git a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/i18n/Translations.java b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/i18n/Translations.java index 3ebb37f96..8278e14c6 100644 --- a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/i18n/Translations.java +++ b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/i18n/Translations.java @@ -1,476 +1,478 @@ /******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.web.gwt.app.client.i18n; import java.util.Map; import com.google.gwt.i18n.client.Constants; import com.google.gwt.i18n.client.LocalizableResource.Generate; import com.google.gwt.i18n.client.LocalizableResource.GenerateKeys; /** * Programmatically available localised text strings. This interface will be bound to localised properties files found * in the {@code com.google.gwt.i18n.client} package. */ @GenerateKeys @Generate(format = "com.google.gwt.i18n.rebind.format.PropertiesFormat", locales = { "default" }) public interface Translations extends Constants { @Description("Error dialog title") @DefaultStringValue("Errors") String errorDialogTitle(); @Description("Error dialog title when used to display warnings") @DefaultStringValue("Warnings") String warningDialogTitle(); @Description("Error dialog title when used to display information") @DefaultStringValue("Information") String infoDialogTitle(); @Description("Name label") @DefaultStringValue("Name") String nameLabel(); @Description("Value Type label") @DefaultStringValue("Value Type") String valueTypeLabel(); @Description("Label label") @DefaultStringValue("Label") String labelLabel(); @Description("ID label") @DefaultStringValue("ID") String idLabel(); @Description("Type label") @DefaultStringValue("Type") String typeLabel(); @Description("User label") @DefaultStringValue("User") String userLabel(); @Description("Start label") @DefaultStringValue("Start") String startLabel(); @Description("End label") @DefaultStringValue("End") String endLabel(); @Description("Status label") @DefaultStringValue("Status") String statusLabel(); @Description("Status map") @DefaultStringMapValue({ "NOT_STARTED", "Not Started", // "IN_PROGRESS", "In Progress", // "SUCCEEDED", "Succeeded", // "FAILED", "Failed", // "CANCEL_PENDING", "Cancel Pending", // "CANCELED", "Cancelled", // "DatasourceCreationFailed", "The datasource creation has failed." }) Map<String, String> statusMap(); @Description("Actions label") @DefaultStringValue("Actions") String actionsLabel(); @Description("Action map") @DefaultStringMapValue({ "Log", "Log", // "Cancel", "Cancel", // "Delete", "Delete", // "Edit", "Edit", // "Download", "Download" }) Map<String, String> actionMap(); @Description("Size label") @DefaultStringValue("Size") String sizeLabel(); @Description("Last modified label") @DefaultStringValue("Last Modified") String lastModifiedLabel(); @Description("Date label") @DefaultStringValue("Date") String dateLabel(); @Description("Message label") @DefaultStringValue("Message") String messageLabel(); @Description("Job label") @DefaultStringValue("Job") String jobLabel(); @Description("Jobs menu item") @DefaultStringValue("Jobs") String jobsLabel(); @Description("File system label") @DefaultStringValue("File System") String fileSystemLabel(); @Description("Entity type label") @DefaultStringValue("Entity Type") String entityTypeLabel(); @Description("Tables label") @DefaultStringValue("Tables") String tablesLabel(); @Description("Table label") @DefaultStringValue("Table") String tableLabel(); @Description("Variables label") @DefaultStringValue("Variables") String variablesLabel(); @Description("Variable label") @DefaultStringValue("Variable") String variableLabel(); @Description("Unit label") @DefaultStringValue("Unit") String unitLabel(); @Description("User message map") @DefaultStringMapValue({ // "CategoryDialogNameRequired", "A category name is required.", // "CategoryNameAlreadyExists", "The specified category name already exists.", // "AttributeNameRequired", "An attribute name is required.", // "AttributeNameAlreadyExists", "The specified attribute name already exists.", // "BaseLanguageLabelRequired", "The base language field (marked with *) requires a value.", // "jobCancelled", "Job cancelled.", // "jobDeleted", "Job deleted.", // "completedJobsDeleted", "All completed jobs deleted.", // "SetCommandStatus_NotFound", "Job could not be cancelled (not found).", // "SetCommandStatus_BadRequest_IllegalStatus", "Job status cannot be set to the specified value.", // "SetCommandStatus_BadRequest_NotCancellable", "Job has completed and has already been cancelled.", // "DeleteCommand_NotFound", "Job could not be deleted (not found).", // "DeleteCommand_BadRequest_NotDeletable", "Job is currently running and therefore cannot be deleted at this time.", // "cannotCreateFolderPathAlreadyExist", "Could not create the folder, a folder or a file exist with that name at the specified path.", // "cannotCreateFolderParentIsReadOnly", "Could create the following folder because its parent folder is read-only.", // "cannotCreatefolderUnexpectedError", "There was an unexpected error while creating the folder.", // "cannotDeleteNotEmptyFolder", "This folder contains one or many file(s) and as a result cannot be deleted.", // "cannotDeleteReadOnlyFile", "Could delete the file or folder because it is read-only.", // "couldNotDeleteFileError", "There was an error while deleting the file or folder.", // "datasourceMustBeSelected", "You must select a datasource.", // "fileReadError", "The file could not be read.", // "ViewNameRequired", "You must provide a name for the view.", // "TableSelectionRequired", "You must select at least one table.", // "TableEntityTypesDoNotMatch", "The selected tables must all have the same entity type.", // "VariableDefinitionMethodRequired", "You must indicate how the view's variables are to be defined.", // "DatasourceNameRequired", "You must provide a name for the datasource.", // "DatasourceAlreadyExistsWithThisName", "A datasource already exists with this name.", // "ExcelFileRequired", "An Excel file is required.", "ExcelFileSuffixInvalid", // "Invalid Excel file suffix: .xls or .xlsx are expected.", // "ViewMustBeAttachedToExistingOrNewDatasource", "The view must be attached to either an existing datasource or a new one.", // "DuplicateDatasourceName", "The datasource name is already in use. Please choose another.", // "UnknownError", "An unknown error has occurred.", // "InternalError", "An internal error has occurred. Please contact technical support.", // "DatasourceNameDisallowedChars", "Datasource names cannot contain colon or period characters.", // "ViewNameDisallowedChars", "View names cannot contain colon or period characters.", // "XMLFileRequired", "An XML file is required.", // "XMLFileSuffixInvalid", "Invalid XML file suffix: .xml is expected.", // "ZipFileRequired", "An Zip file is required.", // "ZipFileSuffixInvalid", "Invalid Zip file suffix: .zip is expected.",// "ReportTemplateWasNotFound", "The specified report template could not be found.",// "ReportJobStarted", "Report job has been launched. You can follow its progress in the job list.",// "ReportTemplateAlreadyExistForTheSpecifiedName", "A report template already exist with the specified name.",// "BirtReportDesignFileIsRequired", "A BIRT Design File must be selected.",// "CronExpressionIsRequired", "A schedule expression must be specified when the Schedule checkbox is selected.",// "NotificationEmailsAreInvalid", "One or more of the notifications emails specified are invalid.",// "ReportTemplateNameIsRequired", "A name is required for the report template.",// - "OccurrenceGroupIsRequired", "An Occurence Group must be specified for Repeatable variables." }) + "OccurrenceGroupIsRequired", "An Occurence Group must be specified for Repeatable variables.",// + "NewVariableNameIsRequired", "A name is required for the new variable to be created.",// + "CopyFromVariableNameIsRequired", "You must enter the name of a variable from which the new variable will be created from." }) Map<String, String> userMessageMap(); @Description("You must select a file message") @DefaultStringValue("You must select a file.") String fileMustBeSelected(); @Description("Yes label") @DefaultStringValue("Yes") String yesLabel(); @Description("No label") @DefaultStringValue("No") String noLabel(); @Description("Missing label") @DefaultStringValue("Missing") String missingLabel(); @Description("Categories label") @DefaultStringValue("Categories") String categoriesLabel(); @Description("Attributes label") @DefaultStringValue("Attributes") String attributesLabel(); @Description("Language label") @DefaultStringValue("Language") String languageLabel(); @Description("Value label") @DefaultStringValue("Value") String valueLabel(); @Description("Code label") @DefaultStringValue("Code") String codeLabel(); @Description("Mime Type label") @DefaultStringValue("Mime Type") String mimeTypeLabel(); @Description("Repeatable label") @DefaultStringValue("Repeatable") String repeatableLabel(); @Description("Occurrence Group label") @DefaultStringValue("Occurrence Group") String occurrenceGroupLabel(); @Description("Multiple table selection instructions") @DefaultStringValue("Select one or more tables:") String multipleTableSelectionInstructionsLabel(); @Description("Single table selection instructions") @DefaultStringValue("Select one table:") String singleTableSelectionInstructionsLabel(); @Description("Datasource label") @DefaultStringValue("Datasource") String datasourceLabel(); @Description("Table selector title") @DefaultStringValue("Table selector") String tableSelectorTitle(); @Description("Select all label") @DefaultStringValue("select all") String selectAllLabel(); @Description("File Selector title") @DefaultStringValue("File Selector") String fileSelectorTitle(); @Description("Log label") @DefaultStringValue("Log") String logLabel(); @Description("Confirmation title map") @DefaultStringMapValue({ // "unsavedChangesTitle", "Unsaved Changes", // "deleteTable", "Delete Table", // "clearJobsList", "Clear Jobs List", // "cancelJob", "Cancel Job", // "replaceExistingFile", "Replace File", // "deleteFile", "Delete File", // "removeDatasource", "Remove Datasource",// "removeReportTemplate", "Remove Report Template" }) Map<String, String> confirmationTitleMap(); @Description("Confirmation message map") @DefaultStringMapValue({ // "confirmUnsavedChanges", "You have unsaved changes. Are you sure you want to move away from this tab?", // "removingTablesFromViewMayAffectVariables", "Removing tables from the view will have an impact on which Variables can be defined.", // "confirmClearJobsList", "All the completed jobs (succeeded, failed or cancelled) will be removed from the jobs list. Currently running jobs will be unaffected.<br /><br />Please confirm that you want to clear the jobs list.", // "confirmCancelJob", "The job will be cancelled. Changes will be rolled back as much as possible: although cancelled, a job might be partially completed.<br /><br />Please confirm that you want cancel this job.", // "confirmReplaceExistingFile", "The file that you are uploading already exist in the file system.<br /><br />Please confirm that you want to replace the existing file.", // "confirmDeleteFile", "The file will be removed from the file system.<br /><br />Please confirm that you want to delete this file.", // "confirmRemoveDatasource", "Please confirm that you want to remove the current datasource from Opal configuration (datasource content will not be affected).",// "confirmDeleteReportTemplate", "Please confirm that you want to remove the current Report Template from Opal configuration (report design and generated reports will not be affected)." }) Map<String, String> confirmationMessageMap(); @Description("A name is required when creating a new folder") @DefaultStringValue("You must specify a folder name") String folderNameIsRequired(); @Description("Dot names are not permitted") @DefaultStringValue("The names '.' and '..' are not permitted.") String dotNamesAreInvalid(); @Description("Data export instructions") @DefaultStringValue("Select the tables and the export destination.") String dataExportInstructions(); @Description("Data export instructions conclusion") @DefaultStringValue("Data export job is launched.") String dataExportInstructionsConclusion(); @Description("Data import instructions") @DefaultStringValue("Select the file to be imported and the destination datasource.") String dataImportInstructions(); @Description("Data import instructions conclusion") @DefaultStringValue("Data import job is launched.") String dataImportInstructionsConclusion(); @Description("Export to Excel icon title") @DefaultStringValue("Export to Excel file") String exportToExcelTitle(); @Description("Csv label") @DefaultStringValue("CSV") String csvLabel(); @Description("Opal XML label") @DefaultStringValue("Opal XML") String opalXmlLabel(); @Description("Row must be integer message") @DefaultStringValue("Row must be an integer.") String rowMustBeIntegerMessage(); @Description("Row must be positive message") @DefaultStringValue("Row must must be a positive value.") String rowMustBePositiveMessage(); @Description("Charset must not be null message") @DefaultStringValue("The character set must not be null or empty.") String charsetMustNotBeNullMessage(); @Description("Charset does not exist message") @DefaultStringValue("The specified character set could not be found.") String charsetDoesNotExistMessage(); @Description("Sheet label") @DefaultStringValue("Sheet") String sheetLabel(); @Description("Row number label") @DefaultStringValue("Row Number") String rowNumberLabel(); @Description("Error label") @DefaultStringValue("Error") String errorLabel(); @Description("Datasource parsing error map") @DefaultStringMapValue({ "CategoryNameRequired", "Category name required", // "CategoryVariableNameRequired", "Category variable name required", // "DuplicateCategoryName", "Duplicate category name", // "DuplicateColumns", "Duplicate columns", // "DuplicateVariableName", "Duplicate variable name", // "TableDefinitionErrors", "Table definition errors", // "UnexpectedErrorInCategory", "Unexpected error in category", // "UnexpectedErrorInVariable", "Unexpected error in variable", // "UnidentifiedVariableName", "Unidentified variable name", // "UnknownValueType", "Unknown value type", // "VariableCategoriesDefinitionErrors", "Variable categories definition errors", // "VariableNameCannotContainColon", "Variable name cannot contain colon", // "VariableNameRequired", "Variable name required", // "CsvInitialisationError", "Error occurred initialising csv datasource", // "CsvVariablesHeaderMustContainName", "The variables.csv header must contain 'name'", // "CsvVariablesHeaderMustContainValueType", "The variables.csv header must contain 'valueType'.", // "CsvVariablesHeaderMustContainEntityType", "The variables.csv header must contain 'entityType'.", // "CsvCannotCreateWriter", "Cannot create writer", // "CsvCannotSetVariableHeader", "Cannot set variables header", // "CsvCannotObtainWriter", "Can not get csv writer", // "CsvCannotObtainReader", "Can not get csv reader" }) Map<String, String> datasourceParsingErrorMap(); @Description("Datasource comparison error map") @DefaultStringMapValue({ "IncompatibleValueType", "Incompatible value type", // "IncompatibleEntityType", "Incompatible entity type", // "VariablePresentInSourceButNotDestination", "Variable exists in source but not in destination" }) Map<String, String> datasourceComparisonErrorMap(); @Description("New variables label") @DefaultStringValue("New Variables") String newVariablesLabel(); @Description("Modified variables label") @DefaultStringValue("Modified Variables") String modifiedVariablesLabel(); @Description("Conflicted variables label") @DefaultStringValue("Conflicts") String conflictedVariablesLabel(); @Description("No data available label") @DefaultStringValue("No data available") String noDataAvailableLabel(); @Description("Remove label") @DefaultStringValue("Remove") String removeLabel(); @Description("View label") @DefaultStringValue("View") String viewLabel(); @Description("Create Datasource Completed summary") @DefaultStringValue("The datasource was successfully created.") String datasourceCreationCompleted(); @Description("Create Datasource Failed summary") @DefaultStringValue("The datasource creation has failed.") String datasourceCreationFailed(); @Description("Item label") @DefaultStringValue("Item") String itemLabel(); @Description("Script label") @DefaultStringValue("Script") String scriptLabel(); @Description("Line label") @DefaultStringValue("Line") String lineLabel(); @Description("Add new category title") @DefaultStringValue("Add New Category") String addNewCategory(); @Description("Edit category title") @DefaultStringValue("Edit Category") String editCategory(); @Description("Add new attribute title") @DefaultStringValue("Add New Attribute") String addNewAttribute(); @Description("Edit attribute title") @DefaultStringValue("Edit Attribute") String editAttribute(); @Description("Report produced date") @DefaultStringValue("Produced Date") String producedDate(); @Description("Run label") @DefaultStringValue("Run") String runLabel(); @Description("Paging of label") @DefaultStringValue("of") String ofLabel(); @Description("Values label") @DefaultStringValue("Values") String valuesLabel(); @Description("Copy of label") @DefaultStringValue("Copy_of_") String copyOf(); @Description("Script contains errors and was not saved") @DefaultStringValue("The script contains errors and was not saved. Click 'Test' to execute the script and see a detailed report of the errors.") String scriptContainsErrorsAndWasNotSaved(); }
true
false
null
null
diff --git a/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseCompareButton.java b/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseCompareButton.java index af1e9c5..d8dc016 100644 --- a/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseCompareButton.java +++ b/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseCompareButton.java @@ -1,56 +1,56 @@ package nl.tue.fingerpaint.client.gui.buttons; import java.util.Set; import nl.tue.fingerpaint.client.gui.GuiState; import nl.tue.fingerpaint.client.resources.FingerpaintConstants; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.cellview.client.CellList; import com.google.gwt.user.client.ui.Button; import com.google.gwt.view.client.MultiSelectionModel; /** * Button that can be used to cancel the comparing. * * @author Group Fingerpaint */ public class CloseCompareButton extends Button implements ClickHandler { /** * SelectionModel of the {@link CellList} that is used to make a selection * of results to compare. Used to deselect items when this button is * clicked. */ protected final MultiSelectionModel<String> selectionModel; /** * Construct a new button that can be used to cancel comparing two results. * * @param selectionModel * SelectionModel of the {@link CellList} that is used to make a * selection of results to compare. Used to deselect items when * this button is clicked. */ public CloseCompareButton(final MultiSelectionModel<String> selectionModel) { - super(FingerpaintConstants.INSTANCE.btnCancel()); + super(FingerpaintConstants.INSTANCE.btnClose()); this.selectionModel = selectionModel; addClickHandler(this); ensureDebugId("closeCompareButton"); } /** * Unselects all selected items and hides the panel. * @param event The event that has fired. */ @Override public void onClick(ClickEvent event) { Set<String> selected = selectionModel.getSelectedSet(); for (String s : selected) { selectionModel.setSelected(s, false); } GuiState.comparePopupPanel.hide(); } } diff --git a/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseSaveButton.java b/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseSaveButton.java index b158a2d..8e94f38 100644 --- a/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseSaveButton.java +++ b/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/CloseSaveButton.java @@ -1,41 +1,41 @@ package nl.tue.fingerpaint.client.gui.buttons; import nl.tue.fingerpaint.client.gui.GuiState; import nl.tue.fingerpaint.client.resources.FingerpaintConstants; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; /** * Button that can be used to close the save results or overwrite pop-up panel. * * @author Group Fingerpaint */ public class CloseSaveButton extends Button implements ClickHandler { /** * Construct a new button that can be used to close the save results or * overwrite pop-up panel. */ public CloseSaveButton() { - super(FingerpaintConstants.INSTANCE.btnClose()); + super(FingerpaintConstants.INSTANCE.btnCancel()); addClickHandler(this); ensureDebugId("closeSaveButton"); } /** * Closes the overwrite panel, shows the save panel and selects the * previously entered name. * @param event The event that has fired. */ @Override public void onClick(ClickEvent event) { GuiState.overwriteSavePanel.hide(); GuiState.overwriteSavePanel.remove(GuiState.overwriteSaveButton); GuiState.saveItemPanel.show(); GuiState.saveNameTextBox.setSelectionRange(0, GuiState.saveNameTextBox.getText().length()); GuiState.saveNameTextBox.setFocus(true); } }
false
false
null
null
diff --git a/src/java/com/sapienter/jbilling/server/util/csv/CsvExporter.java b/src/java/com/sapienter/jbilling/server/util/csv/CsvExporter.java index 0d390b7d..d06c91d5 100644 --- a/src/java/com/sapienter/jbilling/server/util/csv/CsvExporter.java +++ b/src/java/com/sapienter/jbilling/server/util/csv/CsvExporter.java @@ -1,123 +1,127 @@ /* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>. */ package com.sapienter.jbilling.server.util.csv; import au.com.bytecode.opencsv.CSVWriter; import com.sapienter.jbilling.server.util.converter.BigDecimalConverter; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; import org.apache.log4j.Logger; import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.util.List; /** * CsvExporter * * @author Brian Cowdery * @since 03/03/11 */ public class CsvExporter<T extends Exportable> implements Exporter<T> { private static final Logger LOG = Logger.getLogger(CsvExporter.class); /** The maximum safe number of exportable elements to processes. */ public static final Integer MAX_RESULTS = 10000; static { ConvertUtils.register(new BigDecimalConverter(), BigDecimal.class); } private Class<T> type; private CsvExporter(Class<T> type) { this.type = type; } /** * Factory method to produce a new instance of CsvExporter for the given type. * * @param type type of exporter * @param <T> type T * @return new exporter of type T */ public static <T extends Exportable> CsvExporter<T> createExporter(Class<T> type) { return new CsvExporter<T>(type); } public Class<T> getType() { return type; } public String export(List<? extends Exportable> list) { String[] header; // list can be empty, instantiate a new instance of type to // extract the field names for the CSV header try { header = type.newInstance().getFieldNames(); } catch (InstantiationException e) { LOG.debug("Could not produce a new instance of " + type.getSimpleName() + " to build CSV header."); return null; } catch (IllegalAccessException e) { LOG.debug("Constructor of " + type.getSimpleName() + " is not accessible to build CSV header."); return null; } StringWriter out = new StringWriter(); CSVWriter writer = new CSVWriter(out); writer.writeNext(header); for (Exportable exportable : list) { for (Object[] values : exportable.getFieldValues()) { writer.writeNext(convertToString(values)); } } try { writer.close(); out.close(); } catch (IOException e) { LOG.debug("Writer cannot be closed, exported CSV may be missing data."); } return out.toString(); } public String[] convertToString(Object[] objects) { String[] strings = new String[objects.length]; int i = 0; for (Object object : objects) { if (object != null) { Converter converter = ConvertUtils.lookup(object.getClass()); - strings[i++] = converter.convert(object.getClass(), object).toString(); + if (converter != null) { + strings[i++] = converter.convert(object.getClass(), object).toString(); + } else { + strings[i++] = object.toString(); + } } else { strings[i++] = ""; } } return strings; } }
true
false
null
null
diff --git a/samples/ApiDemos/src/com/example/android/apis/app/DeviceAdminSample.java b/samples/ApiDemos/src/com/example/android/apis/app/DeviceAdminSample.java index f7ee2d73..b62706a6 100644 --- a/samples/ApiDemos/src/com/example/android/apis/app/DeviceAdminSample.java +++ b/samples/ApiDemos/src/com/example/android/apis/app/DeviceAdminSample.java @@ -1,428 +1,455 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.apis.app; import com.example.android.apis.R; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.admin.DeviceAdminReceiver; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; /** * Example of a do-nothing admin class. When enabled, it lets you control * some of its policy and reports when there is interesting activity. */ public class DeviceAdminSample extends DeviceAdminReceiver { static SharedPreferences getSamplePreferences(Context context) { return context.getSharedPreferences(DeviceAdminReceiver.class.getName(), 0); } static String PREF_PASSWORD_QUALITY = "password_quality"; static String PREF_PASSWORD_LENGTH = "password_length"; + static String PREF_PASSWORD_HISTORY_LENGTH = "password_history_length"; static String PREF_MAX_FAILED_PW = "max_failed_pw"; void showToast(Context context, CharSequence msg) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } @Override public void onEnabled(Context context, Intent intent) { showToast(context, "Sample Device Admin: enabled"); } @Override public CharSequence onDisableRequested(Context context, Intent intent) { return "This is an optional message to warn the user about disabling."; } @Override public void onDisabled(Context context, Intent intent) { showToast(context, "Sample Device Admin: disabled"); } @Override public void onPasswordChanged(Context context, Intent intent) { showToast(context, "Sample Device Admin: pw changed"); } @Override public void onPasswordFailed(Context context, Intent intent) { showToast(context, "Sample Device Admin: pw failed"); } @Override public void onPasswordSucceeded(Context context, Intent intent) { showToast(context, "Sample Device Admin: pw succeeded"); } /** * <p>UI control for the sample device admin. This provides an interface * to enable, disable, and perform other operations with it to see * their effect.</p> * * <p>Note that this is implemented as an inner class only keep the sample * all together; typically this code would appear in some separate class. */ public static class Controller extends Activity { static final int RESULT_ENABLE = 1; DevicePolicyManager mDPM; ActivityManager mAM; ComponentName mDeviceAdminSample; Button mEnableButton; Button mDisableButton; // Password quality spinner choices // This list must match the list found in samples/ApiDemos/res/values/arrays.xml final static int mPasswordQualityValues[] = new int[] { DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC, DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC, DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC }; Spinner mPasswordQuality; EditText mPasswordLength; + EditText mPasswordHistoryLength; Button mSetPasswordButton; EditText mPassword; Button mResetPasswordButton; EditText mMaxFailedPw; Button mForceLockButton; Button mWipeDataButton; private Button mTimeoutButton; private EditText mTimeout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE); mAM = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); mDeviceAdminSample = new ComponentName(Controller.this, DeviceAdminSample.class); setContentView(R.layout.device_admin_sample); // Watch for button clicks. mEnableButton = (Button)findViewById(R.id.enable); mEnableButton.setOnClickListener(mEnableListener); mDisableButton = (Button)findViewById(R.id.disable); mDisableButton.setOnClickListener(mDisableListener); mPasswordQuality = (Spinner)findViewById(R.id.password_quality); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.password_qualities, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mPasswordQuality.setAdapter(adapter); mPasswordQuality.setOnItemSelectedListener( new OnItemSelectedListener() { public void onItemSelected( AdapterView<?> parent, View view, int position, long id) { setPasswordQuality(mPasswordQualityValues[position]); } public void onNothingSelected(AdapterView<?> parent) { setPasswordQuality(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); } }); mPasswordLength = (EditText)findViewById(R.id.password_length); mPasswordLength.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { try { setPasswordLength(Integer.parseInt(s.toString())); } catch (NumberFormatException e) { } } }); + mPasswordHistoryLength = (EditText)findViewById(R.id.password_history_length); + mPasswordHistoryLength.addTextChangedListener(new TextWatcher() { + public void afterTextChanged(Editable s) { + } + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + public void onTextChanged(CharSequence s, int start, int before, int count) { + try { + setPasswordHistoryLength(Integer.parseInt(s.toString())); + } catch (NumberFormatException e) { + } + } + }); mSetPasswordButton = (Button)findViewById(R.id.set_password); mSetPasswordButton.setOnClickListener(mSetPasswordListener); mPassword = (EditText)findViewById(R.id.password); mResetPasswordButton = (Button)findViewById(R.id.reset_password); mResetPasswordButton.setOnClickListener(mResetPasswordListener); mMaxFailedPw = (EditText)findViewById(R.id.max_failed_pw); mMaxFailedPw.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { try { int maxFailCount = Integer.parseInt(s.toString()); if (maxFailCount > 0) { Toast.makeText(Controller.this, "WARNING: Phone will wipe after " + s + " incorrect passwords", Toast.LENGTH_SHORT).show(); } setMaxFailedPw(maxFailCount); } catch (NumberFormatException e) { } } }); mForceLockButton = (Button)findViewById(R.id.force_lock); mForceLockButton.setOnClickListener(mForceLockListener); mWipeDataButton = (Button)findViewById(R.id.wipe_data); mWipeDataButton.setOnClickListener(mWipeDataListener); mTimeout = (EditText) findViewById(R.id.timeout); mTimeoutButton = (Button) findViewById(R.id.set_timeout); mTimeoutButton.setOnClickListener(mSetTimeoutListener); } void updateButtonStates() { boolean active = mDPM.isAdminActive(mDeviceAdminSample); if (active) { mEnableButton.setEnabled(false); mDisableButton.setEnabled(true); mPasswordQuality.setEnabled(true); mPasswordLength.setEnabled(true); + mPasswordHistoryLength.setEnabled(true); mSetPasswordButton.setEnabled(true); mPassword.setEnabled(true); mResetPasswordButton.setEnabled(true); mForceLockButton.setEnabled(true); mWipeDataButton.setEnabled(true); } else { mEnableButton.setEnabled(true); mDisableButton.setEnabled(false); mPasswordQuality.setEnabled(false); mPasswordLength.setEnabled(false); + mPasswordHistoryLength.setEnabled(false); mSetPasswordButton.setEnabled(false); mPassword.setEnabled(false); mResetPasswordButton.setEnabled(false); mForceLockButton.setEnabled(false); mWipeDataButton.setEnabled(false); } } void updateControls() { SharedPreferences prefs = getSamplePreferences(this); final int pwQuality = prefs.getInt(PREF_PASSWORD_QUALITY, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); final int pwLength = prefs.getInt(PREF_PASSWORD_LENGTH, 0); + final int pwHistoryLength = prefs.getInt(PREF_PASSWORD_HISTORY_LENGTH, 0); final int maxFailedPw = prefs.getInt(PREF_MAX_FAILED_PW, 0); for (int i=0; i<mPasswordQualityValues.length; i++) { if (mPasswordQualityValues[i] == pwQuality) { mPasswordQuality.setSelection(i); } } mPasswordLength.setText(Integer.toString(pwLength)); + mPasswordHistoryLength.setText(Integer.toString(pwHistoryLength)); mMaxFailedPw.setText(Integer.toString(maxFailedPw)); } void updatePolicies() { SharedPreferences prefs = getSamplePreferences(this); final int pwQuality = prefs.getInt(PREF_PASSWORD_QUALITY, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); final int pwLength = prefs.getInt(PREF_PASSWORD_LENGTH, 0); + final int pwHistoryLength = prefs.getInt(PREF_PASSWORD_HISTORY_LENGTH, 0); final int maxFailedPw = prefs.getInt(PREF_MAX_FAILED_PW, 0); boolean active = mDPM.isAdminActive(mDeviceAdminSample); if (active) { mDPM.setPasswordQuality(mDeviceAdminSample, pwQuality); mDPM.setPasswordMinimumLength(mDeviceAdminSample, pwLength); + mDPM.setPasswordHistoryLength(mDeviceAdminSample, pwHistoryLength); mDPM.setMaximumFailedPasswordsForWipe(mDeviceAdminSample, maxFailedPw); } } void setPasswordQuality(int quality) { SharedPreferences prefs = getSamplePreferences(this); prefs.edit().putInt(PREF_PASSWORD_QUALITY, quality).commit(); updatePolicies(); } void setPasswordLength(int length) { SharedPreferences prefs = getSamplePreferences(this); prefs.edit().putInt(PREF_PASSWORD_LENGTH, length).commit(); updatePolicies(); } + void setPasswordHistoryLength(int length) { + SharedPreferences prefs = getSamplePreferences(this); + prefs.edit().putInt(PREF_PASSWORD_HISTORY_LENGTH, length).commit(); + updatePolicies(); + } + void setMaxFailedPw(int length) { SharedPreferences prefs = getSamplePreferences(this); prefs.edit().putInt(PREF_MAX_FAILED_PW, length).commit(); updatePolicies(); } @Override protected void onResume() { super.onResume(); updateButtonStates(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case RESULT_ENABLE: if (resultCode == Activity.RESULT_OK) { Log.i("DeviceAdminSample", "Admin enabled!"); } else { Log.i("DeviceAdminSample", "Admin enable FAILED!"); } return; } super.onActivityResult(requestCode, resultCode, data); } private OnClickListener mEnableListener = new OnClickListener() { public void onClick(View v) { // Launch the activity to have the user enable our admin. Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Additional text explaining why this needs to be added."); startActivityForResult(intent, RESULT_ENABLE); } }; private OnClickListener mDisableListener = new OnClickListener() { public void onClick(View v) { mDPM.removeActiveAdmin(mDeviceAdminSample); updateButtonStates(); } }; private OnClickListener mSetPasswordListener = new OnClickListener() { public void onClick(View v) { // Launch the activity to have the user set a new password. Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD); startActivity(intent); } }; private OnClickListener mResetPasswordListener = new OnClickListener() { public void onClick(View v) { if (mAM.isUserAMonkey()) { // Don't trust monkeys to do the right thing! AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this); builder.setMessage("You can't reset my password because you are a monkey!"); builder.setPositiveButton("I admit defeat", null); builder.show(); return; } boolean active = mDPM.isAdminActive(mDeviceAdminSample); if (active) { mDPM.resetPassword(mPassword.getText().toString(), DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY); } } }; private OnClickListener mForceLockListener = new OnClickListener() { public void onClick(View v) { if (mAM.isUserAMonkey()) { // Don't trust monkeys to do the right thing! AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this); builder.setMessage("You can't lock my screen because you are a monkey!"); builder.setPositiveButton("I admit defeat", null); builder.show(); return; } boolean active = mDPM.isAdminActive(mDeviceAdminSample); if (active) { mDPM.lockNow(); } } }; private OnClickListener mWipeDataListener = new OnClickListener() { public void onClick(View v) { if (mAM.isUserAMonkey()) { // Don't trust monkeys to do the right thing! AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this); builder.setMessage("You can't wipe my data because you are a monkey!"); builder.setPositiveButton("I admit defeat", null); builder.show(); return; } AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this); builder.setMessage("This will erase all of your data. Are you sure?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this); builder.setMessage("This is not a test. " + "This WILL erase all of your data! " + "Are you really absolutely sure?"); builder.setPositiveButton("BOOM!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { boolean active = mDPM.isAdminActive(mDeviceAdminSample); if (active) { mDPM.wipeData(0); } } }); builder.setNegativeButton("Oops, run away!", null); builder.show(); } }); builder.setNegativeButton("No way!", null); builder.show(); } }; private OnClickListener mSetTimeoutListener = new OnClickListener() { public void onClick(View v) { if (mAM.isUserAMonkey()) { // Don't trust monkeys to do the right thing! AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this); builder.setMessage("You can't lock my screen because you are a monkey!"); builder.setPositiveButton("I admit defeat", null); builder.show(); return; } boolean active = mDPM.isAdminActive(mDeviceAdminSample); if (active) { long timeMs = 1000L*Long.parseLong(mTimeout.getText().toString()); mDPM.setMaximumTimeToLock(mDeviceAdminSample, timeMs); } } }; } }
false
false
null
null
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java index a50b3cfa6..8772f53e2 100644 --- a/src/com/android/settings/wifi/WifiSettings.java +++ b/src/com/android/settings/wifi/WifiSettings.java @@ -1,857 +1,864 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.wifi; import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.DetailedState; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WpsInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.security.Credentials; import android.security.KeyStore; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.android.settings.R; import com.android.settings.SettingsPreferenceFragment; import com.android.settings.wifi.p2p.WifiP2pSettings; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * Two types of UI are provided here. * * The first is for "usual Settings", appearing as any other Setup fragment. * * The second is for Setup Wizard, with a simplified interface that hides the action bar * and menus. */ public class WifiSettings extends SettingsPreferenceFragment implements DialogInterface.OnClickListener { private static final String TAG = "WifiSettings"; private static final int MENU_ID_WPS_PBC = Menu.FIRST; private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1; private static final int MENU_ID_P2P = Menu.FIRST + 2; private static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3; private static final int MENU_ID_ADVANCED = Menu.FIRST + 4; private static final int MENU_ID_SCAN = Menu.FIRST + 5; private static final int MENU_ID_CONNECT = Menu.FIRST + 6; private static final int MENU_ID_FORGET = Menu.FIRST + 7; private static final int MENU_ID_MODIFY = Menu.FIRST + 8; private static final int WIFI_DIALOG_ID = 1; private static final int WPS_PBC_DIALOG_ID = 2; private static final int WPS_PIN_DIALOG_ID = 3; // Combo scans can take 5-6s to complete - set to 10s. private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000; // Instance state keys private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode"; private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state"; private final IntentFilter mFilter; private final BroadcastReceiver mReceiver; private final Scanner mScanner; private WifiManager mWifiManager; private WifiManager.Channel mChannel; private WifiManager.ActionListener mConnectListener; private WifiManager.ActionListener mSaveListener; private WifiManager.ActionListener mForgetListener; private boolean mP2pSupported; private WifiEnabler mWifiEnabler; // An access point being editted is stored here. private AccessPoint mSelectedAccessPoint; private DetailedState mLastState; private WifiInfo mLastInfo; private AtomicBoolean mConnected = new AtomicBoolean(false); private int mKeyStoreNetworkId = INVALID_NETWORK_ID; private WifiDialog mDialog; private TextView mEmptyView; /* Used in Wifi Setup context */ // this boolean extra specifies whether to disable the Next button when not connected private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect"; private static final String EXTRA_WIFI_SHOW_ACTION_BAR = "wifi_show_action_bar"; private static final String EXTRA_WIFI_SHOW_MENUS = "wifi_show_menus"; // should Next button only be enabled when we have a connection? private boolean mEnableNextOnConnection; // Save the dialog details private boolean mDlgEdit; private AccessPoint mDlgAccessPoint; private Bundle mAccessPointSavedState; // Menus are not shown by Setup Wizard private boolean mShowMenu; /* End of "used in Wifi Setup context" */ public WifiSettings() { mFilter = new IntentFilter(); mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION); mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { handleEvent(context, intent); } }; mScanner = new Scanner(); } @Override public void onActivityCreated(Bundle savedInstanceState) { // We don't call super.onActivityCreated() here, since it assumes we already set up // Preference (probably in onCreate()), while WifiSettings exceptionally set it up in // this method. mP2pSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); mChannel = mWifiManager.initialize(getActivity(), getActivity().getMainLooper(), null); mConnectListener = new WifiManager.ActionListener() { public void onSuccess() { } public void onFailure(int reason) { Toast.makeText(getActivity(), R.string.wifi_failed_connect_message, Toast.LENGTH_SHORT).show(); } }; mSaveListener = new WifiManager.ActionListener() { public void onSuccess() { } public void onFailure(int reason) { Toast.makeText(getActivity(), R.string.wifi_failed_save_message, Toast.LENGTH_SHORT).show(); } }; mForgetListener = new WifiManager.ActionListener() { public void onSuccess() { } public void onFailure(int reason) { Toast.makeText(getActivity(), R.string.wifi_failed_forget_message, Toast.LENGTH_SHORT).show(); } }; if (savedInstanceState != null && savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) { mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE); mAccessPointSavedState = savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE); } final Activity activity = getActivity(); final Intent intent = activity.getIntent(); // if we're supposed to enable/disable the Next button based on our current connection // state, start it off in the right state mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); if (mEnableNextOnConnection) { if (hasNextButton()) { final ConnectivityManager connectivity = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getNetworkInfo( ConnectivityManager.TYPE_WIFI); changeNextButtonState(info.isConnected()); } } } addPreferencesFromResource(R.xml.wifi_settings); // Action bar is hidden for Setup Wizard final boolean showActionBar = intent.getBooleanExtra(EXTRA_WIFI_SHOW_ACTION_BAR, true); if (showActionBar) { Switch actionBarSwitch = new Switch(activity); if (activity instanceof PreferenceActivity) { PreferenceActivity preferenceActivity = (PreferenceActivity) activity; if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) { final int padding = activity.getResources().getDimensionPixelSize( R.dimen.action_bar_switch_padding); actionBarSwitch.setPadding(0, 0, padding, 0); activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM); activity.getActionBar().setCustomView(actionBarSwitch, new ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT)); } } mWifiEnabler = new WifiEnabler(activity, actionBarSwitch); } mEmptyView = (TextView) getView().findViewById(android.R.id.empty); getListView().setEmptyView(mEmptyView); // Menu is hidden for Setup Wizard mShowMenu = intent.getBooleanExtra(EXTRA_WIFI_SHOW_MENUS, true); if (mShowMenu) { registerForContextMenu(getListView()); } - setHasOptionsMenu(mShowMenu); + // FIXME: When WPS image button is implemented, use mShowMenu instead of always showing + // the options menu + setHasOptionsMenu(true); // After confirming PreferenceScreen is available, we call super. super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); if (mWifiEnabler != null) { mWifiEnabler.resume(); } getActivity().registerReceiver(mReceiver, mFilter); if (mKeyStoreNetworkId != INVALID_NETWORK_ID && KeyStore.getInstance().state() == KeyStore.State.UNLOCKED) { mWifiManager.connect(mChannel, mKeyStoreNetworkId, mConnectListener); } mKeyStoreNetworkId = INVALID_NETWORK_ID; updateAccessPoints(); } @Override public void onPause() { super.onPause(); if (mWifiEnabler != null) { mWifiEnabler.pause(); } getActivity().unregisterReceiver(mReceiver); mScanner.pause(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); if (mShowMenu) { - final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) .setEnabled(wifiIsEnabled) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); if (mP2pSupported) { menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p) .setEnabled(wifiIsEnabled) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) .setEnabled(wifiIsEnabled) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan) //.setIcon(R.drawable.ic_menu_scan_network) .setEnabled(wifiIsEnabled) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin) .setEnabled(wifiIsEnabled) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) //.setIcon(android.R.drawable.ic_menu_manage) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); + } else { + // FIXME: Interim support for WPS, until ImageButton is available + menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) + .setEnabled(wifiIsEnabled) + .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } super.onCreateOptionsMenu(menu, inflater); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // If the dialog is showing, save its state. if (mDialog != null && mDialog.isShowing()) { outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit); if (mDlgAccessPoint != null) { mAccessPointSavedState = new Bundle(); mDlgAccessPoint.saveWifiState(mAccessPointSavedState); outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ID_WPS_PBC: showDialog(WPS_PBC_DIALOG_ID); return true; case MENU_ID_P2P: if (getActivity() instanceof PreferenceActivity) { ((PreferenceActivity) getActivity()).startPreferencePanel( WifiP2pSettings.class.getCanonicalName(), null, R.string.wifi_p2p_settings_title, null, this, 0); } else { startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null); } return true; case MENU_ID_WPS_PIN: showDialog(WPS_PIN_DIALOG_ID); return true; case MENU_ID_SCAN: if (mWifiManager.isWifiEnabled()) { mScanner.forceScan(); } return true; case MENU_ID_ADD_NETWORK: if (mWifiManager.isWifiEnabled()) { onAddNetworkPressed(); } return true; case MENU_ID_ADVANCED: if (getActivity() instanceof PreferenceActivity) { ((PreferenceActivity) getActivity()).startPreferencePanel( AdvancedWifiSettings.class.getCanonicalName(), null, R.string.wifi_advanced_titlebar, null, this, 0); } else { startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null); } return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { if (info instanceof AdapterContextMenuInfo) { Preference preference = (Preference) getListView().getItemAtPosition( ((AdapterContextMenuInfo) info).position); if (preference instanceof AccessPoint) { mSelectedAccessPoint = (AccessPoint) preference; menu.setHeaderTitle(mSelectedAccessPoint.ssid); if (mSelectedAccessPoint.getLevel() != -1 && mSelectedAccessPoint.getState() == null) { menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); } if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); } } } } @Override public boolean onContextItemSelected(MenuItem item) { if (mSelectedAccessPoint == null) { return super.onContextItemSelected(item); } switch (item.getItemId()) { case MENU_ID_CONNECT: { if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { if (!requireKeyStore(mSelectedAccessPoint.getConfig())) { mWifiManager.connect(mChannel, mSelectedAccessPoint.networkId, mConnectListener); } } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) { /** Bypass dialog for unsecured networks */ mSelectedAccessPoint.generateOpenNetworkConfig(); mWifiManager.connect(mChannel, mSelectedAccessPoint.getConfig(), mConnectListener); } else { showDialog(mSelectedAccessPoint, true); } return true; } case MENU_ID_FORGET: { mWifiManager.forget(mChannel, mSelectedAccessPoint.networkId, mForgetListener); return true; } case MENU_ID_MODIFY: { showDialog(mSelectedAccessPoint, true); return true; } } return super.onContextItemSelected(item); } @Override public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { if (preference instanceof AccessPoint) { mSelectedAccessPoint = (AccessPoint) preference; /** Bypass dialog for unsecured, unsaved networks */ if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE && mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { mSelectedAccessPoint.generateOpenNetworkConfig(); mWifiManager.connect(mChannel, mSelectedAccessPoint.getConfig(), mConnectListener); } else { showDialog(mSelectedAccessPoint, false); } } else { return super.onPreferenceTreeClick(screen, preference); } return true; } private void showDialog(AccessPoint accessPoint, boolean edit) { if (mDialog != null) { removeDialog(WIFI_DIALOG_ID); mDialog = null; } // Save the access point and edit mode mDlgAccessPoint = accessPoint; mDlgEdit = edit; showDialog(WIFI_DIALOG_ID); } @Override public Dialog onCreateDialog(int dialogId) { switch (dialogId) { case WIFI_DIALOG_ID: AccessPoint ap = mDlgAccessPoint; // For manual launch if (ap == null) { // For re-launch from saved state if (mAccessPointSavedState != null) { ap = new AccessPoint(getActivity(), mAccessPointSavedState); // For repeated orientation changes mDlgAccessPoint = ap; } } // If it's still null, fine, it's for Add Network mSelectedAccessPoint = ap; mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit); return mDialog; case WPS_PBC_DIALOG_ID: return new WpsDialog(getActivity(), WpsInfo.PBC); case WPS_PIN_DIALOG_ID: return new WpsDialog(getActivity(), WpsInfo.DISPLAY); } return super.onCreateDialog(dialogId); } private boolean requireKeyStore(WifiConfiguration config) { if (WifiConfigController.requireKeyStore(config) && KeyStore.getInstance().state() != KeyStore.State.UNLOCKED) { mKeyStoreNetworkId = config.networkId; Credentials.getInstance().unlock(getActivity()); return true; } return false; } /** * Shows the latest access points available with supplimental information like * the strength of network and the security for it. */ private void updateAccessPoints() { // Safeguard from some delayed event handling if (getActivity() == null) return; final int wifiState = mWifiManager.getWifiState(); switch (wifiState) { case WifiManager.WIFI_STATE_ENABLED: // AccessPoints are automatically sorted with TreeSet. final Collection<AccessPoint> accessPoints = constructAccessPoints(); getPreferenceScreen().removeAll(); if(accessPoints.size() == 0) { addMessagePreference(R.string.wifi_empty_list_wifi_on); } for (AccessPoint accessPoint : accessPoints) { getPreferenceScreen().addPreference(accessPoint); } break; case WifiManager.WIFI_STATE_ENABLING: getPreferenceScreen().removeAll(); break; case WifiManager.WIFI_STATE_DISABLING: addMessagePreference(R.string.wifi_stopping); break; case WifiManager.WIFI_STATE_DISABLED: addMessagePreference(R.string.wifi_empty_list_wifi_off); break; } } private void addMessagePreference(int messageId) { if (mEmptyView != null) mEmptyView.setText(messageId); getPreferenceScreen().removeAll(); } /** Returns sorted list of access points */ private List<AccessPoint> constructAccessPoints() { ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>(); /** Lookup table to more quickly update AccessPoints by only considering objects with the * correct SSID. Maps SSID -> List of AccessPoints with the given SSID. */ Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>(); final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); if (configs != null) { for (WifiConfiguration config : configs) { AccessPoint accessPoint = new AccessPoint(getActivity(), config); accessPoint.update(mLastInfo, mLastState); accessPoints.add(accessPoint); apMap.put(accessPoint.ssid, accessPoint); } } final List<ScanResult> results = mWifiManager.getScanResults(); if (results != null) { for (ScanResult result : results) { // Ignore hidden and ad-hoc networks. if (result.SSID == null || result.SSID.length() == 0 || result.capabilities.contains("[IBSS]")) { continue; } boolean found = false; for (AccessPoint accessPoint : apMap.getAll(result.SSID)) { if (accessPoint.update(result)) found = true; } if (!found) { AccessPoint accessPoint = new AccessPoint(getActivity(), result); accessPoints.add(accessPoint); apMap.put(accessPoint.ssid, accessPoint); } } } // Pre-sort accessPoints to speed preference insertion Collections.sort(accessPoints); return accessPoints; } /** A restricted multimap for use in constructAccessPoints */ private class Multimap<K,V> { private HashMap<K,List<V>> store = new HashMap<K,List<V>>(); /** retrieve a non-null list of values with key K */ List<V> getAll(K key) { List<V> values = store.get(key); return values != null ? values : Collections.<V>emptyList(); } void put(K key, V val) { List<V> curVals = store.get(key); if (curVals == null) { curVals = new ArrayList<V>(3); store.put(key, curVals); } curVals.add(val); } } private void handleEvent(Context context, Intent intent) { String action = intent.getAction(); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)); } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) || WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) || WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) { updateAccessPoints(); } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) { //Ignore supplicant state changes when network is connected //TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and //introduce a broadcast that combines the supplicant and network //network state change events so the apps dont have to worry about //ignoring supplicant state change when network is connected //to get more fine grained information. SupplicantState state = (SupplicantState) intent.getParcelableExtra( WifiManager.EXTRA_NEW_STATE); if (!mConnected.get() && SupplicantState.isHandshakeState(state)) { updateConnectionState(WifiInfo.getDetailedStateOf(state)); } } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( WifiManager.EXTRA_NETWORK_INFO); mConnected.set(info.isConnected()); changeNextButtonState(info.isConnected()); updateAccessPoints(); updateConnectionState(info.getDetailedState()); } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) { updateConnectionState(null); } } private void updateConnectionState(DetailedState state) { /* sticky broadcasts can call this when wifi is disabled */ if (!mWifiManager.isWifiEnabled()) { mScanner.pause(); return; } if (state == DetailedState.OBTAINING_IPADDR) { mScanner.pause(); } else { mScanner.resume(); } mLastInfo = mWifiManager.getConnectionInfo(); if (state != null) { mLastState = state; } for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) { // Maybe there's a WifiConfigPreference Preference preference = getPreferenceScreen().getPreference(i); if (preference instanceof AccessPoint) { final AccessPoint accessPoint = (AccessPoint) preference; accessPoint.update(mLastInfo, mLastState); } } } private void updateWifiState(int state) { getActivity().invalidateOptionsMenu(); switch (state) { case WifiManager.WIFI_STATE_ENABLED: mScanner.resume(); return; // not break, to avoid the call to pause() below case WifiManager.WIFI_STATE_ENABLING: addMessagePreference(R.string.wifi_starting); break; case WifiManager.WIFI_STATE_DISABLED: addMessagePreference(R.string.wifi_empty_list_wifi_off); break; } mLastInfo = null; mLastState = null; mScanner.pause(); } private class Scanner extends Handler { private int mRetry = 0; void resume() { if (!hasMessages(0)) { sendEmptyMessage(0); } } void forceScan() { removeMessages(0); sendEmptyMessage(0); } void pause() { mRetry = 0; removeMessages(0); } @Override public void handleMessage(Message message) { if (mWifiManager.startScanActive()) { mRetry = 0; } else if (++mRetry >= 3) { mRetry = 0; Toast.makeText(getActivity(), R.string.wifi_fail_to_scan, Toast.LENGTH_LONG).show(); return; } sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS); } } /** * Renames/replaces "Next" button when appropriate. "Next" button usually exists in * Wifi setup screens, not in usual wifi settings screen. * * @param connected true when the device is connected to a wifi network. */ private void changeNextButtonState(boolean connected) { if (mEnableNextOnConnection && hasNextButton()) { getNextButton().setEnabled(connected); } } public void onClick(DialogInterface dialogInterface, int button) { if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) { forget(); } else if (button == WifiDialog.BUTTON_SUBMIT) { submit(mDialog.getController()); } } /* package */ void submit(WifiConfigController configController) { final WifiConfiguration config = configController.getConfig(); if (config == null) { if (mSelectedAccessPoint != null && !requireKeyStore(mSelectedAccessPoint.getConfig()) && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { mWifiManager.connect(mChannel, mSelectedAccessPoint.networkId, mConnectListener); } } else if (config.networkId != INVALID_NETWORK_ID) { if (mSelectedAccessPoint != null) { mWifiManager.save(mChannel, config, mSaveListener); } } else { if (configController.isEdit() || requireKeyStore(config)) { mWifiManager.save(mChannel, config, mSaveListener); } else { mWifiManager.connect(mChannel, config, mConnectListener); } } if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } updateAccessPoints(); } /* package */ void forget() { if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { // Should not happen, but a monkey seems to triger it Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); return; } mWifiManager.forget(mChannel, mSelectedAccessPoint.networkId, mForgetListener); if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } updateAccessPoints(); // We need to rename/replace "Next" button in wifi setup context. changeNextButtonState(false); } /** * Refreshes acccess points and ask Wifi module to scan networks again. */ /* package */ void refreshAccessPoints() { if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } getPreferenceScreen().removeAll(); } /** * Called when "add network" button is pressed. */ /* package */ void onAddNetworkPressed() { // No exact access point is selected. mSelectedAccessPoint = null; showDialog(null, true); } /* package */ int getAccessPointsCount() { final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); if (wifiIsEnabled) { return getPreferenceScreen().getPreferenceCount(); } else { return 0; } } /** * Requests wifi module to pause wifi scan. May be ignored when the module is disabled. */ /* package */ void pauseWifiScan() { if (mWifiManager.isWifiEnabled()) { mScanner.pause(); } } /** * Requests wifi module to resume wifi scan. May be ignored when the module is disabled. */ /* package */ void resumeWifiScan() { if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } } @Override protected int getHelpResource() { // Setup Wizard has different help content if (mShowMenu) { return R.string.help_url_wifi; } return 0; } }
false
false
null
null
diff --git a/app/controllers/GateWorker.java b/app/controllers/GateWorker.java index 4d05745..3d741a3 100644 --- a/app/controllers/GateWorker.java +++ b/app/controllers/GateWorker.java @@ -1,370 +1,372 @@ /** * This file is part of RibbonWeb application (check README). * Copyright (C) 2012-2013 Stanislav Nepochatov * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ package controllers; import play.db.ebean.Model; /** * Gate connector thread class. This class is almost a copy * of AppComponents.NetWorker class in libRibbonApp * @author Stanislav Nepochatov <[email protected]> */ public class GateWorker extends Thread{ /** * Client socket object. */ public java.net.Socket clientSocket; /** * Input stream (from server). */ public java.io.BufferedReader inStream; /** * Output stream (to server). */ public java.io.PrintWriter outStream; /** * Display is NetWorker connection is alive. */ public Boolean isAlive = false; /** * Array of protocol listeners. */ public AppComponents.Listener[] NetListeners; /** * Define NetWorker collect/execute behavior. * <p>Modes: * <ul> * <li>0 - execute commands;</li> * <li>1 - collect single input line</li> * <li>2 - collect all line before END: command emmited;</li> * </ul> * </p> */ protected Integer collectState = 0; /** * String buffer for collected data. */ protected StringBuffer collectBuf = new StringBuffer(); /** * Personal collect lock object. */ private final Object collectLock = new Object(); private Boolean atomFlag = false; private final Object atomLock = new Object(); /** * Try connect to server. * @param givenAddress address to connect; * @param givenPort port to connect; */ public void tryConnect(String givenAddress, Integer givenPort) { this.NetListeners = getProtocol(); try { clientSocket = new java.net.Socket(givenAddress, givenPort); inStream = new java.io.BufferedReader(new java.io.InputStreamReader(clientSocket.getInputStream(), "UTF-8")); outStream = new java.io.PrintWriter(clientSocket.getOutputStream(), true); isAlive = true; } catch (java.io.IOException ex) {MiniGate.gateErrorStr = "Неможливо встановити з’єднання!";} } /** * Get protocol listeners (should be overriden). * @return array of listeners; */ public AppComponents.Listener[] getProtocol() { return new AppComponents.Listener[] { //Disable gate if server closing connection. new AppComponents.Listener("COMMIT_CLOSE") { @Override public void exec(String args) { System.out.println("Завершення роботи гейта."); isAlive = false; } }, //Mark database message entry with server command. new AppComponents.Listener("RIBBON_UCTL_LOAD_INDEX") { @Override public void exec(String args) { MessageClasses.MessageEntry currMessage = new MessageClasses.MessageEntry(args); synchronized (MiniGate.sender.getLock()) { if (currMessage.getProperty("REMOTE_ID") != null) { models.MessageProbe gettedProbe = (models.MessageProbe) new Model.Finder(String.class, models.MessageProbe.class).byId(currMessage.getProperty("REMOTE_ID").TEXT_MESSAGE); if (gettedProbe != null) { gettedProbe.ribbon_index = currMessage.INDEX; gettedProbe.update(); } } models.MessageProbe gettedProbe2 = (models.MessageProbe) new Model.Finder(String.class, models.MessageProbe.class).where().eq("ribbon_index", currMessage.ORIG_INDEX).findUnique(); if (gettedProbe2 != null) { gettedProbe2.curr_status = models.MessageProbe.STATUS.ACCEPTED; gettedProbe2.update(); } } } }, new AppComponents.Listener("RIBBON_UCTL_UPDATE_INDEX") { @Override public void exec(String args) { MessageClasses.MessageEntry currMessage = new MessageClasses.MessageEntry(args); synchronized (MiniGate.sender.getLock()) { models.MessageProbe gettedProbe = (models.MessageProbe) new Model.Finder(String.class, models.MessageProbe.class).where().eq("ribbon_index", currMessage.INDEX).findUnique(); if (gettedProbe != null) { if (gettedProbe.curr_status == models.MessageProbe.STATUS.WAIT_CONFIRM) { gettedProbe.curr_status = models.MessageProbe.STATUS.POSTED; gettedProbe.update(); } else { gettedProbe.curr_status = models.MessageProbe.STATUS.ACCEPTED; gettedProbe.update(); } } } } } }; } @Override public void run() { while (isAlive) { try { synchronized (atomLock) { atomFlag = true; atomLock.notifyAll(); } String inputLine = null; inputLine = inStream.readLine(); System.out.println("SERV: " + inputLine); if (inputLine == null) { throw new NullPointerException(); } synchronized (collectLock) { synchronized (atomLock) { atomFlag = false; } System.out.println("COLLECT = " + collectState); switch (collectState) { case 0: try { this.exec(inputLine); } catch (Exception ex) { ex.printStackTrace(); } break; case 1: collectBuf.append(inputLine); collectState = 0; System.out.println("<RET"); collectLock.notify(); break; case 2: if (!inputLine.startsWith("END:")) { collectBuf.append(inputLine + "\n"); if (inputLine.startsWith("RIBBON_ERROR:")) { collectState = 0; System.out.println("<ERROR"); collectLock.notify(); } } else { collectState = 0; System.out.println("<COLLECT"); collectLock.notify(); } } } } catch (java.io.IOException ex) { isAlive = false; } catch (NullPointerException ex) { MiniGate.isGateReady = false; MiniGate.gateErrorStr = "Сервер не відповідає!"; this.closeGate(); MiniGate.gate = new GateWorker(); MiniGate.init(); break; } } } /** * Execute command with listeners array. * @param inputCommand command to execute; */ private void exec(String inputCommand) { String[] parsedCommandStruct = Generic.CsvFormat.parseDoubleStruct(inputCommand); Boolean executed = false; for (AppComponents.Listener currListener : NetListeners) { if (parsedCommandStruct[0].equals(currListener.COMM_NAME)) { currListener.exec(parsedCommandStruct[1]); executed = true; } } if (!executed) {} } /** * Send command to the server. * @param givenCommand command to send; */ public void sendCommand(String givenCommand) { synchronized (atomLock) { if (!atomFlag) { try { System.out.println("===WAIT==="); atomLock.wait(); } catch (InterruptedException ex) {} } } System.out.println("===PRINT==="); outStream.println(givenCommand); } /** * Send command and return server status. * @param givenCommand command to send; * @return return status line from server; */ public String sendCommandWithReturn(String givenCommand) { String respond = null; this.collectState = 1; System.out.println(">RET: " + givenCommand); sendCommand(givenCommand); synchronized (collectLock) { while (collectState == 1) { try { collectLock.wait(); } catch (InterruptedException ex) {} } respond = collectBuf.toString(); collectBuf = new StringBuffer(); } return respond; } /** * Send command and return command status. * @param givenCommand command to send; * @return return null if respond is OK: or String if error ocurred; */ public String sendCommandWithCheck(String givenCommand) { String respond = sendCommandWithReturn(givenCommand); if (respond.startsWith("OK:") || respond.startsWith("PROCEED:")) { return null; } else if (respond.startsWith("RIBBON_ERROR")){ return respond.substring(respond.indexOf(':') + 1); } else { this.exec(respond); return null; } } /** * Send command and get input stream to END: command break. * @param givenCommand command to send; * @return all lines to END:; */ public String sendCommandWithCollect(String givenCommand) { String respond; synchronized (collectLock) { System.out.println(">COLLECT: " + givenCommand); this.collectState = 2; sendCommand(givenCommand); while (collectState == 2) { try { collectLock.wait(); } catch (InterruptedException ex) { } } respond = collectBuf.toString(); collectBuf = new StringBuffer(); } return respond; } /** * Close this gate connection. */ public void closeGate() { - outStream.println("RIBBON_NCTL_CLOSE:"); + if (outStream != null) { + outStream.println("RIBBON_NCTL_CLOSE:"); + } } /** * Collect stream to END: command break.<br> * <p><b>WARNING! This method don't use synchronization with <code>socketLock</code>!</b></p> * @return all lines to END:; */ public String collectToEnd() { StringBuffer buf = new StringBuffer(); Boolean keepCollect = true; while (keepCollect) { try { String inputLine = inStream.readLine(); if (!inputLine.equals("END:")) { buf.append(inputLine); buf.append("\n"); } else { keepCollect = false; } } catch (java.io.IOException ex) { isAlive = false; } } return buf.toString(); } /** * Send command with context switching and return answer from server; * @param givenUser name form using context; * @return answer from server. */ public String sendCommandWithContextCollect(String givenUser, String givenCommand) { String contextErr = this.sendCommandWithCheck("RIBBON_NCTL_ACCESS_CONTEXT:{" + givenUser + "}"); if (contextErr != null) { return contextErr; } return this.sendCommandWithCollect(givenCommand); } /** * Send command with context switching and return answer from server; * @param givenUser name form using context; * @return answer from server. */ public String sendCommandWithContextReturn(String givenUser, String givenCommand) { String contextErr = this.sendCommandWithCheck("RIBBON_NCTL_ACCESS_CONTEXT:{" + givenUser + "}"); if (contextErr != null) { return contextErr; } return this.sendCommandWithReturn(givenCommand); } }
true
false
null
null
diff --git a/statcvs-xml2/src/de/berlios/statcvs/xml/chart/SymbolicNameAnnotation.java b/statcvs-xml2/src/de/berlios/statcvs/xml/chart/SymbolicNameAnnotation.java index 7730bdf..3c2f8d8 100644 --- a/statcvs-xml2/src/de/berlios/statcvs/xml/chart/SymbolicNameAnnotation.java +++ b/statcvs-xml2/src/de/berlios/statcvs/xml/chart/SymbolicNameAnnotation.java @@ -1,123 +1,130 @@ /* * StatCvs-XML - XML output for StatCvs. * * Copyright by Steffen Pingel, Tammo van Lessen. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package de.berlios.statcvs.xml.chart; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import net.sf.statcvs.model.SymbolicName; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RefineryUtilities; import org.jfree.ui.TextAnchor; /** * SymbolicNameAnnotation * * Provides symbolic name annotations for XYPlots with java.util.Date * objects on the domain axis. * * @author Tammo van Lessen */ public class SymbolicNameAnnotation implements XYAnnotation { private final Color linePaint = Color.GRAY; private final Color textPaint = Color.DARK_GRAY; private final Stroke stroke = new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {3.5f}, 0.0f); private final Font font = new Font("Dialog", Font.PLAIN, 9); private SymbolicName symbolicName; /** * Creates an annotation for a symbolic name. * Paints a gray dashed vertical line at the symbolic names * date position and draws its name at the top left. * * @param symbolicName */ public SymbolicNameAnnotation(SymbolicName symbolicName) { this.symbolicName = symbolicName; } /** * @see org.jfree.chart.annotations.XYAnnotation#draw(java.awt.Graphics2D, org.jfree.chart.plot.XYPlot, java.awt.geom.Rectangle2D, org.jfree.chart.axis.ValueAxis, org.jfree.chart.axis.ValueAxis) */ public void draw(Graphics2D g2d, XYPlot xyPlot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis) { PlotOrientation orientation = xyPlot.getOrientation(); + // don't draw the annotation if symbolic names date is out of axis' bounds. + if (domainAxis.getUpperBound() < symbolicName.getDate().getTime() + || domainAxis.getLowerBound() > symbolicName.getDate().getTime()) { + + return; + } + RectangleEdge domainEdge = Plot.resolveDomainAxisLocation( xyPlot.getDomainAxisLocation(), orientation); RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation( xyPlot.getRangeAxisLocation(), orientation); float x = (float)domainAxis.translateValueToJava2D( symbolicName.getDate().getTime(), dataArea, domainEdge); float y1 = (float)rangeAxis.translateValueToJava2D( rangeAxis.getUpperBound(), dataArea, rangeEdge); float y2 = (float)rangeAxis.translateValueToJava2D( rangeAxis.getLowerBound(), dataArea, rangeEdge); g2d.setPaint(linePaint); g2d.setStroke(stroke); Line2D line = new Line2D.Float(x, y1, x, y2); g2d.draw(line); float anchorX = x; float anchorY = y1 + 2; g2d.setFont(font); g2d.setPaint(textPaint); /*g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);*/ RefineryUtilities.drawRotatedString( symbolicName.getName(), g2d, anchorX, anchorY, TextAnchor.BOTTOM_RIGHT, TextAnchor.BOTTOM_RIGHT, -Math.PI/2 ); } } \ No newline at end of file
true
false
null
null
diff --git a/src/compiler/language/translator/conceptual/ConceptualTranslator.java b/src/compiler/language/translator/conceptual/ConceptualTranslator.java index f191e0e..c6b774f 100644 --- a/src/compiler/language/translator/conceptual/ConceptualTranslator.java +++ b/src/compiler/language/translator/conceptual/ConceptualTranslator.java @@ -1,144 +1,149 @@ package compiler.language.translator.conceptual; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import compiler.language.ast.ParseInfo; import compiler.language.ast.topLevel.CompilationUnitAST; import compiler.language.conceptual.ConceptualException; import compiler.language.conceptual.NameConflictException; import compiler.language.conceptual.QName; import compiler.language.conceptual.Resolvable; import compiler.language.conceptual.UnresolvableException; import compiler.language.conceptual.topLevel.ConceptualFile; import compiler.language.conceptual.topLevel.ConceptualPackage; import compiler.language.parser.LanguageParser; import compiler.language.parser.LanguageTokenizer; /* * Created on 14 Nov 2010 */ /** * @author Anthony Bryant */ public class ConceptualTranslator { private LanguageParser parser; private ConceptualPackage rootPackage; private ASTConverter astConverter; private NameResolver nameResolver; /** * Creates a new ConceptualTranslator to parse and convert files to the conceptual hierarchy. * @param parser - the LanguageParser to use to parse files * @param classpath - the classpath for this translator */ public ConceptualTranslator(LanguageParser parser, List<File> classpath) { this.parser = parser; rootPackage = new ConceptualPackage(this, classpath); astConverter = new ASTConverter(rootPackage); nameResolver = new NameResolver(astConverter.getConceptualASTNodes()); nameResolver.initialize(rootPackage); } /** * Translates the files which have been parsed into the conceptual representation. * @throws NameConflictException - if a name conflict was detected * @throws ConceptualException - if a conceptual problem was detected during the translation */ public void translate() throws NameConflictException, ConceptualException { nameResolver.resolveParents(); } /** * Resolves the specified QName on the root package * @param name - the name to resolve * @return the Resolvable resolved * @throws NameConflictException - if a name conflict was detected * @throws UnresolvableException - if the name is not resolvable without more information */ public Resolvable translate(QName name) throws NameConflictException, UnresolvableException { return rootPackage.resolve(name, false); } /** * Attempts to parse the specified file into a conceptual file. If something fails in the process, an error is printed before returning null. * If a file is correctly parsed and converted into a ConceptualFile, it is also added to the NameResolver. * @param file - the file to parse * @param expectedPackage - the package that the file is expected to be in, which should be checked against the package declaration inside it * @return the ConceptualFile parsed, or null if an error occurred */ public ConceptualFile parseFile(File file, ConceptualPackage expectedPackage) { CompilationUnitAST ast; try { FileReader reader = new FileReader(file); LanguageTokenizer tokenizer = new LanguageTokenizer(reader); ast = parser.parse(tokenizer); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } + if (ast == null) + { + return null; + } + try { ConceptualFile conceptualFile = astConverter.convert(file, ast, expectedPackage); nameResolver.addFile(conceptualFile); return conceptualFile; } catch (ConceptualException e) { printConceptualException(e.getMessage(), e.getParseInfo()); return null; } catch (NameConflictException e) { printConceptualException(e.getMessage() == null ? "Name conflict detected" : e.getMessage(), e.getParseInfo()); return null; } } private static void printConceptualException(String message, ParseInfo... parseInfos) { if (parseInfos == null || parseInfos.length < 1) { System.err.println(message); return; } // make a String representation of the ParseInfos' character ranges StringBuffer buffer = new StringBuffer(); for (int i = 0; i < parseInfos.length; i++) { // line:start-end buffer.append(parseInfos[i].getLocationText()); if (i != parseInfos.length - 1) { buffer.append(", "); } } if (parseInfos.length == 1) { System.err.println(buffer + ": " + message); System.err.println(parseInfos[0].getHighlightedLine()); } else { System.err.println(buffer + ": " + message); for (ParseInfo info : parseInfos) { System.err.println(info.getHighlightedLine()); } } } }
true
false
null
null
diff --git a/src/main/java/org/xerial/snappy/Snappy.java b/src/main/java/org/xerial/snappy/Snappy.java index 256a5b4..0f8436f 100755 --- a/src/main/java/org/xerial/snappy/Snappy.java +++ b/src/main/java/org/xerial/snappy/Snappy.java @@ -1,544 +1,544 @@ /*-------------------------------------------------------------------------- * Copyright 2011 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // snappy-java Project // // Snappy.java // Since: 2011/03/29 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.snappy; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; /** * Snappy API for data compression/decompression * * @author leo * */ public class Snappy { static { LoadSnappy.load(); } /** * High-level API for compressing the input byte array. This method performs * array copy to generate the result. If you want to save this cost, use * {@link #compress(byte[], int, int, byte[], int)} or * {@link #compress(ByteBuffer, ByteBuffer)}. * * @param input * the input data * @return the compressed byte array * @throws SnappyException */ public static byte[] compress(byte[] input) throws SnappyException { return rawCompress(input, input.length); } /** * Compress the input buffer content in [inputOffset, * ...inputOffset+inputLength) then output to the specified output buffer. * * @param input * @param inputOffset * @param inputLength * @param output * @param outputOffset * @return byte size of the compressed data * @throws SnappyException * when failed to access the input/output buffer */ public static int compress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws SnappyException { return rawCompress(input, inputOffset, inputLength, output, outputOffset); } /** * Compress the content in the given input buffer. After the compression, * you can retrieve the compressed data from the output buffer [pos() ... * limit()) (compressed data size = limit() - pos() = remaining()) * * @param uncompressed * buffer[pos() ... limit()) containing the input data * @param compressed * output of the compressed data. Uses range [pos()..]. * @return byte size of the compressed data. * * @throws SnappyError * when the input is not a direct buffer */ public static int compress(ByteBuffer uncompressed, ByteBuffer compressed) throws SnappyException { if (!uncompressed.isDirect()) throw new SnappyError(SnappyErrorCode.NOT_A_DIRECT_BUFFER, "input is not a direct buffer"); if (!compressed.isDirect()) throw new SnappyError(SnappyErrorCode.NOT_A_DIRECT_BUFFER, "destination is not a direct buffer"); // input: uncompressed[pos(), limit()) // output: compressed int uPos = uncompressed.position(); int uLen = uncompressed.remaining(); int compressedSize = SnappyNative.rawCompress(uncompressed, uPos, uLen, compressed, compressed.position()); // pos limit // [ ......BBBBBBB.........] compressed.limit(compressed.position() + compressedSize); return compressedSize; } public static byte[] compress(char[] input) { - return rawCompress(input, input.length * 2); // short uses 2 bytes + return rawCompress(input, input.length * 2); // char uses 2 bytes } public static byte[] compress(double[] input) { return rawCompress(input, input.length * 8); // double uses 8 bytes } public static byte[] compress(float[] input) { return rawCompress(input, input.length * 4); // float uses 4 bytes } public static byte[] compress(int[] input) { return rawCompress(input, input.length * 4); // int uses 4 bytes } public static byte[] compress(long[] input) { return rawCompress(input, input.length * 8); // long uses 8 bytes } public static byte[] compress(short[] input) { return rawCompress(input, input.length * 2); // short uses 2 bytes } public static byte[] compress(String s) throws SnappyException { try { return compress(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 encoder is not found"); } } public static byte[] compress(String s, String encoding) throws UnsupportedEncodingException, SnappyException { byte[] data = s.getBytes(encoding); return compress(data); } /** * Get the native library version of the snappy * * @return native library version */ public static String getNativeLibraryVersion() { return SnappyNative.nativeLibraryVersion(); } /** * Returns true iff the contents of compressed buffer [offset, * offset+length) can be uncompressed successfully. Does not return the * uncompressed data. Takes time proportional to the input length, but is * usually at least a factor of four faster than actual decompression. */ public static boolean isValidCompressedBuffer(byte[] input, int offset, int length) throws SnappyException { if (input == null) throw new NullPointerException("input is null"); return SnappyNative.isValidCompressedBuffer(input, offset, length); } /** * Returns true iff the contents of compressed buffer [pos() ... limit()) * can be uncompressed successfully. Does not return the uncompressed data. * Takes time proportional to the input length, but is usually at least a * factor of four faster than actual decompression. */ public static boolean isValidCompressedBuffer(ByteBuffer compressed) throws SnappyException { return SnappyNative.isValidCompressedBuffer(compressed, compressed.position(), compressed.remaining()); } /** * Get the maximum byte size needed for compressing data of the given byte * size. * * @param byteSize * byte size of the data to compress * @return maximum byte size of the compressed data */ public static int maxCompressedLength(int byteSize) { return SnappyNative.maxCompressedLength(byteSize); } /** * Compress the input data and produce a byte array of the uncompressed data * * @param data * input array. The input MUST be an array type * @param byteSize * the input byte size * @return compressed data */ public static byte[] rawCompress(Object data, int byteSize) { byte[] buf = new byte[Snappy.maxCompressedLength(byteSize)]; int compressedByteSize = SnappyNative.rawCompress(data, 0, byteSize, buf, 0); byte[] result = new byte[compressedByteSize]; System.arraycopy(buf, 0, result, 0, compressedByteSize); return result; } /** * Compress the input buffer [offset,... ,offset+length) contents, then * write the compressed data to the output buffer[offset, ...) * * @param input * input array. This MUST be primitive array type * @param inputOffset * byte offset at the output array * @param inputLength * byte length of the input data * @param output * output array. This MUST be primitive array type * @param outputOffset * byte offset at the output array * @return byte size of the compressed data * @throws SnappyException */ public static int rawCompress(Object input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws SnappyException { if (input == null || output == null) throw new NullPointerException("input or output is null"); int compressedSize = SnappyNative.rawCompress(input, inputOffset, inputLength, output, outputOffset); return compressedSize; } /** * Uncompress the content in the input buffer. The uncompressed data is * written to the output buffer. * * Note that if you pass the wrong data or the range [inputOffset, * inputOffset + inputLength) that cannot be uncompressed, your JVM might * crash due to the access violation exception issued in the native code * written in C++. To avoid this type of crash, use * {@link #isValidCompressedBuffer(byte[], int, int)} first. * * @param input * input byte array * @param inputOffset * byte offset * @param inputLength * byte length of the input data * @param output * output buffer, MUST be a primitive type array * @param outputOffset * byte offset * @return the byte size of the uncompressed data * @throws SnappyException */ public static int rawUncompress(byte[] input, int inputOffset, int inputLength, Object output, int outputOffset) throws SnappyException { if (input == null || output == null) throw new NullPointerException("input or output is null"); return SnappyNative.rawUncompress(input, inputOffset, inputLength, output, outputOffset); } /** * High-level API for uncompressing the input byte array. * * @param input * @return the uncompressed byte array * @throws SnappyException */ public static byte[] uncompress(byte[] input) throws SnappyException { byte[] result = new byte[Snappy.uncompressedLength(input)]; int byteSize = Snappy.uncompress(input, 0, input.length, result, 0); return result; } /** * Uncompress the content in the input buffer. The uncompressed data is * written to the output buffer. * * Note that if you pass the wrong data or the range [inputOffset, * inputOffset + inputLength) that cannot be uncompressed, your JVM might * crash due to the access violation exception issued in the native code * written in C++. To avoid this type of crash, use * {@link #isValidCompressedBuffer(byte[], int, int)} first. * * @param input * @param inputOffset * @param inputLength * @param output * @param outputOffset * @return the byte size of the uncompressed data * @throws SnappyException */ public static int uncompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws SnappyException { return rawUncompress(input, inputOffset, inputLength, output, outputOffset); } /** * Uncompress the content in the input buffer. The result is dumped to the * specified output buffer. * * Note that if you pass the wrong data or the range [pos(), limit()) that * cannot be uncompressed, your JVM might crash due to the access violation * exception issued in the native code written in C++. To avoid this type of * crash, use {@link #isValidCompressedBuffer(ByteBuffer)} first. * * * @param compressed * buffer[pos() ... limit()) containing the input data * @param uncompressed * output of the the uncompressed data. It uses buffer[pot()..] * @return uncompressed data size * * @throws SnappyException * when failed to uncompress the given input * @throws SnappyError * when the input is not a direct buffer */ public static int uncompress(ByteBuffer compressed, ByteBuffer uncompressed) throws SnappyException { if (!compressed.isDirect()) throw new SnappyError(SnappyErrorCode.NOT_A_DIRECT_BUFFER, "input is not a direct buffer"); if (!uncompressed.isDirect()) throw new SnappyError(SnappyErrorCode.NOT_A_DIRECT_BUFFER, "destination is not a direct buffer"); int cPos = compressed.position(); int cLen = compressed.remaining(); // pos limit // [ ......UUUUUU.........] int decompressedSize = SnappyNative .rawUncompress(compressed, cPos, cLen, uncompressed, uncompressed.position()); uncompressed.limit(uncompressed.position() + decompressedSize); return decompressedSize; } public static char[] uncompressCharArray(byte[] input) throws SnappyException { return uncompressCharArray(input, 0, input.length); } public static char[] uncompressCharArray(byte[] input, int offset, int length) throws SnappyException { int uncompressedLength = Snappy.uncompressedLength(input, offset, length); char[] result = new char[uncompressedLength / 2]; int byteSize = SnappyNative.rawUncompress(input, offset, length, result, 0); return result; } public static double[] uncompressDoubleArray(byte[] input) throws SnappyException { int uncompressedLength = Snappy.uncompressedLength(input, 0, input.length); double[] result = new double[uncompressedLength / 8]; int byteSize = SnappyNative.rawUncompress(input, 0, input.length, result, 0); return result; } /** * Get the uncompressed byte size of the given compressed input. This * operation takes O(1) time. * * @param input * @return umcompressed byte size of the the given input data * @throws SnappyException * when failed to uncompress the given input. The error code is * {@link SnappyErrorCode#PARSING_ERROR} */ public static int uncompressedLength(byte[] input) throws SnappyException { return SnappyNative.uncompressedLength(input, 0, input.length); } /** * Get the uncompressed byte size of the given compressed input. This * operation takes O(1) time. * * @param input * @param offset * @param length * @return umcompressed byte size of the the given input data * @throws SnappyException * when failed to uncompress the given input. The error code is * {@link SnappyErrorCode#PARSING_ERROR} */ public static int uncompressedLength(byte[] input, int offset, int length) throws SnappyException { if (input == null) throw new NullPointerException("input is null"); return SnappyNative.uncompressedLength(input, offset, length); } public static class CompressedDataLength { public final int cursor; public final int uncompressedLength; public CompressedDataLength(int cursor, int uncompressedLength) { this.cursor = cursor; this.uncompressedLength = uncompressedLength; } } public static CompressedDataLength getUncompressedLength(byte[] input, int offset, int limit) throws SnappyException { if (input == null) throw new NullPointerException("input is null"); long b = 0; long result = 0; int cursor = offset; if (cursor >= limit) return null; for (;;) { b = input[cursor++]; result = b & 127; if (b < 128) break; if (cursor >= limit) return null; b = input[cursor++]; result |= (b & 127) << 7; if (b < 128) break; if (cursor >= limit) return null; b = input[cursor++]; result |= (b & 127) << 14; if (b < 128) break; if (cursor >= limit) return null; b = input[cursor++]; result |= (b & 127) << 21; if (b < 128) break; if (cursor >= limit) return null; b = input[cursor++]; result |= (b & 127) << 28; if (b < 16) break; return null; // Value is too long to be a varint32 } if (result > Integer.MAX_VALUE) throw new IllegalStateException("cannot uncompress byte array longer than 2^31-1: " + result); return new CompressedDataLength(cursor, (int) result); } /** * Get the uncompressed byte size of the given compressed input. This * operation taks O(1) time. * * @param compressed * input data [pos() ... limit()) * @return uncompressed byte length of the given input * @throws SnappyException * when failed to uncompress the given input. The error code is * {@link SnappyErrorCode#PARSING_ERROR} * @throws SnappyError * when the input is not a direct buffer */ public static int uncompressedLength(ByteBuffer compressed) throws SnappyException { if (!compressed.isDirect()) throw new SnappyError(SnappyErrorCode.NOT_A_DIRECT_BUFFER, "input is not a direct buffer"); return SnappyNative.uncompressedLength(compressed, compressed.position(), compressed.remaining()); } public static float[] uncompressFloatArray(byte[] input) throws SnappyException { return uncompressFloatArray(input, 0, input.length); } public static float[] uncompressFloatArray(byte[] input, int offset, int length) throws SnappyException { int uncompressedLength = Snappy.uncompressedLength(input, offset, length); float[] result = new float[uncompressedLength / 4]; int byteSize = SnappyNative.rawUncompress(input, offset, length, result, 0); return result; } public static int[] uncompressIntArray(byte[] input) throws SnappyException { return uncompressIntArray(input, 0, input.length); } public static int[] uncompressIntArray(byte[] input, int offset, int length) throws SnappyException { int uncompressedLength = Snappy.uncompressedLength(input, offset, length); int[] result = new int[uncompressedLength / 4]; int byteSize = SnappyNative.rawUncompress(input, offset, length, result, 0); return result; } public static long[] uncompressLongArray(byte[] input) throws SnappyException { return uncompressLongArray(input, 0, input.length); } public static long[] uncompressLongArray(byte[] input, int offset, int length) throws SnappyException { int uncompressedLength = Snappy.uncompressedLength(input, offset, length); long[] result = new long[uncompressedLength / 8]; int byteSize = SnappyNative.rawUncompress(input, offset, length, result, 0); return result; } public static short[] uncompressShortArray(byte[] input) throws SnappyException { return uncompressShortArray(input, 0, input.length); } public static short[] uncompressShortArray(byte[] input, int offset, int length) throws SnappyException { int uncompressedLength = Snappy.uncompressedLength(input, offset, length); short[] result = new short[uncompressedLength / 2]; int byteSize = SnappyNative.rawUncompress(input, offset, length, result, 0); return result; } public static String uncompressString(byte[] input) throws SnappyException { try { return uncompressString(input, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 decoder is not found"); } } public static String uncompressString(byte[] input, int offset, int length) throws SnappyException { try { return uncompressString(input, offset, length, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 decoder is not found"); } } public static String uncompressString(byte[] input, int offset, int length, String encoding) throws SnappyException, UnsupportedEncodingException { byte[] uncompressed = new byte[uncompressedLength(input, offset, length)]; int compressedSize = uncompress(input, offset, length, uncompressed, 0); return new String(uncompressed, encoding); } public static String uncompressString(byte[] input, String encoding) throws SnappyException, UnsupportedEncodingException { byte[] uncompressed = uncompress(input); return new String(uncompressed, encoding); } }
true
false
null
null
diff --git a/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryResult.java b/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryResult.java index aea3cdc93..c1977a491 100644 --- a/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryResult.java +++ b/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryResult.java @@ -1,280 +1,280 @@ package ae3.service.structuredquery; import ae3.model.AtlasGene; import ae3.model.ListResultRow; import ae3.restresult.RestOut; import uk.ac.ebi.gxa.utils.MappingIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * Atlas structured query result container class * @author pashky */ public class AtlasStructuredQueryResult { protected final Logger log = LoggerFactory.getLogger(getClass()); private EfvTree<Integer> resultEfvs; private EfoTree<Integer> resultEfos; private Collection<StructuredResultRow> results; private Map<AtlasGene,List<ListResultRow>> listResults; private Iterable<ExpFactorResultCondition> conditions; private Set<String> expandableEfs; private long total; private long start; private long rowsPerPage; private int rowsPerGene; private EfvTree<FacetUpDn> efvFacet; private Map<String,Iterable<FacetCounter>> geneFacets; private boolean hasEFOExpansion = false; /** * Constructor * @param start starting position in paging * @param rowsPerPage number of rows in page */ public AtlasStructuredQueryResult(long start, long rowsPerPage, int expsPerGene) { this.results = new ArrayList<StructuredResultRow>(); - this.listResults = new HashMap<AtlasGene,List<ListResultRow>>(); + this.listResults = new LinkedHashMap<AtlasGene,List<ListResultRow>>(); this.geneFacets = new HashMap<String, Iterable<FacetCounter>>(); this.start = start; this.rowsPerPage = rowsPerPage; this.rowsPerGene = expsPerGene; } /** * Adds result to list * @param result result to add */ public void addResult(StructuredResultRow result) { results.add(result); } /** * Returns number of results * @return number of results in result list */ @RestOut(name="numberOfResultGenes") public int getSize() { return results.size(); } /** * Return iterable results * @return iterable results */ public Iterable<StructuredResultRow> getResults() { return results; } public EfoTree<Integer> getResultEfos() { return resultEfos; } public void setResultEfos(EfoTree<Integer> resultEfos) { this.resultEfos = resultEfos; } /** * Returns sorted list of atlas list view results sorted by number of studies and p-value * @return */ public List<ListResultRow> getListResults() { List<ListResultRow> allRows = new ArrayList<ListResultRow>(); for(List<ListResultRow> rows : listResults.values()) allRows.addAll(rows); Collections.sort(allRows,Collections.reverseOrder()); return allRows; } /** * Adds listResult to list * @param listRow to add */ public void addListResult(ListResultRow listRow) { List<ListResultRow> list = listResults.get(listRow.getGene()); if(list == null) listResults.put(listRow.getGene(), list = new ArrayList<ListResultRow>()); list.add(listRow); } public static class ListResultGene { private List<ListResultRow> rows; public ListResultGene(List<ListResultRow> rows) { this.rows = rows; } public AtlasGene getGene() { return rows.get(0).getGene(); } public List<ListResultRow> getExpressions() { return rows; } } @RestOut(name="genes") public Iterable<ListResultGene> getListResultsGenes() { return new Iterable<ListResultGene>() { public Iterator<ListResultGene> iterator() { return new MappingIterator<List<ListResultRow>, ListResultGene>(listResults.values().iterator()) { public ListResultGene map(List<ListResultRow> listResultRows) { return new ListResultGene(listResultRows); } }; } }; } /** * Set results EFVs tree * @param resultEfvs result EFVs tree */ public void setResultEfvs(EfvTree<Integer> resultEfvs) { this.resultEfvs = resultEfvs; } /** * Returns result EFVs tree * @return */ public EfvTree<Integer> getResultEfvs() { return resultEfvs; } /** * Returns results current page number * @return page number */ public long getPage() { return getStart() / getRowsPerPage(); } /** * Returns results start position in paging * @return start position */ @RestOut(name="startingFrom") public long getStart() { return start; } /** * Returns total number of results * @return total number of results */ @RestOut(name="totalResultGenes") public long getTotal() { return total; } /** * Returns number of rows in page * @return number of rows in page */ public long getRowsPerPage() { return rowsPerPage; } /** * Returns number of rows (Factor values) allowed to show in list view per gene * @return */ public int getRowsPerGene() { return rowsPerGene; } public void setRowsPerGene(int listRowsPerGene) { this.rowsPerGene = listRowsPerGene; } /** * Sets total number of results * @param total total number of results */ public void setTotal(long total) { this.total = total; } /** * Sets EFV facet tree * @param efvFacet tree of EFVs with {@link FacetUpDn} objects as payload */ public void setEfvFacet(EfvTree<FacetUpDn> efvFacet) { this.efvFacet = efvFacet; } /** * Returns EFV facet tree * @return tree of EFVs with {@link ae3.service.structuredquery.FacetUpDn} objects as payload */ public EfvTree<FacetUpDn> getEfvFacet() { return efvFacet; } /** * Returns map of gene facets * @return map of string to iterable list of {@link ae3.service.structuredquery.FacetCounter} objects */ public Map<String,Iterable<FacetCounter>> getGeneFacets() { return geneFacets; } /** * Returns one gene facet by name * @param name facet name to get * @return iterable list of {@link ae3.service.structuredquery.FacetCounter} objects */ public Iterable<FacetCounter> getGeneFacet(String name) { return geneFacets.get(name); } /** * Sets gene facet by name * @param name gene facet name * @param facet iterable list of {@link ae3.service.structuredquery.FacetCounter} objects */ public void setGeneFacet(String name, Iterable<FacetCounter> facet) { this.geneFacets.put(name, facet); } /** * Returns query result condition * @return iterable list of conditions */ public Iterable<ExpFactorResultCondition> getConditions() { return conditions; } /** * Sets list of query result conditions * @param conditions iterable list of conditions */ public void setConditions(Iterable<ExpFactorResultCondition> conditions) { this.conditions = conditions; } /** * Returns set of EFs collapsed by heatmap trimming function and available for expansion * @return set of strings representing EF names */ public Set<String> getExpandableEfs() { return expandableEfs; } /** * Sets set of EFs collapsed by heatmap trimming function and available for expansion * @param expandableEfs collection of strings */ public void setExpandableEfs(Collection<String> expandableEfs) { this.expandableEfs = new HashSet<String>(); this.expandableEfs.addAll(expandableEfs); } public boolean isHasEFOExpansion() { return hasEFOExpansion; } public void setHasEFOExpansion(boolean hasEFOExpansion) { this.hasEFOExpansion = hasEFOExpansion; } }
true
false
null
null
diff --git a/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/event/moveitem/BeforeMoveItemsEvent.java b/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/event/moveitem/BeforeMoveItemsEvent.java index af66012f4..26c328795 100644 --- a/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/event/moveitem/BeforeMoveItemsEvent.java +++ b/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/event/moveitem/BeforeMoveItemsEvent.java @@ -1,126 +1,123 @@ /* * Copyright 2009 Sysmap Solutions Software e Consultoria Ltda. * * 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 br.com.sysmap.crux.widgets.client.event.moveitem; import java.util.List; import br.com.sysmap.crux.widgets.client.transferlist.TransferList.Item; -import br.com.sysmap.crux.widgets.client.transferlist.TransferList.ItemLocation; import com.google.gwt.event.shared.GwtEvent; /** * Event fired by TransferList widget before its items are moved across the lists * @author Gess� S. F. Daf� */ public class BeforeMoveItemsEvent extends GwtEvent<BeforeMoveItemsHandler>{ private static Type<BeforeMoveItemsHandler> TYPE = new Type<BeforeMoveItemsHandler>(); private HasBeforeMoveItemsHandlers source; private List<Item> items; private boolean canceled; + private boolean leftToRight; /** * Constructor */ - public BeforeMoveItemsEvent(HasBeforeMoveItemsHandlers source, List<Item> items) + private BeforeMoveItemsEvent(HasBeforeMoveItemsHandlers source, List<Item> items, boolean leftToRight) { this.source = source; this.items = items; + this.leftToRight = leftToRight; } /** * @return the source */ public HasBeforeMoveItemsHandlers getSource() { return source; } /** * @return */ public static Type<BeforeMoveItemsHandler> getType() { return TYPE; } @Override protected void dispatch(BeforeMoveItemsHandler handler) { handler.onBeforeMoveItems(this); } @Override public Type<BeforeMoveItemsHandler> getAssociatedType() { return TYPE; } - public static BeforeMoveItemsEvent fire(HasBeforeMoveItemsHandlers source, List<Item> items) + public static BeforeMoveItemsEvent fire(HasBeforeMoveItemsHandlers source, List<Item> items, boolean leftToRight) { - BeforeMoveItemsEvent event = new BeforeMoveItemsEvent(source, items); + BeforeMoveItemsEvent event = new BeforeMoveItemsEvent(source, items, leftToRight); source.fireEvent(event); return event; } /** * @return the row */ public List<Item> getItems() { return items; } /** * @return the canceled */ public boolean isCanceled() { return canceled; } /** * @param canceled the canceled to set */ public void cancel() { this.canceled = true; } /** * Return true if selected items are being moved from left to right list * @return */ public boolean isMovingToRight() { - boolean existsItems = this.items != null && this.items.size() > 0; - boolean itemsAreFromLeft = existsItems && ItemLocation.left.equals(this.items.get(0).getLocation()); - return itemsAreFromLeft; + return leftToRight; } /** * Return true if selected items are being moved from right to left list * @return */ public boolean isMovingToLeft() { - boolean existsItems = this.items != null && this.items.size() > 0; - boolean itemsAreFromRight = existsItems && ItemLocation.right.equals(this.items.get(0).getLocation()); - return itemsAreFromRight; + return !leftToRight; } } \ No newline at end of file diff --git a/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/transferlist/TransferList.java b/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/transferlist/TransferList.java index e6eefb362..186b04aff 100644 --- a/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/transferlist/TransferList.java +++ b/trunk/CruxWidgets/src/br/com/sysmap/crux/widgets/client/transferlist/TransferList.java @@ -1,465 +1,465 @@ /* * Copyright 2009 Sysmap Solutions Software e Consultoria Ltda. * * 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 br.com.sysmap.crux.widgets.client.transferlist; import java.util.ArrayList; import java.util.List; import br.com.sysmap.crux.widgets.client.event.moveitem.HasBeforeMoveItemsHandlers; import br.com.sysmap.crux.widgets.client.event.moveitem.BeforeMoveItemsEvent; import br.com.sysmap.crux.widgets.client.event.moveitem.BeforeMoveItemsHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * A decorated panel, with a title bar. * @author Gess� S. F. Daf� */ public class TransferList extends Composite implements HasBeforeMoveItemsHandlers { public static final String DEFAULT_STYLE_NAME = "crux-TransferList" ; private HorizontalPanel panel; private ListBox leftList; private ListBox rightList; private Button moveToRightButton; private Button moveToLeftButton; private Label leftListLabel; private Label rightListLabel; private boolean multiTransferFromLeft = true; private boolean multiTransferFromRight = true; /** * TODO - Gess� - Comment this * @author Gess� S. F. Daf� */ public static enum ItemLocation { left, right; } /** * TODO - Gess� - Comment this * @author Gess� S. F. Daf� */ public static class Item { private String label; private String value; private ItemLocation location; /** * @param label * @param value */ public Item(String label, String value) { this(label, value, ItemLocation.left); } /** * @param label * @param value * @param location */ public Item(String label, String value, ItemLocation location) { this.label = label; this.value = value; this.location = location; } /** * @return the label */ public String getLabel() { return label; } /** * @return the value */ public String getValue() { return value; } /** * @return the location */ public ItemLocation getLocation() { return location; } } /** * @param width * @param height * @param styleName */ public TransferList() { super(); this.panel = createPanelCells(); initWidget(panel); } /** * @param panel2 */ private HorizontalPanel createPanelCells() { HorizontalPanel panel = new HorizontalPanel(); panel.setStyleName(DEFAULT_STYLE_NAME); VerticalPanel vPanelLeft = new VerticalPanel(); this.leftListLabel = new Label(); this.leftList = new ListBox(this.multiTransferFromLeft); this.leftList.setStyleName("leftList"); vPanelLeft.add(this.leftListLabel); vPanelLeft.add(this.leftList); panel.add(vPanelLeft); VerticalPanel commandsPanel = createCommands(); panel.add(commandsPanel); panel.setCellVerticalAlignment(commandsPanel, HasVerticalAlignment.ALIGN_MIDDLE); VerticalPanel vPanelRight = new VerticalPanel(); this.rightListLabel = new Label(); this.rightList = new ListBox(this.multiTransferFromRight); this.rightList.setStyleName("rightList"); vPanelRight.add(this.rightListLabel); vPanelRight.add(this.rightList); panel.add(vPanelRight); return panel; } /** * @return */ private VerticalPanel createCommands() { VerticalPanel commandsPanel = new VerticalPanel(); commandsPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); commandsPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); commandsPanel.setStyleName("commands"); commandsPanel.setSpacing(5); this.moveToRightButton = new Button(); moveToRightButton.setStyleName("moveToRight"); moveToRightButton.addClickHandler(new TransferItemClickHandler(this, true)); commandsPanel.add(this.moveToRightButton); this.moveToLeftButton = new Button(); moveToLeftButton.setStyleName("moveToLeft"); moveToLeftButton.addClickHandler(new TransferItemClickHandler(this, false)); commandsPanel.add(this.moveToLeftButton); return commandsPanel; } /** * @return the moveToRightButton */ public Button getMoveToRightButton() { return moveToRightButton; } /** * @return the moveToLeftButton */ public Button getMoveToLeftButton() { return moveToLeftButton; } /** * @return the leftList */ protected ListBox getLeftList() { return leftList; } /** * @return the rightList */ protected ListBox getRightList() { return rightList; } /** * @param text */ public void setLeftToRightButtonText(String text) { this.moveToRightButton.setText(text); } /** * @param text */ public void setRightToLeftButtonText(String text) { this.moveToLeftButton.setText(text); } /** * @param label */ public void setLeftListLabel(String label) { this.leftListLabel.setText(label); } /** * @param label */ public void setRightListLabel(String label) { this.rightListLabel.setText(label); } /** * Sets the items to be shown */ public void setCollection(List<Item> items) { this.leftList.clear(); this.rightList.clear(); for (Item item : items) { if(item.location.equals(ItemLocation.left)) { leftList.addItem(item.getLabel(), item.getValue()); } else { rightList.addItem(item.getLabel(), item.getValue()); } } } /** * @param parseInt */ public void setVisibleItemCount(int count) { this.leftList.setVisibleItemCount(count); this.rightList.setVisibleItemCount(count); } /** * @return */ public List<Item> getLeftItens() { return getItens(getLeftList(), true); } /** * @return */ public List<Item> getRightItens() { return getItens(getRightList(), false); } /** * @param listBox * @param left * @return */ private List<Item> getItens(ListBox listBox, boolean left) { List<Item> items = new ArrayList<Item>(); for(int i = 0; i < listBox.getItemCount(); i++) { Item item = new Item( listBox.getItemText(i), listBox.getValue(i), left ? ItemLocation.left : ItemLocation.right ); items.add(item); } return items; } /** * @see br.com.sysmap.crux.widgets.client.event.moveitem.HasBeforeMoveItemsHandlers#addBeforeMoveItemsHandler(br.com.sysmap.crux.widgets.client.event.moveitem.BeforeMoveItemsHandler) */ public HandlerRegistration addBeforeMoveItemsHandler(BeforeMoveItemsHandler handler) { return addHandler(handler, BeforeMoveItemsEvent.getType()); } /** * Click handler for transfer list buttons * @author Gess� S. F. Daf� */ private static class TransferItemClickHandler implements ClickHandler { private TransferList transferList; private boolean leftToRight; /** * @param transfer * @param leftToRight */ public TransferItemClickHandler(TransferList transfer, boolean leftToRight) { this.transferList = transfer; this.leftToRight = leftToRight; } /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { ListBox listToRemove = leftToRight ? transferList.getLeftList() : transferList.getRightList(); ListBox listToAdd = leftToRight ? transferList.getRightList() : transferList.getLeftList(); List<String[]> move = new ArrayList<String[]>(); List<String[]> keep = new ArrayList<String[]>(); for (int i = 0; i < listToRemove.getItemCount(); i++) { String text = listToRemove.getItemText(i); String value = listToRemove.getValue(i); String[] item = new String[]{text, value}; if(listToRemove.isItemSelected(i)) { move.add(item); } else { keep.add(item); } } ItemLocation itemsLocation = leftToRight ? ItemLocation.left : ItemLocation.right; List<Item> itemsForEvet = createItemList(move, itemsLocation); - BeforeMoveItemsEvent moveEvt = BeforeMoveItemsEvent.fire(transferList, itemsForEvet); + BeforeMoveItemsEvent moveEvt = BeforeMoveItemsEvent.fire(transferList, itemsForEvet, leftToRight); if(!moveEvt.isCanceled()) { listToRemove.clear(); for (String[] item : move) { listToAdd.addItem(item[0], item[1]); } for (String[] item : keep) { listToRemove.addItem(item[0], item[1]); } } } /** * Creates a list of Item from a list of string[] containing labels and values * @param arrays * @param location * @return */ private List<Item> createItemList(List<String[]> arrays, ItemLocation location) { List<Item> items = new ArrayList<Item>(); for (String[] array : arrays) { Item item = new Item(array[0], array[1], location); items.add(item); } return items; } } /** * @return the multiTransferFromLeft */ public boolean isMultiTransferFromLeft() { return multiTransferFromLeft; } /** * @param multiTransferFromLeft the multiTransferFromLeft to set */ @SuppressWarnings("deprecation") public void setMultiTransferFromLeft(boolean multiTransferFromLeft) { this.multiTransferFromLeft = multiTransferFromLeft; clearListSelections(this.leftList); this.leftList.setMultipleSelect(this.multiTransferFromLeft); } /** * @return the multiTransferFromRight */ public boolean isMultiTransferFromRight() { return multiTransferFromRight; } /** * @param multiTransferFromRight the multiTransferFromRight to set */ @SuppressWarnings("deprecation") public void setMultiTransferFromRight(boolean multiTransferFromRight) { this.multiTransferFromRight = multiTransferFromRight; clearListSelections(this.rightList); this.rightList.setMultipleSelect(this.multiTransferFromRight); } /** * Clears the selections made in a listBox. * @param list */ private void clearListSelections(ListBox list) { int count = list.getItemCount(); for(int i = 0; i < count; i++) { list.setItemSelected(i, false); } } } \ No newline at end of file
false
false
null
null
diff --git a/src/de/raptor2101/GalDroid/Activities/Views/ImageInformationView.java b/src/de/raptor2101/GalDroid/Activities/Views/ImageInformationView.java index 822989c..4f0ae07 100644 --- a/src/de/raptor2101/GalDroid/Activities/Views/ImageInformationView.java +++ b/src/de/raptor2101/GalDroid/Activities/Views/ImageInformationView.java @@ -1,302 +1,313 @@ package de.raptor2101.GalDroid.Activities.Views; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutionException; import de.raptor2101.GalDroid.R; import de.raptor2101.GalDroid.Activities.GalDroidApp; import de.raptor2101.GalDroid.Activities.Listeners.CommentLoaderListener; import de.raptor2101.GalDroid.Activities.Listeners.TagLoaderListener; import de.raptor2101.GalDroid.WebGallery.GalleryCache; import de.raptor2101.GalDroid.WebGallery.GalleryImageView; import de.raptor2101.GalDroid.WebGallery.Interfaces.GalleryObject; import de.raptor2101.GalDroid.WebGallery.Interfaces.WebGallery; import de.raptor2101.GalDroid.WebGallery.Tasks.CommentLoaderTask; import de.raptor2101.GalDroid.WebGallery.Tasks.ImageLoaderTask; import de.raptor2101.GalDroid.WebGallery.Tasks.TagLoaderTask; import android.content.Context; import android.media.ExifInterface; import android.os.AsyncTask; import android.os.AsyncTask.Status; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TableLayout; import android.widget.TextView; public class ImageInformationView extends TableLayout { private final static String ClassTag = "ImageInformationView"; public class ExtractInformationTask extends AsyncTask<Void,Void,Void> { private GalleryImageView mGalleryImageView; public ExtractInformationTask(GalleryImageView imageView) { mGalleryImageView = imageView; } @Override protected Void doInBackground(Void... params) { if(!mGalleryImageView.isLoaded()) { ImageLoaderTask task = mGalleryImageView.getImageLoaderTask(); if(task!=null) { try { task.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; } @Override protected void onPostExecute(Void result) { if(mGalleryImageView.isLoaded()) { extractObjectInformation(mGalleryImageView.getGalleryObject()); } } } private TagLoaderListener mTagLoaderListener; private CommentLoaderListener mCommentLoaderListener; private TagLoaderTask mTagLoaderTask; private CommentLoaderTask mCommentLoaderTask; private ExtractInformationTask mExtractTask; private GalleryImageView mCurrentImageView; public ImageInformationView(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public ImageInformationView(Context context) { super(context); initialize(); } public void setGalleryImageView(GalleryImageView imageView) { mCurrentImageView = imageView; if(getVisibility() == VISIBLE) { executeExtrationTask(); } } @Override public void setVisibility(int visibility) { if(visibility == VISIBLE) { executeExtrationTask(); } super.setVisibility(visibility); } private void executeExtrationTask() { - clearImageInformations(); - mExtractTask = new ExtractInformationTask(mCurrentImageView); - mExtractTask.execute(); + if (mCurrentImageView != null) { + clearImageInformations(); + mExtractTask = new ExtractInformationTask(mCurrentImageView); + mExtractTask.execute(); + } } private void initialize(){ LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.image_information_view, this); mTagLoaderListener = new TagLoaderListener((TextView)findViewById(R.id.textTags), (ProgressBar)findViewById(R.id.progressBarTags)); mCommentLoaderListener = new CommentLoaderListener((ViewGroup)findViewById(R.id.layoutComments), (ProgressBar)findViewById(R.id.progressBarComments)); } private void clearImageInformations() { TextView textView = (TextView) findViewById(R.id.textTitle); textView.setText(""); textView = (TextView) findViewById(R.id.textTags); textView.setText(""); textView = (TextView) findViewById(R.id.textUploadDate); textView.setText(""); textView = (TextView) findViewById(R.id.textExifCreateDate); textView.setText(""); textView = (TextView) findViewById(R.id.textExifAperture); textView.setText(""); textView = (TextView) findViewById(R.id.textExifExposure); textView.setText(""); textView = (TextView) findViewById(R.id.textExifFlash); textView.setText(""); textView = (TextView) findViewById(R.id.textExifISO); textView.setText(""); textView = (TextView) findViewById(R.id.textExifModel); textView.setText(""); textView = (TextView) findViewById(R.id.textExifModel); textView.setText(""); textView = (TextView) findViewById(R.id.textExifMake); textView.setText(""); textView = (TextView) findViewById(R.id.textExifFocalLength); textView.setText(""); textView = (TextView) findViewById(R.id.textExifWhiteBalance); textView.setText(""); textView = (TextView) findViewById(R.id.textGeoLat); textView.setText(""); textView = (TextView) findViewById(R.id.textGeoLong); textView.setText(""); textView = (TextView) findViewById(R.id.textGeoHeight); textView.setText(""); } private void extractObjectInformation(GalleryObject galleryObject) { GalDroidApp app = (GalDroidApp) getContext().getApplicationContext(); WebGallery webGallery = app.getWebGallery(); GalleryCache galleryCache = app.getGalleryCache(); TextView textTitle = (TextView) findViewById(R.id.textTitle); TextView textUploadDate = (TextView) findViewById(R.id.textUploadDate); textTitle.setText(galleryObject.getTitle()); textUploadDate.setText(galleryObject.getDateUploaded().toLocaleString()); if(mTagLoaderTask != null && (mTagLoaderTask.getStatus() == Status.RUNNING || mTagLoaderTask.getStatus() == Status.PENDING)) { Log.d(ClassTag, "Aborting TagLoaderTask"); mTagLoaderTask.cancel(true); } if(mCommentLoaderTask != null && (mCommentLoaderTask.getStatus() == Status.RUNNING || mCommentLoaderTask.getStatus() == Status.PENDING)) { Log.d(ClassTag, "Aborting CommentLoaderTask"); mCommentLoaderTask.cancel(true); } mTagLoaderTask = new TagLoaderTask(webGallery, mTagLoaderListener); mTagLoaderTask.execute(galleryObject); mCommentLoaderTask = new CommentLoaderTask(webGallery, mCommentLoaderListener); mCommentLoaderTask.execute(galleryObject); extractExifInformation(galleryObject, galleryCache); } private void extractExifInformation(GalleryObject galleryObject, GalleryCache galleryCache) { File cachedFile = galleryCache.getFile(galleryObject.getImage().getUniqueId()); + try { ExifInterface exif = new ExifInterface(cachedFile.getAbsolutePath()); TextView textField = (TextView) findViewById(R.id.textExifCreateDate); textField.setText(exif.getAttribute(ExifInterface.TAG_DATETIME)); textField = (TextView) findViewById(R.id.textExifAperture); textField.setText(exif.getAttribute(ExifInterface.TAG_APERTURE)); try { textField = (TextView) findViewById(R.id.textExifExposure); float exposureTime = 1.0f / Float.parseFloat(exif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME)); textField.setText(String.format("1/%.0fs", exposureTime)); } catch (Exception e) { } try { textField = (TextView) findViewById(R.id.textExifFlash); int flash = exif.getAttributeInt(ExifInterface.TAG_FLASH, 0); textField.setText(String.format("%d", flash)); } catch (Exception e) { } textField = (TextView) findViewById(R.id.textExifISO); textField.setText(exif.getAttribute(ExifInterface.TAG_ISO)); textField = (TextView) findViewById(R.id.textExifModel); textField.setText(exif.getAttribute(ExifInterface.TAG_MODEL)); textField = (TextView) findViewById(R.id.textExifModel); textField.setText(exif.getAttribute(ExifInterface.TAG_MODEL)); textField = (TextView) findViewById(R.id.textExifMake); textField.setText(exif.getAttribute(ExifInterface.TAG_MAKE)); try { double focalLength = exif.getAttributeDouble(ExifInterface.TAG_FOCAL_LENGTH, 0); textField = (TextView) findViewById(R.id.textExifFocalLength); textField.setText(String.format("%.0fmm", focalLength)); } catch (Exception e) { } try { textField = (TextView) findViewById(R.id.textExifWhiteBalance); int whiteBalance = exif.getAttributeInt(ExifInterface.TAG_FLASH, 0); if(whiteBalance == ExifInterface.WHITEBALANCE_AUTO) { textField.setText(R.string.object_exif_whitebalance_auto); } else { textField.setText(R.string.object_exif_whitebalance_manual); } } catch (Exception e) { } textField = (TextView) findViewById(R.id.textGeoLat); String latitude = parseDegMinSec(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)); textField.setText(latitude); textField = (TextView) findViewById(R.id.textGeoLong); String longitude = parseDegMinSec(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)); textField.setText(longitude); textField = (TextView) findViewById(R.id.textGeoHeight); String height = exif.getAttribute(ExifInterface.TAG_GPS_ALTITUDE); textField.setText(parseHeight(height)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String parseDegMinSec(String tagGpsValue) { try { String[] values = tagGpsValue.split("[,/]"); float deg = Float.parseFloat(values[0])/Float.parseFloat(values[1]); float min = Float.parseFloat(values[2])/Float.parseFloat(values[3]); float sec = Float.parseFloat(values[4])/Float.parseFloat(values[5]); return String.format("%.0f° %.0f' %.2f\"", deg,min,sec); } catch (Exception e) { return ""; } } private String parseHeight(String tagGpsValue) { try { String[] values = tagGpsValue.split("/"); float height = Float.parseFloat(values[0])/Float.parseFloat(values[1]); return String.format("%.2fm", height); } catch (Exception e) { return ""; } } public ExtractInformationTask getExtractionInfromationTask() { return mExtractTask; } + + public CommentLoaderTask getCommentLoaderTask() { + return mCommentLoaderTask; + } + + public TagLoaderTask getTagLoaderTask() { + return mTagLoaderTask; + } }
false
false
null
null
diff --git a/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdReport.java b/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdReport.java index 817edaf..f85f96b 100644 --- a/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdReport.java +++ b/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdReport.java @@ -1,428 +1,428 @@ package org.apache.maven.plugin.pmd; /* * 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. */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.maven.model.ReportPlugin; import org.apache.maven.project.MavenProject; import org.apache.maven.reporting.AbstractMavenReport; import org.codehaus.doxia.site.renderer.SiteRenderer; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.PathTool; import org.codehaus.plexus.util.StringUtils; /** * Base class for the PMD reports. * * @author <a href="mailto:[email protected]">Brett Porter</a> */ public abstract class AbstractPmdReport extends AbstractMavenReport { /** * The output directory for the intermediate XML report. * * @parameter expression="${project.build.directory}" * @required */ protected File targetDirectory; /** * The output directory for the final HTML report. * * @parameter expression="${project.reporting.outputDirectory}" * @required */ protected String outputDirectory; /** * Site rendering component for generating the HTML report. * * @component */ private SiteRenderer siteRenderer; /** * The project to analyse. * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; /** * Set the output format type, in addition to the HTML report. Must be one of: "none", * "csv", "xml", "txt" or the full class name of the PMD renderer to use. * See the net.sourceforge.pmd.renderers package javadoc for available renderers. * XML is required if the pmd:check goal is being used. * * @parameter expression="${format}" default-value="xml" */ protected String format = "xml"; /** * Link the violation line numbers to the source xref. Links will be created * automatically if the jxr plugin is being used. * * @parameter expression="${linkXRef}" default-value="true" */ private boolean linkXRef; /** * Location of the Xrefs to link to. * * @parameter default-value="${project.reporting.outputDirectory}/xref" */ private File xrefLocation; /** * Location of the Test Xrefs to link to. * * @parameter default-value="${project.reporting.outputDirectory}/xref-test" */ private File xrefTestLocation; /** * A list of files to exclude from checking. Can contain ant-style wildcards and double wildcards. * * @parameter * @since 2.2 */ private String[] excludes; /** * A list of files to include from checking. Can contain ant-style wildcards and double wildcards. * Defaults to **\/*.java * * @since 2.2 * @parameter */ private String[] includes; /** * The source directories containing the sources to be compiled. * * @parameter expression="${project.compileSourceRoots}" * @required * @readonly */ private List compileSourceRoots; /** * The source directories containing the test-sources to be compiled. * * @parameter expression="${project.testCompileSourceRoots}" * @required * @readonly */ private List testSourceRoots; /** * The project source directories that should be excluded. * * @since 2.2 * @parameter */ private List excludeRoots; /** * Run PMD on the tests * * @parameter default-value="false" * @since 2.2 */ protected boolean includeTests; /** * Whether to build an aggregated report at the root, or build individual reports. * * @parameter expression="${aggregate}" default-value="false" * @since 2.2 */ protected boolean aggregate; /** * The projects in the reactor for aggregation report. * * @parameter expression="${reactorProjects}" * @readonly */ protected List reactorProjects; /** * @see org.apache.maven.reporting.AbstractMavenReport#getProject() */ protected MavenProject getProject() { return project; } /** * @see org.apache.maven.reporting.AbstractMavenReport#getSiteRenderer() */ protected SiteRenderer getSiteRenderer() { return siteRenderer; } protected String constructXRefLocation( boolean test ) { String location = null; if ( linkXRef ) { File xrefLoc = test ? xrefTestLocation : xrefLocation; String relativePath = PathTool.getRelativePath( outputDirectory, xrefLoc.getAbsolutePath() ); if ( StringUtils.isEmpty( relativePath ) ) { relativePath = "."; } relativePath = relativePath + "/" + xrefLoc.getName(); if ( xrefLoc.exists() ) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; } else { // Not yet generated - check if the report is on its way for ( Iterator reports = project.getReportPlugins().iterator(); reports.hasNext(); ) { ReportPlugin plugin = (ReportPlugin) reports.next(); String artifactId = plugin.getArtifactId(); if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) { location = relativePath; } } } if ( location == null ) { getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); } } return location; } /** * Convenience method to get the list of files where the PMD tool will be executed * * @return a List of the files where the PMD tool will be executed * @throws java.io.IOException */ protected Map getFilesToProcess( ) throws IOException { String sourceXref = constructXRefLocation( false ); String testXref = includeTests ? constructXRefLocation( true ) : ""; if ( aggregate && !project.isExecutionRoot() ) { return Collections.EMPTY_MAP; } if ( excludeRoots == null ) { excludeRoots = Collections.EMPTY_LIST; } List excludeRootFiles = new ArrayList( excludeRoots.size() ); for ( Iterator it = excludeRoots.iterator(); it.hasNext(); ) { String root = (String) it.next(); File file = new File( root ); if ( file.exists() && file.isDirectory() ) { excludeRootFiles.add( file ); } } List directories = new ArrayList(); for ( Iterator i = compileSourceRoots.iterator(); i.hasNext(); ) { String root = (String) i.next(); File sroot = new File( root ); directories.add( new PmdFileInfo( project, sroot, sourceXref ) ); } if ( includeTests ) { for ( Iterator i = testSourceRoots.iterator(); i.hasNext(); ) { String root = (String) i.next(); File sroot = new File( root ); directories.add( new PmdFileInfo( project, sroot, testXref ) ); } } if ( aggregate ) { for ( Iterator i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject localProject = (MavenProject) i.next(); for ( Iterator i2 = localProject.getCompileSourceRoots().iterator(); i2.hasNext(); ) { String root = (String) i2.next(); File sroot = new File( root ); directories.add( new PmdFileInfo( localProject, sroot, sourceXref ) ); } if ( includeTests ) { for ( Iterator i2 = localProject.getTestCompileSourceRoots().iterator(); i2.hasNext(); ) { String root = (String) i2.next(); File sroot = new File( root ); directories.add( new PmdFileInfo( localProject, sroot, testXref ) ); } } } } String excluding = getIncludeExcludeString( excludes ); String including = getIncludeExcludeString( includes ); Map files = new TreeMap(); if ( "".equals( including ) ) { including = "**/*.java"; } StringBuffer excludesStr = new StringBuffer(); if ( StringUtils.isNotEmpty( excluding ) ) { excludesStr.append( excluding ); } String[] defaultExcludes = FileUtils.getDefaultExcludes(); for ( int i = 0; i < defaultExcludes.length; i++ ) { if ( excludesStr.length() > 0 ) { excludesStr.append( "," ); } excludesStr.append( defaultExcludes[i] ); } getLog().debug( "Excluded files: '" + excludesStr + "'" ); for ( Iterator it = directories.iterator(); it.hasNext(); ) { PmdFileInfo finfo = (PmdFileInfo) it.next(); File sourceDirectory = finfo.getSourceDirectory(); if ( sourceDirectory.exists() && sourceDirectory.isDirectory() && !excludeRootFiles.contains( sourceDirectory ) ) { List newfiles = FileUtils.getFiles( sourceDirectory, including, excludesStr.toString() ); for ( Iterator it2 = newfiles.iterator(); it2.hasNext(); ) { files.put( it2.next(), finfo ); } } } return files; } /** - * Convenience method that concatenates the files to be excluded into the appropriate format + * Convenience method that concatenates the files to be excluded into the appropriate format. * - * @param exclude the array of Strings that contains the files to be excluded - * @return a String that contains the concatenates file names + * @param arr the array of Strings that contains the files to be excluded + * @return a String that contains the concatenated file names */ private String getIncludeExcludeString( String[] arr ) { StringBuffer str = new StringBuffer(); if ( arr != null ) { for ( int index = 0; index < arr.length; index++ ) { if ( str.length() > 0 ) { str.append( ',' ); } str.append( arr[index] ); } } return str.toString(); } protected boolean isHtml() { return "html".equals( format ); } /** * @see org.apache.maven.reporting.AbstractMavenReport#canGenerateReport() */ public boolean canGenerateReport() { if ( aggregate && !project.isExecutionRoot() ) { return false; } // if format is XML, we need to output it even if the file list is empty // so the "check" goals can check for failures if ( "xml".equals( format ) ) { return true; } try { Map filesToProcess = getFilesToProcess( ); if ( filesToProcess.isEmpty() ) { return false; } } catch ( IOException e ) { getLog().error( e ); } return true; } /** * @see org.apache.maven.reporting.AbstractMavenReport#getOutputDirectory() */ protected String getOutputDirectory() { return outputDirectory; } } diff --git a/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdViolationCheckMojo.java b/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdViolationCheckMojo.java index 42bd518..036bcd0 100644 --- a/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdViolationCheckMojo.java +++ b/src/main/java/org/apache/maven/plugin/pmd/AbstractPmdViolationCheckMojo.java @@ -1,300 +1,300 @@ package org.apache.maven.plugin.pmd; /* * 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. */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; 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.xml.pull.MXParser; import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * Base class for mojos that check if there were any PMD violations. * * @author <a href="mailto:[email protected]">Brett Porter</a> */ public abstract class AbstractPmdViolationCheckMojo extends AbstractMojo { private final Boolean FAILURES_KEY = Boolean.TRUE; private final Boolean WARNINGS_KEY = Boolean.FALSE; /** * The location of the XML report to check, as generated by the PMD report. * * @parameter expression="${project.build.directory}" * @required */ private File targetDirectory; /** * Whether to fail the build if the validation check fails. * * @parameter expression="${pmd.failOnViolation}" default-value="true" * @required */ private boolean failOnViolation; /** * The project language, for determining whether to run the report. * * @parameter expression="${project.artifact.artifactHandler.language}" * @required * @readonly */ private String language; /** * Whether to build an aggregated report at the root, or build individual reports. * * @parameter expression="${aggregate}" default-value="false" * @since 2.2 */ protected boolean aggregate; /** * Print details of check failures to build output * * @parameter expression="${pmd.verbose}" default-value="false" */ private boolean verbose; /** * The project to analyse. * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; protected void executeCheck( String filename, String tagName, String key, int failurePriority ) throws MojoFailureException, MojoExecutionException { if ( aggregate && !project.isExecutionRoot() ) { return; } if ( "java".equals( language ) || aggregate ) { File outputFile = new File( targetDirectory, filename ); if ( outputFile.exists() ) { try { XmlPullParser xpp = new MXParser(); FileReader freader = new FileReader( outputFile ); BufferedReader breader = new BufferedReader( freader ); xpp.setInput( breader ); Map violations = getViolations( xpp, tagName, failurePriority ); List failures = (List) violations.get( FAILURES_KEY ); List warnings = (List) violations.get( WARNINGS_KEY ); if ( verbose ) { printErrors( failures, warnings ); } int failureCount = failures.size(); int warningCount = warnings.size(); String message = getMessage( failureCount, warningCount, key, outputFile ); if ( failureCount > 0 && failOnViolation ) { throw new MojoFailureException( message ); } this.getLog().info( message ); } catch ( IOException e ) { throw new MojoExecutionException( "Unable to read PMD results xml: " + outputFile.getAbsolutePath(), e ); } catch ( XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read PMD results xml: " + outputFile.getAbsolutePath(), e ); } } else { throw new MojoFailureException( "Unable to perform check, " + "unable to find " + outputFile ); } } } /** * Method for collecting the violations found by the PMD tool * * @param xpp * the xml parser object * @param tagName * the element that will be checked * @return an int that specifies the number of violations found * @throws XmlPullParserException * @throws IOException */ private Map getViolations( XmlPullParser xpp, String tagName, int failurePriority ) throws XmlPullParserException, IOException { int eventType = xpp.getEventType(); List failures = new ArrayList(); List warnings = new ArrayList(); while ( eventType != XmlPullParser.END_DOCUMENT ) { if ( eventType == XmlPullParser.START_TAG && tagName.equals( xpp.getName() ) ) { Map details = getErrorDetails( xpp ); try { int priority = Integer.parseInt( (String) details.get( "priority" ) ); if ( priority <= failurePriority ) { failures.add( details ); } else { warnings.add( details ); } } catch ( NumberFormatException e ) { // i don't know what priority this is. Treat it like a // failure failures.add( details ); } catch ( NullPointerException e ) { // i don't know what priority this is. Treat it like a // failure failures.add( details ); } } eventType = xpp.next(); } HashMap map = new HashMap( 2 ); map.put( FAILURES_KEY, failures ); map.put( WARNINGS_KEY, warnings ); return map; } /** * Prints the warnings and failures * * @param failures * list of failures * @param warnings * list of warnings */ protected void printErrors( List failures, List warnings ) { Iterator iter = warnings.iterator(); while ( iter.hasNext() ) { printError( (Map) iter.next(), "Warning" ); } iter = failures.iterator(); while ( iter.hasNext() ) { printError( (Map) iter.next(), "Failure" ); } } /** * Gets the output message * - * @param failures - * @param warnings + * @param failureCount + * @param warningCount * @param key * @param outputFile * @return */ private String getMessage( int failureCount, int warningCount, String key, File outputFile ) { StringBuffer message = new StringBuffer(); if ( failureCount > 0 || warningCount > 0 ) { if ( failureCount > 0 ) { message.append( "You have " + failureCount + " " + key + ( failureCount > 1 ? "s" : "" ) ); } if ( warningCount > 0 ) { if ( failureCount > 0 ) { message.append( " and " ); } else { message.append( "You have " ); } message.append( warningCount + " warning" + ( warningCount > 1 ? "s" : "" ) ); } message.append( ". For more details see:" + outputFile.getAbsolutePath() ); } return message.toString(); } /** * Formats the failure details and prints them as an INFO message * * @param item */ abstract protected void printError( Map item, String severity ); /** * Gets the attributes and text for the violation tag and puts them in a * HashMap * * @param xpp * @throws XmlPullParserException * @throws IOException */ abstract protected Map getErrorDetails( XmlPullParser xpp ) throws XmlPullParserException, IOException; }
false
false
null
null
diff --git a/atlassian-plugins-core/src/main/java/com/atlassian/plugin/descriptors/AbstractModuleDescriptor.java b/atlassian-plugins-core/src/main/java/com/atlassian/plugin/descriptors/AbstractModuleDescriptor.java index 95b106ea..3fdac598 100644 --- a/atlassian-plugins-core/src/main/java/com/atlassian/plugin/descriptors/AbstractModuleDescriptor.java +++ b/atlassian-plugins-core/src/main/java/com/atlassian/plugin/descriptors/AbstractModuleDescriptor.java @@ -1,436 +1,436 @@ package com.atlassian.plugin.descriptors; import static com.atlassian.plugin.util.Assertions.notNull; import static com.atlassian.plugin.util.validation.ValidationPattern.createPattern; import static com.atlassian.plugin.util.validation.ValidationPattern.test; import java.util.List; import java.util.Map; import org.apache.commons.lang.Validate; import org.dom4j.Element; import com.atlassian.plugin.ModuleDescriptor; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.PluginParseException; import com.atlassian.plugin.Resources; import com.atlassian.plugin.StateAware; import com.atlassian.plugin.elements.ResourceDescriptor; import com.atlassian.plugin.elements.ResourceLocation; import com.atlassian.plugin.loaders.LoaderUtils; import com.atlassian.plugin.module.LegacyModuleFactory; import com.atlassian.plugin.module.ModuleFactory; import com.atlassian.plugin.module.PrefixDelegatingModuleFactory; import com.atlassian.plugin.util.ClassUtils; import com.atlassian.plugin.util.JavaVersionUtils; import com.atlassian.plugin.util.validation.ValidationPattern; import com.atlassian.util.concurrent.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractModuleDescriptor<T> implements ModuleDescriptor<T>, StateAware { protected Plugin plugin; String key; String name; protected String moduleClassName; - Class<T> moduleClass; + protected Class<T> moduleClass; String description; boolean enabledByDefault = true; boolean systemModule = false; /** * @deprecated since 2.2.0 */ @Deprecated protected boolean singleton = true; Map<String, String> params; protected Resources resources = Resources.EMPTY_RESOURCES; private Float minJavaVersion; private String i18nNameKey; private String descriptionKey; private String completeKey; boolean enabled = false; protected final ModuleFactory moduleFactory; private final Logger log = LoggerFactory.getLogger(getClass()); public AbstractModuleDescriptor(final ModuleFactory moduleFactory) { Validate.notNull(moduleFactory, "Module creator factory cannot be null"); this.moduleFactory = moduleFactory; } /** * @Deprecated since 2.5.0 use the constructor which requires a * {@link com.atlassian.plugin.module.ModuleFactory} */ @Deprecated public AbstractModuleDescriptor() { this(ModuleFactory.LEGACY_MODULE_FACTORY); } public void init(@NotNull final Plugin plugin, @NotNull final Element element) throws PluginParseException { validate(element); this.plugin = notNull("plugin", plugin); this.key = element.attributeValue("key"); this.name = element.attributeValue("name"); this.i18nNameKey = element.attributeValue("i18n-name-key"); this.completeKey = buildCompleteKey(plugin, key); this.description = element.elementTextTrim("description"); this.moduleClassName = element.attributeValue("class"); final Element descriptionElement = element.element("description"); this.descriptionKey = (descriptionElement != null) ? descriptionElement.attributeValue("key") : null; params = LoaderUtils.getParams(element); if ("disabled".equalsIgnoreCase(element.attributeValue("state"))) { enabledByDefault = false; } if ("true".equalsIgnoreCase(element.attributeValue("system"))) { systemModule = true; } if (element.element("java-version") != null) { minJavaVersion = Float.valueOf(element.element("java-version").attributeValue("min")); } if ("false".equalsIgnoreCase(element.attributeValue("singleton"))) { singleton = false; } else if ("true".equalsIgnoreCase(element.attributeValue("singleton"))) { singleton = true; } else { singleton = isSingletonByDefault(); } resources = Resources.fromXml(element); } /** * Validates the element, collecting the rules from * {@link #provideValidationRules(ValidationPattern)} * * @param element The configuration element * @since 2.2.0 */ private void validate(final Element element) { notNull("element", element); final ValidationPattern pattern = createPattern(); provideValidationRules(pattern); pattern.evaluate(element); } /** * Provides validation rules for the pattern * * @param pattern The validation pattern * @since 2.2.0 */ protected void provideValidationRules(final ValidationPattern pattern) { pattern.rule(test("@key").withError("The key is required")); } /** * Override this for module descriptors which don't expect to be able to * load a class successfully * * @param plugin * @param element * @deprecated Since 2.1.0, use {@link #loadClass(Plugin,String)} instead */ @Deprecated protected void loadClass(final Plugin plugin, final Element element) throws PluginParseException { loadClass(plugin, element.attributeValue("class")); } /** * Loads the module class that this descriptor provides, and will not * necessarily be the implementation class. Override this for module * descriptors whose type cannot be determined via generics. * * @param clazz The module class name to load * @throws IllegalStateException If the module class cannot be determined * and the descriptor doesn't define a module type via generics */ protected void loadClass(final Plugin plugin, final String clazz) throws PluginParseException { if (moduleClassName != null) { if (moduleFactory instanceof LegacyModuleFactory) // not all plugins // have to have a // class { moduleClass = ((LegacyModuleFactory) moduleFactory).getModuleClass(moduleClassName, this); } // This is only here for backwards compatibility with old code that // uses {@link // com.atlassian.plugin.PluginAccessor#getEnabledModulesByClass(Class)} else if (moduleFactory instanceof PrefixDelegatingModuleFactory) { moduleClass = ((PrefixDelegatingModuleFactory) moduleFactory).guessModuleClass(moduleClassName, this); } } // If this module has no class, then we assume Void else { moduleClass = (Class<T>) Void.class; } // Usually is null when a prefix is used in the class name if (moduleClass == null) { try { Class moduleTypeClass = null; try { moduleTypeClass = ClassUtils.getTypeArguments(AbstractModuleDescriptor.class, getClass()).get(0); } catch (RuntimeException ex) { log.debug("Unable to get generic type, usually due to Class.forName() problems", ex); moduleTypeClass = getModuleReturnClass(); } moduleClass = moduleTypeClass; } catch (final ClassCastException ex) { throw new IllegalStateException("The module class must be defined in a concrete instance of " + "ModuleDescriptor and not as another generic type."); } if (moduleClass == null) { throw new IllegalStateException("The module class cannot be determined, likely because it needs a concrete " + "module type defined in the generic type it passes to AbstractModuleDescriptor"); } } } Class<?> getModuleReturnClass() { try { return getClass().getMethod("getModule").getReturnType(); } catch (NoSuchMethodException e) { throw new IllegalStateException("The getModule() method is missing (!) on " + getClass()); } } /** * Build the complete key based on the provided plugin and module key. This * method has no side effects. * * @param plugin The plugin for which the module belongs * @param moduleKey The key for the module * @return A newly constructed complete key, null if the plugin is null */ private String buildCompleteKey(final Plugin plugin, final String moduleKey) { if (plugin == null) { return null; } final StringBuffer completeKeyBuffer = new StringBuffer(32); completeKeyBuffer.append(plugin.getKey()).append(":").append(moduleKey); return completeKeyBuffer.toString(); } /** * Override this if your plugin needs to clean up when it's been removed. */ public void destroy(final Plugin plugin) {} public boolean isEnabledByDefault() { return enabledByDefault && satisfiesMinJavaVersion(); } public boolean isSystemModule() { return systemModule; } /** * @deprecated Since 2.2.0 */ @Deprecated public boolean isSingleton() { return singleton; } /** * @deprecated Since 2.2.0 */ @Deprecated protected boolean isSingletonByDefault() { return true; } /** * Check that the module class of this descriptor implements a given * interface, or extends a given class. * * @param requiredModuleClazz The class this module's class must implement * or extend. * @throws PluginParseException If the module class does not implement or * extend the given class. */ final protected void assertModuleClassImplements(final Class<T> requiredModuleClazz) throws PluginParseException { if (!enabled) { throw new PluginParseException("Plugin module " + getKey() + " not enabled"); } if (!requiredModuleClazz.isAssignableFrom(getModuleClass())) { throw new PluginParseException("Given module class: " + getModuleClass().getName() + " does not implement " + requiredModuleClazz.getName()); } } public String getCompleteKey() { return completeKey; } public String getPluginKey() { return getPlugin().getKey(); } public String getKey() { return key; } public String getName() { return name; } public Class<T> getModuleClass() { return moduleClass; } public abstract T getModule(); public String getDescription() { return description; } public Map<String, String> getParams() { return params; } public String getI18nNameKey() { return i18nNameKey; } public String getDescriptionKey() { return descriptionKey; } public List<ResourceDescriptor> getResourceDescriptors() { return resources.getResourceDescriptors(); } public List<ResourceDescriptor> getResourceDescriptors(final String type) { return resources.getResourceDescriptors(type); } public ResourceLocation getResourceLocation(final String type, final String name) { return resources.getResourceLocation(type, name); } public ResourceDescriptor getResourceDescriptor(final String type, final String name) { return resources.getResourceDescriptor(type, name); } public Float getMinJavaVersion() { return minJavaVersion; } public boolean satisfiesMinJavaVersion() { if (minJavaVersion != null) { return JavaVersionUtils.satisfiesMinVersion(minJavaVersion); } return true; } /** * Sets the plugin for the ModuleDescriptor */ public void setPlugin(final Plugin plugin) { this.completeKey = buildCompleteKey(plugin, key); this.plugin = plugin; } /** * @return The plugin this module descriptor is associated with */ public Plugin getPlugin() { return plugin; } @Override public String toString() { return getCompleteKey() + " (" + getDescription() + ")"; } /** * Enables the descriptor by loading the module class. Classes overriding * this method MUST call super.enabled() before their own enabling code. * * @since 2.1.0 */ public void enabled() { loadClass(plugin, moduleClassName); enabled = true; } /** * Disables the module descriptor. Classes overriding this method MUST call * super.disabled() after their own disabling code. */ public void disabled() { enabled = false; moduleClass = null; } } diff --git a/atlassian-plugins-osgi/src/main/java/com/atlassian/plugin/osgi/factory/descriptor/ComponentModuleDescriptor.java b/atlassian-plugins-osgi/src/main/java/com/atlassian/plugin/osgi/factory/descriptor/ComponentModuleDescriptor.java index b2cfa86d..c765ee82 100644 --- a/atlassian-plugins-osgi/src/main/java/com/atlassian/plugin/osgi/factory/descriptor/ComponentModuleDescriptor.java +++ b/atlassian-plugins-osgi/src/main/java/com/atlassian/plugin/osgi/factory/descriptor/ComponentModuleDescriptor.java @@ -1,45 +1,53 @@ package com.atlassian.plugin.osgi.factory.descriptor; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.PluginParseException; import com.atlassian.plugin.descriptors.AbstractModuleDescriptor; import com.atlassian.plugin.descriptors.CannotDisable; import com.atlassian.plugin.module.ModuleFactory; import com.atlassian.plugin.osgi.module.BeanPrefixModuleFactory; /** * Module descriptor for Spring components. Shouldn't be directly used outside providing read-only information. * * @since 2.2.0 */ @CannotDisable public class ComponentModuleDescriptor<Object> extends AbstractModuleDescriptor { public ComponentModuleDescriptor() { super(ModuleFactory.LEGACY_MODULE_FACTORY); } @Override protected void loadClass(Plugin plugin, String clazz) throws PluginParseException { - // do nothing + try + { + // this should have been done once by Spring so should never throw exception. + this.moduleClass = plugin.loadClass(clazz, null); + } + catch (ClassNotFoundException e) + { + throw new PluginParseException("cannot load component class", e); + } } @Override public Object getModule() { return (Object) new BeanPrefixModuleFactory().createModule(getKey(), this); } /** * @deprecated - BEWARE that this is a temporary method that will not exist for long. Deprecated since 2.3.0 * * @return Module Class Name * @since 2.3.0 */ public String getModuleClassName() { return moduleClassName; } } diff --git a/atlassian-plugins-osgi/src/test/java/com/atlassian/plugin/osgi/TestPluginModuleCreation.java b/atlassian-plugins-osgi/src/test/java/com/atlassian/plugin/osgi/TestPluginModuleCreation.java index 2619a0dc..3afdb646 100644 --- a/atlassian-plugins-osgi/src/test/java/com/atlassian/plugin/osgi/TestPluginModuleCreation.java +++ b/atlassian-plugins-osgi/src/test/java/com/atlassian/plugin/osgi/TestPluginModuleCreation.java @@ -1,313 +1,316 @@ package com.atlassian.plugin.osgi; import com.atlassian.plugin.DefaultModuleDescriptorFactory; import com.atlassian.plugin.JarPluginArtifact; import com.atlassian.plugin.Plugin; +import com.atlassian.plugin.descriptors.AbstractModuleDescriptor; import com.atlassian.plugin.hostcontainer.HostContainer; import com.atlassian.plugin.impl.UnloadablePlugin; import com.atlassian.plugin.loaders.ClassPathPluginLoader; import com.atlassian.plugin.module.ClassPrefixModuleFactory; import com.atlassian.plugin.module.PrefixDelegatingModuleFactory; import com.atlassian.plugin.module.PrefixModuleFactory; import com.atlassian.plugin.osgi.hostcomponents.ComponentRegistrar; import com.atlassian.plugin.osgi.hostcomponents.HostComponentProvider; import com.atlassian.plugin.osgi.module.BeanPrefixModuleFactory; import com.atlassian.plugin.osgi.test.TestServlet; import com.atlassian.plugin.servlet.ServletModuleManager; import com.atlassian.plugin.servlet.descriptors.ServletModuleDescriptor; import com.atlassian.plugin.test.PluginJarBuilder; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.io.File; import java.util.HashSet; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests around the creation of the module class of {@link com.atlassian.plugin.ModuleDescriptor} */ public class TestPluginModuleCreation extends PluginInContainerTestBase { public void testInstallPlugin2AndGetModuleClass() throws Exception { final PluginJarBuilder firstBuilder = new PluginJarBuilder("first"); final File jar = firstBuilder .addFormattedResource("atlassian-plugin.xml", "<atlassian-plugin name='Test' key='first' pluginsVersion='2'>", " <plugin-info>", " <version>1.0</version>", " </plugin-info>", " <servlet key='foo' class='first.MyServlet'>", " <url-pattern>/foo</url-pattern>", " </servlet>", + " <component key='obj' class='com.atlassian.plugin.osgi.test.TestServlet'/>", "</atlassian-plugin>") .addFormattedJava("first.MyServlet", "package first;", "import javax.servlet.http.HttpServlet;", "public class MyServlet extends javax.servlet.http.HttpServlet {", " public String getServletInfo() {", " return 'bob';", " }", "}") .build(); final ServletModuleManager servletModuleManager = mock(ServletModuleManager.class); HostContainer hostContainer = mock(HostContainer.class); when(hostContainer.create(StubServletModuleDescriptor.class)).thenReturn(new StubServletModuleDescriptor(moduleFactory, servletModuleManager)); final DefaultModuleDescriptorFactory moduleDescriptorFactory = new DefaultModuleDescriptorFactory(hostContainer); moduleDescriptorFactory.addModuleDescriptor("servlet", StubServletModuleDescriptor.class); initPluginManager(new HostComponentProvider() { public void provide(final ComponentRegistrar registrar) { } }, moduleDescriptorFactory); pluginManager.installPlugin(new JarPluginArtifact(jar)); assertEquals(1, pluginManager.getEnabledPlugins().size()); assertEquals("first.MyServlet", pluginManager.getPlugin("first").getModuleDescriptor("foo").getModule().getClass().getName()); + assertEquals(1, pluginManager.getPlugin("first").getModuleDescriptorsByModuleClass(TestServlet.class).size()); } public void testInstallPlugins1AndGetModuleClass() throws Exception { ClassPathPluginLoader classPathPluginLoader = new ClassPathPluginLoader("testInstallPlugins1AndGetModuleClass.xml"); final ServletModuleManager servletModuleManager = mock(ServletModuleManager.class); final HostContainer hostContainer = mock(HostContainer.class); moduleFactory = new PrefixDelegatingModuleFactory(new HashSet<PrefixModuleFactory>() {{ add(new ClassPrefixModuleFactory(hostContainer)); add(new BeanPrefixModuleFactory()); }}); when(hostContainer.create(StubServletModuleDescriptor.class)).thenReturn(new StubServletModuleDescriptor(moduleFactory, servletModuleManager)); when(hostContainer.create(TestServlet.class)).thenReturn(new TestServlet()); final DefaultModuleDescriptorFactory moduleDescriptorFactory = new DefaultModuleDescriptorFactory(hostContainer); moduleDescriptorFactory.addModuleDescriptor("servlet", StubServletModuleDescriptor.class); initPluginManager(moduleDescriptorFactory, classPathPluginLoader); assertEquals(1, pluginManager.getEnabledPlugins().size()); assertEquals("com.atlassian.plugin.osgi.test.TestServlet", pluginManager.getPlugin("first").getModuleDescriptor("foo").getModule().getClass().getName()); } public void testInstallPlugins1AndFailToGetModuleClassFromSpring() throws Exception { ClassPathPluginLoader classPathPluginLoader = new ClassPathPluginLoader("testInstallPlugins1AndFailToGetModuleClassFromSpring.xml"); final ServletModuleManager servletModuleManager = mock(ServletModuleManager.class); final HostContainer hostContainer = mock(HostContainer.class); moduleFactory = new PrefixDelegatingModuleFactory(new HashSet<PrefixModuleFactory>() {{ add(new ClassPrefixModuleFactory(hostContainer)); add(new BeanPrefixModuleFactory()); }}); when(hostContainer.create(StubServletModuleDescriptor.class)).thenReturn(new StubServletModuleDescriptor(moduleFactory, servletModuleManager)); when(hostContainer.create(TestServlet.class)).thenReturn(new TestServlet()); doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) throws Throwable { ((ServletModuleDescriptor)invocation.getArguments()[0]).getModule(); return null; } }).when(servletModuleManager).addServletModule((ServletModuleDescriptor)anyObject()); final DefaultModuleDescriptorFactory moduleDescriptorFactory = new DefaultModuleDescriptorFactory(hostContainer); moduleDescriptorFactory.addModuleDescriptor("servlet", StubServletModuleDescriptor.class); initPluginManager(moduleDescriptorFactory, classPathPluginLoader); assertEquals(1, pluginManager.getPlugins().size()); final Plugin plugin = pluginManager.getPlugins().iterator().next(); assertTrue(plugin instanceof UnloadablePlugin); assertEquals(0, pluginManager.getEnabledPlugins().size()); } public void testInstallPlugins2AndGetModuleClassFromSpring() throws Exception { final PluginJarBuilder firstBuilder = new PluginJarBuilder("first"); final File jar = firstBuilder .addFormattedResource("atlassian-plugin.xml", "<atlassian-plugin name='Test' key='first' pluginsVersion='2'>", " <plugin-info>", " <version>1.0</version>", " </plugin-info>", " <servlet key='foo' class='bean:obj'>", " <url-pattern>/foo</url-pattern>", " </servlet>", "<component key='obj' class='first.MyServlet'/>", "</atlassian-plugin>") .addFormattedJava("first.MyServlet", "package first;", "import javax.servlet.http.HttpServlet;", "public class MyServlet extends javax.servlet.http.HttpServlet {", " public String getServletInfo() {", " return 'bob';", " }", "}") .build(); final ServletModuleManager servletModuleManager = mock(ServletModuleManager.class); HostContainer hostContainer = mock(HostContainer.class); when(hostContainer.create(StubServletModuleDescriptor.class)).thenReturn(new StubServletModuleDescriptor(moduleFactory, servletModuleManager)); final DefaultModuleDescriptorFactory moduleDescriptorFactory = new DefaultModuleDescriptorFactory(hostContainer); moduleDescriptorFactory.addModuleDescriptor("servlet", StubServletModuleDescriptor.class); initPluginManager(new HostComponentProvider() { public void provide(final ComponentRegistrar registrar) { } }, moduleDescriptorFactory); pluginManager.installPlugin(new JarPluginArtifact(jar)); assertEquals(1, pluginManager.getEnabledPlugins().size()); assertEquals("first.MyServlet", pluginManager.getPlugin("first").getModuleDescriptor("foo").getModule().getClass().getName()); } public void testGetModuleClassFromComponentModuleDescriptor() throws Exception { final PluginJarBuilder firstBuilder = new PluginJarBuilder("first"); final File jar = firstBuilder .addFormattedResource("atlassian-plugin.xml", "<atlassian-plugin name='Test' key='first' pluginsVersion='2'>", " <plugin-info>", " <version>1.0</version>", " </plugin-info>", "<component key='obj' class='first.MyServlet'/>", "</atlassian-plugin>") .addFormattedJava("first.MyServlet", "package first;", "import javax.servlet.http.HttpServlet;", "public class MyServlet extends javax.servlet.http.HttpServlet {", " public String getServletInfo() {", " return 'bob';", " }", "}") .build(); initPluginManager(); pluginManager.installPlugin(new JarPluginArtifact(jar)); assertEquals(1, pluginManager.getEnabledPlugins().size()); assertEquals("first.MyServlet", pluginManager.getPlugin("first").getModuleDescriptor("obj").getModule().getClass().getName()); } public void testGetModuleClassFromComponentImportModuleDescriptor() throws Exception { final PluginJarBuilder firstBuilder = new PluginJarBuilder("first"); final File jar1 = firstBuilder .addFormattedResource("atlassian-plugin.xml", "<atlassian-plugin name='Test1' key='first' pluginsVersion='2'>", " <plugin-info>", " <version>1.0</version>", " </plugin-info>", "<component key='obj' class='first.MyServlet' public='true'>", "<interface>com.atlassian.plugin.osgi.SomeInterface</interface>", "</component>", "</atlassian-plugin>") .addFormattedJava("com.atlassian.plugin.osgi.SomeInterface", "package com.atlassian.plugin.osgi;", "public interface SomeInterface {}") .addFormattedJava("first.MyServlet", "package first;", "import javax.servlet.http.HttpServlet;", "public class MyServlet extends javax.servlet.http.HttpServlet implements com.atlassian.plugin.osgi.SomeInterface {", " public String getServletInfo() {", " return 'bob';", " }", "}") .build(); final File jar2 = new PluginJarBuilder("second") .addFormattedResource("atlassian-plugin.xml", "<atlassian-plugin name='Test2' key='second' pluginsVersion='2'>", " <plugin-info>", " <version>1.0</version>", " </plugin-info>", " <component-import key='obj' interface='com.atlassian.plugin.osgi.SomeInterface' />", "</atlassian-plugin>" ) .addFormattedJava("com.atlassian.plugin.osgi.SomeInterface", "package com.atlassian.plugin.osgi;", "public interface SomeInterface {}") .build(); initPluginManager(); pluginManager.installPlugin(new JarPluginArtifact(jar1)); pluginManager.installPlugin(new JarPluginArtifact(jar2)); assertEquals(2, pluginManager.getEnabledPlugins().size()); assertEquals("first.MyServlet", pluginManager.getPlugin("first").getModuleDescriptor("obj").getModule().getClass().getName()); assertTrue(pluginManager.getPlugin("second").getModuleDescriptor("obj").getModule() instanceof SomeInterface); } public void testFailToGetModuleClassFromSpring() throws Exception { final PluginJarBuilder firstBuilder = new PluginJarBuilder("first"); final File jar = firstBuilder .addFormattedResource("atlassian-plugin.xml", "<atlassian-plugin name='Test' key='first' pluginsVersion='2'>", " <plugin-info>", " <version>1.0</version>", " </plugin-info>", " <servlet key='foo' class='bean:beanId' name='spring bean for servlet'>", " <url-pattern>/foo</url-pattern>", " </servlet>", "<component key='obj' class='first.MyServlet' />", "</atlassian-plugin>") .addFormattedJava("first.MyServlet", "package first;", "import javax.servlet.http.HttpServlet;", "public class MyServlet extends javax.servlet.http.HttpServlet {", " public String getServletInfo() {", " return 'bob';", " }", "}") .build(); final ServletModuleManager servletModuleManager = mock(ServletModuleManager.class); doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) throws Throwable { ((ServletModuleDescriptor)invocation.getArguments()[0]).getModule(); return null; } }).when(servletModuleManager).addServletModule((ServletModuleDescriptor)anyObject()); final HostContainer hostContainer = mock(HostContainer.class); moduleFactory = new PrefixDelegatingModuleFactory(new HashSet<PrefixModuleFactory>() {{ add(new ClassPrefixModuleFactory(hostContainer)); add(new BeanPrefixModuleFactory()); }}); when(hostContainer.create(StubServletModuleDescriptor.class)).thenReturn(new StubServletModuleDescriptor(moduleFactory, servletModuleManager)); final DefaultModuleDescriptorFactory moduleDescriptorFactory = new DefaultModuleDescriptorFactory(hostContainer); moduleDescriptorFactory.addModuleDescriptor("servlet", StubServletModuleDescriptor.class); initPluginManager(new HostComponentProvider() { public void provide(final ComponentRegistrar registrar) { } }, moduleDescriptorFactory); pluginManager.installPlugin(new JarPluginArtifact(jar)); assertEquals(0, pluginManager.getEnabledPlugins().size()); final Plugin plugin = pluginManager.getPlugins().iterator().next(); assertTrue(plugin instanceof UnloadablePlugin); } }
false
false
null
null