answer stringlengths 17 10.2M |
|---|
package org.apache.xerces.validators.schema;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.validators.common.Grammar;
import org.apache.xerces.validators.common.GrammarResolver;
import org.apache.xerces.validators.common.GrammarResolverImpl;
import org.apache.xerces.validators.common.XMLElementDecl;
import org.apache.xerces.validators.common.XMLAttributeDecl;
import org.apache.xerces.validators.schema.SchemaSymbols;
import org.apache.xerces.validators.schema.XUtil;
import org.apache.xerces.validators.schema.identity.Field;
import org.apache.xerces.validators.schema.identity.IdentityConstraint;
import org.apache.xerces.validators.schema.identity.Key;
import org.apache.xerces.validators.schema.identity.KeyRef;
import org.apache.xerces.validators.schema.identity.Selector;
import org.apache.xerces.validators.schema.identity.Unique;
import org.apache.xerces.validators.schema.identity.XPath;
import org.apache.xerces.validators.schema.identity.XPathException;
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl;
import org.apache.xerces.validators.datatype.IDDatatypeValidator;
import org.apache.xerces.validators.datatype.NOTATIONDatatypeValidator;
import org.apache.xerces.validators.datatype.StringDatatypeValidator;
import org.apache.xerces.validators.datatype.ListDatatypeValidator;
import org.apache.xerces.validators.datatype.UnionDatatypeValidator;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.utils.StringPool;
import org.w3c.dom.Element;
import java.io.IOException;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
//REVISIT: for now, import everything in the DOM package
import org.w3c.dom.*;
//Unit Test
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.validators.common.XMLValidator;
import org.apache.xerces.validators.datatype.DatatypeValidator.*;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.framework.XMLParser;
import org.apache.xerces.framework.XMLDocumentScanner;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
/** Don't check the following code in because it creates a dependency on
the serializer, preventing to package the parser without the serializer.
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
**/
import org.apache.xerces.validators.schema.SchemaSymbols;
/**
* Instances of this class get delegated to Traverse the Schema and
* to populate the Grammar internal representation by
* instances of Grammar objects.
* Traverse a Schema Grammar:
*
* @author Eric Ye, IBM
* @author Jeffrey Rodriguez, IBM
* @author Andy Clark, IBM
*
* @see org.apache.xerces.validators.common.Grammar
*
* @version $Id$
*/
public class TraverseSchema implements
NamespacesScope.NamespacesHandler{
//CONSTANTS
private static final int TOP_LEVEL_SCOPE = -1;
/** Identity constraint keywords. */
private static final String[][] IDENTITY_CONSTRAINTS = {
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_UNIQUE },
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEY },
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEYREF },
};
private static final String redefIdentifier = "_redefined";
// Flags for handleOccurrences to indicate any special
// restrictions on minOccurs and maxOccurs relating to "all".
// NOT_ALL_CONTEXT - not processing an <all>
// PROCESSING_ALL - processing an <element> in an <all>
// GROUP_REF_WITH_ALL - processing <group> reference that contained <all>
// CHILD_OF_GROUP - processing a child of a model group definition
private static final int NOT_ALL_CONTEXT = 0;
private static final int PROCESSING_ALL = 1;
private static final int GROUP_REF_WITH_ALL = 2;
private static final int CHILD_OF_GROUP = 4;
//debugging
private static final boolean DEBUGGING = false;
/** Compile to true to debug identity constraints. */
private static final boolean DEBUG_IDENTITY_CONSTRAINTS = false;
/**
* Compile to true to debug datatype validator lookup for
* identity constraint support.
*/
private static final boolean DEBUG_IC_DATATYPES = false;
//private data members
private boolean fFullConstraintChecking = false;
private XMLErrorReporter fErrorReporter = null;
private StringPool fStringPool = null;
private GrammarResolver fGrammarResolver = null;
private SchemaGrammar fSchemaGrammar = null;
private Element fSchemaRootElement;
// this is always set to refer to the root of the linked list containing the root info of schemas under redefinition.
private SchemaInfo fSchemaInfoListRoot = null;
private SchemaInfo fCurrentSchemaInfo = null;
private boolean fRedefineSucceeded;
private DatatypeValidatorFactoryImpl fDatatypeRegistry = null;
private Hashtable fComplexTypeRegistry = new Hashtable();
private Hashtable fAttributeDeclRegistry = new Hashtable();
// stores the names of groups that we've traversed so we can avoid multiple traversals
// qualified group names are keys and their contentSpecIndexes are values.
private Hashtable fGroupNameRegistry = new Hashtable();
// this Hashtable keeps track of whether a given redefined group does so by restriction.
private Hashtable fRestrictedRedefinedGroupRegistry = new Hashtable();
// stores "final" values of simpleTypes--no clean way to integrate this into the existing datatype validation structure...
private Hashtable fSimpleTypeFinalRegistry = new Hashtable();
// stores <notation> decl
private Hashtable fNotationRegistry = new Hashtable();
private Vector fIncludeLocations = new Vector();
private Vector fImportLocations = new Vector();
private Hashtable fRedefineLocations = new Hashtable();
private Vector fTraversedRedefineElements = new Vector();
// Hashtable associating attributeGroups within a <redefine> which
// restrict attributeGroups in the original schema with the
// new name for those groups in the modified redefined schema.
private Hashtable fRedefineAttributeGroupMap = null;
// simpleType data
private Hashtable fFacetData = new Hashtable(10);
private Stack fSimpleTypeNameStack = new Stack();
private String fListName = "";
private int fAnonTypeCount =0;
private int fScopeCount=0;
private int fCurrentScope=TOP_LEVEL_SCOPE;
private int fSimpleTypeAnonCount = 0;
private Stack fCurrentTypeNameStack = new Stack();
private Stack fCurrentGroupNameStack = new Stack();
private Hashtable fElementRecurseComplex = new Hashtable();
private boolean fElementDefaultQualified = false;
private boolean fAttributeDefaultQualified = false;
private int fBlockDefault = 0;
private int fFinalDefault = 0;
private int fTargetNSURI;
private String fTargetNSURIString = "";
private NamespacesScope fNamespacesScope = null;
private String fCurrentSchemaURL = "";
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private XMLAttributeDecl fTemp2AttributeDecl = new XMLAttributeDecl();
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
private XMLElementDecl fTempElementDecl2 = new XMLElementDecl();
private XMLContentSpec tempContentSpec1 = new XMLContentSpec();
private XMLContentSpec tempContentSpec2 = new XMLContentSpec();
private EntityResolver fEntityResolver = null;
private SubstitutionGroupComparator fSComp = null;
private Hashtable fIdentityConstraints = new Hashtable();
// Yet one more data structure; this one associates
// <unique> and <key> QNames with their corresponding objects,
// so that <keyRef>s can find them.
private Hashtable fIdentityConstraintNames = new Hashtable();
// General Attribute Checking
private GeneralAttrCheck fGeneralAttrCheck = null;
private int fXsiURI;
// REVISIT: maybe need to be moved into SchemaGrammar class
public class ComplexTypeInfo {
public String typeName;
public DatatypeValidator baseDataTypeValidator;
public ComplexTypeInfo baseComplexTypeInfo;
public int derivedBy = 0;
public int blockSet = 0;
public int finalSet = 0;
public int miscFlags=0;
public int scopeDefined = -1;
public int contentType;
public int contentSpecHandle = -1;
public int templateElementIndex = -1;
public int attlistHead = -1;
public DatatypeValidator datatypeValidator;
public boolean isAbstractType() {
return ((miscFlags & CT_IS_ABSTRACT)!=0);
}
public boolean containsAttrTypeID () {
return ((miscFlags & CT_CONTAINS_ATTR_TYPE_ID)!=0);
}
public boolean declSeen () {
return ((miscFlags & CT_DECL_SEEN)!=0);
}
public void setIsAbstractType() {
miscFlags |= CT_IS_ABSTRACT;
}
public void setContainsAttrTypeID() {
miscFlags |= CT_CONTAINS_ATTR_TYPE_ID;
}
public void setDeclSeen() {
miscFlags |= CT_DECL_SEEN;
}
}
private static final int CT_IS_ABSTRACT=1;
private static final int CT_CONTAINS_ATTR_TYPE_ID=2;
private static final int CT_DECL_SEEN=4; // indicates that the declaration was
// traversed as opposed to processed due
// to a forward reference
private class ComplexTypeRecoverableError extends Exception {
ComplexTypeRecoverableError() {super();}
ComplexTypeRecoverableError(String s) {super(s);}
}
private class ParticleRecoverableError extends Exception {
ParticleRecoverableError(String s) {super(s);}
}
//REVISIT: verify the URI.
public final static String SchemaForSchemaURI = "http:
private TraverseSchema( ) {
// new TraverseSchema() is forbidden;
}
public void setFullConstraintCheckingEnabled() {
fFullConstraintChecking = true;
}
public void setGrammarResolver(GrammarResolver grammarResolver){
fGrammarResolver = grammarResolver;
}
public void startNamespaceDeclScope(int prefix, int uri){
//TO DO
}
public void endNamespaceDeclScope(int prefix){
//TO DO, do we need to do anything here?
}
public boolean particleEmptiable(int contentSpecIndex) {
if (!fFullConstraintChecking) {
return true;
}
if (minEffectiveTotalRange(contentSpecIndex)==0)
return true;
else
return false;
}
public int minEffectiveTotalRange(int contentSpecIndex) {
fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1);
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
type == XMLContentSpec.CONTENTSPECNODE_ALL) {
return minEffectiveTotalRangeSeq(contentSpecIndex);
}
else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) {
return minEffectiveTotalRangeChoice(contentSpecIndex);
}
else {
return(fSchemaGrammar.getContentSpecMinOccurs(contentSpecIndex));
}
}
private int minEffectiveTotalRangeSeq(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int result;
if (right == -2)
result = min * minEffectiveTotalRange(left);
else
result = min * (minEffectiveTotalRange(left) + minEffectiveTotalRange(right));
return result;
}
private int minEffectiveTotalRangeChoice(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int result;
if (right == -2)
result = min * minEffectiveTotalRange(left);
else {
int minLeft = minEffectiveTotalRange(left);
int minRight = minEffectiveTotalRange(right);
result = min * ((minLeft < minRight)?minLeft:minRight);
}
return result;
}
public int maxEffectiveTotalRange(int contentSpecIndex) {
fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1);
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
type == XMLContentSpec.CONTENTSPECNODE_ALL) {
return maxEffectiveTotalRangeSeq(contentSpecIndex);
}
else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) {
return maxEffectiveTotalRangeChoice(contentSpecIndex);
}
else {
return(fSchemaGrammar.getContentSpecMaxOccurs(contentSpecIndex));
}
}
private int maxEffectiveTotalRangeSeq(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
int maxLeft = maxEffectiveTotalRange(left);
if (right == -2) {
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * maxLeft;
}
else {
int maxRight = maxEffectiveTotalRange(right);
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED ||
maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * (maxLeft + maxRight);
}
}
private int maxEffectiveTotalRangeChoice(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
int maxLeft = maxEffectiveTotalRange(left);
if (right == -2) {
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * maxLeft;
}
else {
int maxRight = maxEffectiveTotalRange(right);
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED ||
maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * ((maxLeft > maxRight)?maxLeft:maxRight);
}
}
private String resolvePrefixToURI (String prefix) throws Exception {
String uriStr = fStringPool.toString(fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)));
if (uriStr.length() == 0 && prefix.length() > 0) {
// REVISIT: Localize
reportGenericSchemaError("prefix : [" + prefix +"] cannot be resolved to a URI");
return "";
}
//REVISIT, !!!! a hack: needs to be updated later, cause now we only use localpart to key build-in datatype.
if ( prefix.length()==0 && uriStr.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& fTargetNSURIString.length() == 0) {
uriStr = "";
}
return uriStr;
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
XMLErrorReporter errorReporter,
String schemaURL,
EntityResolver entityResolver,
boolean fullChecking
) throws Exception {
fErrorReporter = errorReporter;
fCurrentSchemaURL = schemaURL;
fFullConstraintChecking = fullChecking;
fEntityResolver = entityResolver;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
XMLErrorReporter errorReporter,
String schemaURL,
boolean fullChecking
) throws Exception {
fErrorReporter = errorReporter;
fCurrentSchemaURL = schemaURL;
fFullConstraintChecking = fullChecking;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
boolean fullChecking
) throws Exception {
fFullConstraintChecking = fullChecking;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public void doTraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver) throws Exception {
fNamespacesScope = new NamespacesScope(this);
fSchemaRootElement = root;
fStringPool = stringPool;
fSchemaGrammar = schemaGrammar;
if (fFullConstraintChecking) {
fSchemaGrammar.setDeferContentSpecExpansion();
fSchemaGrammar.setCheckUniqueParticleAttribution();
}
fGrammarResolver = grammarResolver;
fDatatypeRegistry = (DatatypeValidatorFactoryImpl) fGrammarResolver.getDatatypeRegistry();
//Expand to registry type to contain all primitive datatype
fDatatypeRegistry.expandRegistryToFullSchemaSet();
// General Attribute Checking
fGeneralAttrCheck = new GeneralAttrCheck(fErrorReporter);
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
if (root == null) {
// REVISIT: Anything to do?
return;
}
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
//Make sure namespace binding is defaulted
String rootPrefix = root.getPrefix();
if( rootPrefix == null || rootPrefix.length() == 0 ){
String xmlns = root.getAttribute("xmlns");
if( xmlns.length() == 0 )
root.setAttribute("xmlns", SchemaSymbols.URI_SCHEMAFORSCHEMA );
}
//Retrieve the targetnamespace URI information
fTargetNSURIString = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE);
if (fTargetNSURIString==null) {
fTargetNSURIString="";
}
fTargetNSURI = fStringPool.addSymbol(fTargetNSURIString);
if (fGrammarResolver == null) {
// REVISIT: Localize
reportGenericSchemaError("Internal error: don't have a GrammarResolver for TraverseSchema");
}
else{
// for complex type registry, attribute decl registry and
// namespace mapping, needs to check whether the passed in
// Grammar was a newly instantiated one.
if (fSchemaGrammar.getComplexTypeRegistry() == null ) {
fSchemaGrammar.setComplexTypeRegistry(fComplexTypeRegistry);
}
else {
fComplexTypeRegistry = fSchemaGrammar.getComplexTypeRegistry();
}
if (fSchemaGrammar.getAttributeDeclRegistry() == null ) {
fSchemaGrammar.setAttributeDeclRegistry(fAttributeDeclRegistry);
}
else {
fAttributeDeclRegistry = fSchemaGrammar.getAttributeDeclRegistry();
}
if (fSchemaGrammar.getNamespacesScope() == null ) {
fSchemaGrammar.setNamespacesScope(fNamespacesScope);
}
else {
fNamespacesScope = fSchemaGrammar.getNamespacesScope();
}
fSchemaGrammar.setDatatypeRegistry(fDatatypeRegistry);
fSchemaGrammar.setTargetNamespaceURI(fTargetNSURIString);
fGrammarResolver.putGrammar(fTargetNSURIString, fSchemaGrammar);
}
// Retrived the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT);
if (blockAttr == null)
fBlockDefault = 0;
else
fBlockDefault =
parseBlockSet(blockAttr.getValue());
Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT);
if (finalAttr == null)
fFinalDefault = 0;
else
fFinalDefault =
parseFinalSet(finalAttr.getValue());
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
//fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
checkTopLevelDuplicateNames(root);
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
// process <redefine>, <include> and <import> info items.
Element child = XUtil.getFirstChildElement(root);
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
traverseInclude(child);
} else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
} else if (name.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefineSucceeded = true; // presume worked until proven failed.
traverseRedefine(child);
} else
break;
}
// child refers to the first info item which is not <annotation> or
// one of the schema inclusion/importation declarations.
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
traverseAttributeGroupDecl(child, null, null);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null, false );
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
traverseNotationDecl(child); //TO DO
} else {
// REVISIT: Localize
reportGenericSchemaError("error in content of <schema> element information item");
}
} // for each child node
// handle identity constraints
// we must traverse <key>s and <unique>s before we tackel<keyref>s,
// since all have global scope and may be declared anywhere in the schema.
Enumeration elementIndexes = fIdentityConstraints.keys();
while (elementIndexes.hasMoreElements()) {
Integer elementIndexObj = (Integer)elementIndexes.nextElement();
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj);
}
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints != null) {
int elementIndex = elementIndexObj.intValue();
traverseIdentityNameConstraintsFor(elementIndex, identityConstraints);
}
}
elementIndexes = fIdentityConstraints.keys();
while (elementIndexes.hasMoreElements()) {
Integer elementIndexObj = (Integer)elementIndexes.nextElement();
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj);
}
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints != null) {
int elementIndex = elementIndexObj.intValue();
traverseIdentityRefConstraintsFor(elementIndex, identityConstraints);
}
}
// General Attribute Checking
fGeneralAttrCheck = null;
} // traverseSchema(Element)
private void checkTopLevelDuplicateNames(Element root) {
//TO DO : !!!
}
private void extractTopLevel3Components(Element root){
for (Element child = XUtil.getFirstChildElement(root); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
String compName = child.getAttribute(SchemaSymbols.ATT_NAME);
if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
fSchemaGrammar.topLevelAttrGrpDecls.put(compName, child);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
fSchemaGrammar.topLevelAttrDecls.put(compName, child);
} else if ( name.equals(SchemaSymbols.ELT_GROUP) ) {
fSchemaGrammar.topLevelGroupDecls.put(compName, child);
} else if ( name.equals(SchemaSymbols.ELT_NOTATION) ) {
fSchemaGrammar.topLevelNotationDecls.put(compName, child);
}
} // for each child node
}
/**
* Expands a system id and returns the system id as a URL, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URL object representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
private String expandSystemId(String systemId, String currentSystemId) throws Exception{
String id = systemId;
// check for bad parameters id
if (id == null || id.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
URL url = new URL(id);
if (url != null) {
return systemId;
}
}
catch (MalformedURLException e) {
// continue on...
}
// normalize id
id = fixURI(id);
// normalize base
URL base = null;
URL url = null;
try {
if (currentSystemId == null) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"));
}
catch (SecurityException se) {
dir = "";
}
if (!dir.endsWith("/")) {
dir = dir + "/";
}
base = new URL("file", "", dir);
}
else {
base = new URL(currentSystemId);
}
// expand id
url = new URL(base, id);
}
catch (Exception e) {
// let it go through
}
if (url == null) {
return systemId;
}
return url.toString();
}
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
private static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
// Windows fix
if (str.length() >= 2) {
char ch1 = str.charAt(1);
if (ch1 == ':') {
char ch0 = Character.toUpperCase(str.charAt(0));
if (ch0 >= 'A' && ch0 <= 'Z') {
str = "/" + str;
}
}
}
// done
return str;
}
private void traverseInclude(Element includeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(includeDecl, scope);
Attr locationAttr = includeDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION);
if (locationAttr == null) {
// REVISIT: Localize
reportGenericSchemaError("a schemaLocation attribute must be specified on an <include> element");
return;
}
String location = locationAttr.getValue();
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// create a string for uniqueness of this included schema in fIncludeLocations
if (source.getPublicId () != null)
location = source.getPublicId ();
location += (',' + source.getSystemId ());
}
if (fIncludeLocations.contains((Object)location)) {
return;
}
fIncludeLocations.addElement((Object)location);
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE);
if (targetNSURI.length() > 0 && !targetNSURI.equals(fTargetNSURIString) ) {
// REVISIT: Localize
reportGenericSchemaError("included schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"'");
}
else {
// We not creating another TraverseSchema object to compile
// the included schema file, because the scope count, anon-type count
// should not be reset for a included schema, this can be fixed by saving
// the counters in the Schema Grammar,
if (fSchemaInfoListRoot == null) {
fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, null, null);
fCurrentSchemaInfo = fSchemaInfoListRoot;
}
fSchemaRootElement = root;
fCurrentSchemaURL = location;
traverseIncludedSchemaHeader(root);
// and now we'd better save this stuff!
fCurrentSchemaInfo = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, fCurrentSchemaInfo.getNext(), fCurrentSchemaInfo);
(fCurrentSchemaInfo.getPrev()).setNext(fCurrentSchemaInfo);
traverseIncludedSchema(root);
// there must always be a previous element!
fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev();
fCurrentSchemaInfo.restore();
}
}
}
private void traverseIncludedSchemaHeader(Element root) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
// Retrived the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT);
if (blockAttr == null)
fBlockDefault = 0;
else
fBlockDefault =
parseBlockSet(blockAttr.getValue());
Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT);
if (finalAttr == null)
fFinalDefault = 0;
else
fFinalDefault =
parseFinalSet(finalAttr.getValue());
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
} // traverseIncludedSchemaHeader
private void traverseIncludedSchema(Element root) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
checkTopLevelDuplicateNames(root);
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
// handle <redefine>, <include> and <import> elements.
Element child = XUtil.getFirstChildElement(root);
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
traverseInclude(child);
} else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
} else if (name.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefineSucceeded = true; // presume worked until proven failed.
traverseRedefine(child);
} else
break;
}
// handle the rest of the schema elements.
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
if(fRedefineAttributeGroupMap != null) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
String bName = (String)fRedefineAttributeGroupMap.get(dName);
if(bName != null) {
child.setAttribute(SchemaSymbols.ATT_NAME, bName);
// Now we reuse this location in the array to store info we'll need for validation...
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
int templateElementNameIndex = fStringPool.addSymbol("$"+bName);
int typeNameIndex = fStringPool.addSymbol("%"+bName);
typeInfo.scopeDefined = -2;
typeInfo.contentSpecHandle = -1;
typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
typeInfo.datatypeValidator = null;
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
Vector anyAttDecls = new Vector();
// need to determine how to initialize these babies; then
// on the <redefine> traversing end, try
// and cast the hash value into the right form;
// failure indicates nothing to redefine; success
// means we can feed checkAttribute... what it needs...
traverseAttributeGroupDecl(child, typeInfo, anyAttDecls);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
fRedefineAttributeGroupMap.put(dName, new Object []{typeInfo, fSchemaGrammar, anyAttDecls});
continue;
}
}
traverseAttributeGroupDecl(child, null, null);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null , false);
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
if(fGroupNameRegistry.get(fTargetNSURIString + ","+dName) == null) {
// we've been renamed already
traverseGroupDecl(child);
continue;
}
// if we're here: must have been a restriction.
// we have yet to be renamed.
try {
Integer i = (Integer)fGroupNameRegistry.get(fTargetNSURIString + ","+dName);
} catch (ClassCastException c) {
String s = (String)fGroupNameRegistry.get(fTargetNSURIString + ","+dName);
if (s == null) continue; // must have seen this already--somehow...
};
String bName = (String)fGroupNameRegistry.get(fTargetNSURIString +"," + dName);
if(bName != null) {
child.setAttribute(SchemaSymbols.ATT_NAME, bName);
// Now we reuse this location in the array to store info we'll need for validation...
// note that traverseGroupDecl will happily do that for us!
}
traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
traverseNotationDecl(child);
} else {
// REVISIT: Localize
reportGenericSchemaError("error in content of included <schema> element information item");
}
} // for each child node
}
// This method's job is to open a redefined schema and store away its root element, defaultElementQualified and other
// such info, in order that it can be available when redefinition actually takes place.
// It assumes that it will be called from the schema doing the redefining, and it assumes
// that the other schema's info has already been saved, putting the info it finds into the
// SchemaInfoList element that is passed in.
private void openRedefinedSchema(Element redefineDecl, SchemaInfo store) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(redefineDecl, scope);
Attr locationAttr = redefineDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION);
if (locationAttr == null) {
// REVISIT: Localize
fRedefineSucceeded = false;
reportGenericSchemaError("a schemaLocation attribute must be specified on a <redefine> element");
return;
}
String location = locationAttr.getValue();
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// Make sure we don't redefine the same schema twice; it's allowed
// but the specs encourage us to avoid it.
if (source.getPublicId () != null)
location = source.getPublicId ();
location += (',' + source.getSystemId ());
}
if (fRedefineLocations.get((Object)location) != null) {
// then we'd better make sure we're directed at that schema...
fCurrentSchemaInfo = (SchemaInfo)(fRedefineLocations.get((Object)location));
fCurrentSchemaInfo.restore();
return;
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar to be redefined
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root == null) { // nothing to be redefined, so just continue; specs disallow an error here.
fRedefineSucceeded = false;
return;
}
// now if root isn't null, it'll contain the root of the schema we need to redefine.
// We do this in two phases: first, we look through the children of
// redefineDecl. Each one will correspond to an element of the
// redefined schema that we need to redefine. To do this, we rename the
// element of the redefined schema, and rework the base or ref tag of
// the kid we're working on to refer to the renamed group or derive the
// renamed type. Once we've done this, we actually go through the
// schema being redefined and convert it to a grammar. Only then do we
// run through redefineDecl's kids and put them in the grammar.
// This approach is kosher with the specs. It does raise interesting
// questions about error reporting, and perhaps also about grammar
// access, but it is comparatively efficient (we need make at most
// only 2 traversals of any given information item) and moreover
// we can use existing code to build the grammar structures once the
// first pass is out of the way, so this should be quite robust.
// check to see if the targetNameSpace is right
String redefinedTargetNSURIString = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE);
if (redefinedTargetNSURIString.length() > 0 && !redefinedTargetNSURIString.equals(fTargetNSURIString) ) {
// REVISIT: Localize
fRedefineSucceeded = false;
reportGenericSchemaError("redefined schema '"+location+"' has a different targetNameSpace '"
+redefinedTargetNSURIString+"' from the original schema");
}
else {
// targetNamespace is right, so let's do the renaming...
// and let's keep in mind that the targetNamespace of the redefined
// elements is that of the redefined schema!
fSchemaRootElement = root;
fCurrentSchemaURL = location;
// get default form xmlns bindings et al.
traverseIncludedSchemaHeader(root);
// and then save them...
store.setNext(new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, null, store));
(store.getNext()).setPrev(store);
fCurrentSchemaInfo = store.getNext();
fRedefineLocations.put((Object)location, store.getNext());
} // end if
} // end openRedefinedSchema
/****
* <redefine
* schemaLocation = uriReference
* {any attributes with non-schema namespace . . .}>
* Content: (annotation | (
* attributeGroup | complexType | group | simpleType))*
* </redefine>
*/
private void traverseRedefine(Element redefineDecl) throws Exception {
// initialize storage areas...
fRedefineAttributeGroupMap = new Hashtable();
// only case in which need to save contents is when fSchemaInfoListRoot is null; otherwise we'll have
// done this already one way or another.
if (fSchemaInfoListRoot == null) {
fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, null, null);
openRedefinedSchema(redefineDecl, fSchemaInfoListRoot);
if(!fRedefineSucceeded)
return;
fCurrentSchemaInfo = fSchemaInfoListRoot.getNext();
renameRedefinedComponents(redefineDecl,fSchemaInfoListRoot.getNext().getRoot(), fSchemaInfoListRoot.getNext());
} else {
// may have a chain here; need to be wary!
SchemaInfo curr = fSchemaInfoListRoot;
for(; curr.getNext() != null; curr = curr.getNext());
fCurrentSchemaInfo = curr;
fCurrentSchemaInfo.restore();
openRedefinedSchema(redefineDecl, fCurrentSchemaInfo);
if(!fRedefineSucceeded)
return;
renameRedefinedComponents(redefineDecl,fCurrentSchemaInfo.getRoot(), fCurrentSchemaInfo);
}
// Now we have to march through our nicely-renamed schemas from the
// bottom up. When we do these traversals other <redefine>'s may
// perhaps be encountered; we leave recursion to sort this out.
traverseIncludedSchema(fSchemaRootElement);
// and last but not least: traverse our own <redefine>--the one all
// this labour has been expended upon.
for (Element child = XUtil.getFirstChildElement(redefineDecl); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
// annotations can occur anywhere in <redefine>s!
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
if(fGroupNameRegistry.get(fTargetNSURIString +","+ dName) == null ||
((fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName) != null) &&
!((Boolean)fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName)).booleanValue())) { // extension!
traverseGroupDecl(child);
continue;
}
traverseGroupDecl(child);
Integer bCSIndexObj = null;
try {
bCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString +","+ dName+redefIdentifier);
} catch(ClassCastException c) {
// if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema.
// REVISIT: localize
reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>");
continue;
}
if(bCSIndexObj != null) { // we have something!
int bCSIndex = bCSIndexObj.intValue();
Integer dCSIndexObj;
try {
dCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString+","+dName);
} catch (ClassCastException c) {
continue;
}
if(dCSIndexObj == null) // something went wrong...
continue;
int dCSIndex = dCSIndexObj.intValue();
try {
checkParticleDerivationOK(dCSIndex, -1, bCSIndex, -1, null);
}
catch (ParticleRecoverableError e) {
reportGenericSchemaError(e.getMessage());
}
} else
// REVISIT: localize
reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>");
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
if(fRedefineAttributeGroupMap != null) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
Object [] bAttGrpStore = null;
try {
bAttGrpStore = (Object [])fRedefineAttributeGroupMap.get(dName);
} catch(ClassCastException c) {
// if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema.
// REVISIT: localize
reportGenericSchemaError("src-redefine.7.2: an <attributeGroup> within a <redefine> must either have a ref to an <attributeGroup> with the same name or must restrict such an <attributeGroup>");
continue;
}
if(bAttGrpStore != null) { // we have something!
ComplexTypeInfo bTypeInfo = (ComplexTypeInfo)bAttGrpStore[0];
SchemaGrammar bSchemaGrammar = (SchemaGrammar)bAttGrpStore[1];
Vector bAnyAttDecls = (Vector)bAttGrpStore[2];
XMLAttributeDecl bAnyAttDecl =
(bAnyAttDecls.size()>0 )? (XMLAttributeDecl)bAnyAttDecls.elementAt(0):null;
ComplexTypeInfo dTypeInfo = new ComplexTypeInfo();
int templateElementNameIndex = fStringPool.addSymbol("$"+dName);
int dTypeNameIndex = fStringPool.addSymbol("%"+dName);
dTypeInfo.scopeDefined = -2;
dTypeInfo.contentSpecHandle = -1;
dTypeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
dTypeInfo.datatypeValidator = null;
dTypeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,dTypeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, dTypeInfo.scopeDefined,
dTypeInfo.contentType,
dTypeInfo.contentSpecHandle, -1, dTypeInfo.datatypeValidator);
Vector dAnyAttDecls = new Vector();
XMLAttributeDecl dAnyAttDecl =
(dAnyAttDecls.size()>0 )? (XMLAttributeDecl)dAnyAttDecls.elementAt(0):null;
traverseAttributeGroupDecl(child, dTypeInfo, dAnyAttDecls);
dTypeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
dTypeInfo.templateElementIndex);
try {
checkAttributesDerivationOKRestriction(dTypeInfo.attlistHead,fSchemaGrammar,
dAnyAttDecl,bTypeInfo.attlistHead,bSchemaGrammar,bAnyAttDecl);
}
catch (ComplexTypeRecoverableError e) {
String message = e.getMessage();
reportGenericSchemaError("src-redefine.7.2: redefinition failed because of " + message);
}
continue;
}
}
traverseAttributeGroupDecl(child, null, null);
} // no else; error reported in the previous traversal
} //for
// and restore the original globals
fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev();
fCurrentSchemaInfo.restore();
} // traverseRedefine
// the purpose of this method is twofold: 1. To find and appropriately modify all information items
// in redefinedSchema with names that are redefined by children of
// redefineDecl. 2. To make sure the redefine element represented by
// redefineDecl is valid as far as content goes and with regard to
// properly referencing components to be redefined. No traversing is done here!
// This method also takes actions to find and, if necessary, modify the names
// of elements in <redefine>'s in the schema that's being redefined.
private void renameRedefinedComponents(Element redefineDecl, Element schemaToRedefine, SchemaInfo currSchemaInfo) throws Exception {
for (Element child = XUtil.getFirstChildElement(redefineDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) )
continue;
else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
String typeName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(typeName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_SIMPLETYPE, typeName, typeName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_SIMPLETYPE,
typeName, typeName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
String typeName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(typeName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_COMPLEXTYPE, typeName, typeName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_COMPLEXTYPE,
typeName, typeName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
String baseName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(baseName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_ATTRIBUTEGROUP, baseName, baseName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_ATTRIBUTEGROUP,
baseName, baseName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String baseName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(baseName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_GROUP, baseName, baseName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_GROUP,
baseName, baseName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("invalid top-level content for <redefine>");
return;
}
} // for
} // renameRedefinedComponents
// This function looks among the children of curr for an element of type elementSought.
// If it finds one, it evaluates whether its ref attribute contains a reference
// to originalName. If it does, it returns 1 + the value returned by
// calls to itself on all other children. In all other cases it returns 0 plus
// the sum of the values returned by calls to itself on curr's children.
// It also resets the value of ref so that it will refer to the renamed type from the schema
// being redefined.
private int changeRedefineGroup(QName originalName, String elementSought, String newName, Element curr) throws Exception {
int result = 0;
for (Element child = XUtil.getFirstChildElement(curr);
child != null; child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (!name.equals(elementSought))
result += changeRedefineGroup(originalName, elementSought, newName, child);
else {
String ref = child.getAttribute( SchemaSymbols.ATT_REF );
if (!ref.equals("")) {
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if(originalName.equals(new QName(-1, fStringPool.addSymbol(localpart), fStringPool.addSymbol(localpart), fStringPool.addSymbol(uriStr)))) {
if(prefix.equals(""))
child.setAttribute(SchemaSymbols.ATT_REF, newName);
else
child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName);
result++;
}
} // if ref was null some other stage of processing will flag the error
}
}
return result;
} // changeRedefineGroup
// This simple function looks for the first occurrence of an eltLocalname
// schema information item and appropriately changes the value of
// its name or type attribute from oldName to newName.
// Root contains the root of the schema being operated upon.
// If it turns out that what we're looking for is in a <redefine> though, then we
// just rename it--and it's reference--to be the same and wait until
// renameRedefineDecls can get its hands on it and do it properly.
private void fixRedefinedSchema(String eltLocalname, String oldName, String newName, Element schemaToRedefine,
SchemaInfo currSchema) throws Exception {
boolean foundIt = false;
for (Element child = XUtil.getFirstChildElement(schemaToRedefine);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if(name.equals(SchemaSymbols.ELT_REDEFINE)) { // need to search the redefine decl...
for (Element redefChild = XUtil.getFirstChildElement(child);
redefChild != null;
redefChild = XUtil.getNextSiblingElement(redefChild)) {
String redefName = redefChild.getLocalName();
if (redefName.equals(eltLocalname) ) {
String infoItemName = redefChild.getAttribute( SchemaSymbols.ATT_NAME );
if(!infoItemName.equals(oldName))
continue;
else { // found it!
foundIt = true;
openRedefinedSchema(child, currSchema);
if(!fRedefineSucceeded)
return;
if (validateRedefineNameChange(eltLocalname, oldName, newName+redefIdentifier, redefChild) &&
(currSchema.getNext() != null))
fixRedefinedSchema(eltLocalname, oldName, newName+redefIdentifier, fSchemaRootElement, currSchema.getNext());
redefChild.setAttribute( SchemaSymbols.ATT_NAME, newName );
// and we now know we will traverse this, so set fTraversedRedefineElements appropriately...
fTraversedRedefineElements.addElement(newName);
currSchema.restore();
fCurrentSchemaInfo = currSchema;
break;
}
}
} //for
if (foundIt) break;
}
else if (name.equals(eltLocalname) ) {
String infoItemName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(!infoItemName.equals(oldName))
continue;
else { // found it!
foundIt = true;
child.setAttribute( SchemaSymbols.ATT_NAME, newName );
break;
}
}
} //for
if(!foundIt) {
fRedefineSucceeded = false;
// REVISIT: localize
reportGenericSchemaError("could not find a declaration in the schema to be redefined corresponding to " + oldName);
}
} // end fixRedefinedSchema
// this method returns true if the redefine component is valid, and if
// it was possible to revise it correctly. The definition of
// correctly will depend on whether renameRedefineDecls
// or fixRedefineSchema is the caller.
// this method also prepends a prefix onto newName if necessary; newName will never contain one.
private boolean validateRedefineNameChange(String eltLocalname, String oldName, String newName, Element child) throws Exception {
if (eltLocalname.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
Element grandKid = XUtil.getFirstChildElement(child);
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else {
String grandKidName = grandKid.getLocalName();
if(grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = XUtil.getNextSiblingElement(grandKid);
grandKidName = grandKid.getLocalName();
}
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else if(!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else {
String derivedBase = grandKid.getAttribute( SchemaSymbols.ATT_BASE );
QName processedDerivedBase = parseBase(derivedBase);
if(!processedTypeName.equals(processedDerivedBase)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("the base attribute of the restriction child of a simpleType child of a redefine must have the same value as the simpleType's type attribute");
} else {
// now we have to do the renaming...
String prefix = "";
int colonptr = derivedBase.indexOf(":");
if ( colonptr > 0)
prefix = derivedBase.substring(0,colonptr) + ":";
grandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName );
return true;
}
}
}
} else if (eltLocalname.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
Element grandKid = XUtil.getFirstChildElement(child);
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
if(grandKid.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = XUtil.getNextSiblingElement(grandKid);
}
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
// have to go one more level down; let another pass worry whether complexType is valid.
Element greatGrandKid = XUtil.getFirstChildElement(grandKid);
if (greatGrandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
String greatGrandKidName = greatGrandKid.getLocalName();
if(greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
greatGrandKid = XUtil.getNextSiblingElement(greatGrandKid);
greatGrandKidName = greatGrandKid.getLocalName();
}
if (greatGrandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else if(!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) &&
!greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
String derivedBase = greatGrandKid.getAttribute( SchemaSymbols.ATT_BASE );
QName processedDerivedBase = parseBase(derivedBase);
if(!processedTypeName.equals(processedDerivedBase)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("the base attribute of the restriction or extension grandchild of a complexType child of a redefine must have the same value as the complexType's type attribute");
} else {
// now we have to do the renaming...
String prefix = "";
int colonptr = derivedBase.indexOf(":");
if ( colonptr > 0)
prefix = derivedBase.substring(0,colonptr) + ":";
greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName );
return true;
}
}
}
}
}
} else if (eltLocalname.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
int attGroupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child);
if(attGroupRefsCount > 1) {
fRedefineSucceeded = false;
// REVISIT: localize
reportGenericSchemaError("if an attributeGroup child of a <redefine> element contains an attributeGroup ref'ing itself, it must have exactly 1; this one has " + attGroupRefsCount);
} else if (attGroupRefsCount == 1) {
return true;
} else
fRedefineAttributeGroupMap.put(oldName, newName);
} else if (eltLocalname.equals(SchemaSymbols.ELT_GROUP)) {
QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
int groupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child);
if(groupRefsCount > 1) {
fRedefineSucceeded = false;
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
// REVISIT: localize
reportGenericSchemaError("if a group child of a <redefine> element contains a group ref'ing itself, it must have exactly 1; this one has " + groupRefsCount);
} else if (groupRefsCount == 1) {
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
return true;
} else {
fGroupNameRegistry.put(fTargetNSURIString + "," + oldName, newName);
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(true));
}
} else {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("internal Xerces error; please submit a bug with schema as testcase");
}
// if we get here then we must have reported an error and failed somewhere...
return false;
} // validateRedefineNameChange
private void traverseImport(Element importDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(importDecl, scope);
String location = importDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION);
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// create a string for uniqueness of this imported schema in fImportLocations
if (source.getPublicId () != null)
location = source.getPublicId ();
location += (',' + source.getSystemId ());
}
if (fImportLocations.contains((Object)location)) {
return;
}
fImportLocations.addElement((Object)location);
String namespaceString = importDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE);
SchemaGrammar importedGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(namespaceString);
if (importedGrammar == null) {
importedGrammar = new SchemaGrammar();
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE);
if (!targetNSURI.equals(namespaceString) ) {
// REVISIT: Localize
reportGenericSchemaError("imported schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"' from what is declared '"+namespaceString+"'.");
}
else {
TraverseSchema impSchema = new TraverseSchema(root, fStringPool, importedGrammar, fGrammarResolver, fErrorReporter, location, fEntityResolver, fFullConstraintChecking);
Enumeration ics = impSchema.fIdentityConstraints.keys();
while(ics.hasMoreElements()) {
Object icsKey = ics.nextElement();
fIdentityConstraints.put(icsKey, impSchema.fIdentityConstraints.get(icsKey));
}
Enumeration icNames = impSchema.fIdentityConstraintNames.keys();
while(icNames.hasMoreElements()) {
String icsNameKey = (String)icNames.nextElement();
fIdentityConstraintNames.put(icsNameKey, impSchema.fIdentityConstraintNames.get(icsNameKey));
}
}
}
else {
reportGenericSchemaError("Could not get the doc root for imported Schema file: "+location);
}
}
/**
* <annotation>(<appinfo> | <documentation>)*</annotation>
*
* @param annotationDecl: the DOM node corresponding to the <annotation> info item
*/
private void traverseAnnotationDecl(Element annotationDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(annotationDecl, scope);
for(Element child = XUtil.getFirstChildElement(annotationDecl); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if(!((name.equals(SchemaSymbols.ELT_APPINFO)) ||
(name.equals(SchemaSymbols.ELT_DOCUMENTATION)))) {
// REVISIT: Localize
reportGenericSchemaError("an <annotation> can only contain <appinfo> and <documentation> elements");
}
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(child, scope);
}
}
// Evaluates content of Annotation if present.
// @param: elm - top element
// @param: content - content must be annotation? or some other simple content
// @param: isEmpty: -- true if the content allowed is (annotation?) only
// false if must have some element (with possible preceding <annotation?>)
//REVISIT: this function should be used in all traverse* methods!
private Element checkContent( Element elm, Element content, boolean isEmpty ) throws Exception {
//isEmpty = true-> means content can be null!
if ( content == null) {
if (!isEmpty) {
reportSchemaError(SchemaMessageProvider.ContentError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
}
return null;
}
if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
traverseAnnotationDecl( content );
content = XUtil.getNextSiblingElement(content);
if (content == null ) { //must be followed by <simpleType?>
if (!isEmpty) {
reportSchemaError(SchemaMessageProvider.ContentError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
}
return null;
}
if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
reportSchemaError(SchemaMessageProvider.AnnotationError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
return null;
}
//return null if expected only annotation?, else returns updated content
}
return content;
}
//@param: elm - top element
//@param: baseTypeStr - type (base/itemType/memberTypes)
//@param: baseRefContext: whether the caller is using this type as a base for restriction, union or list
//return DatatypeValidator available for the baseTypeStr, null if not found or disallowed.
// also throws an error if the base type won't allow itself to be used in this context.
//REVISIT: this function should be used in some|all traverse* methods!
private DatatypeValidator findDTValidator (Element elm, String baseTypeStr, int baseRefContext ) throws Exception{
int baseType = fStringPool.addSymbol( baseTypeStr );
String prefix = "";
DatatypeValidator baseValidator = null;
String localpart = baseTypeStr;
int colonptr = baseTypeStr.indexOf(":");
if ( colonptr > 0) {
prefix = baseTypeStr.substring(0,colonptr);
localpart = baseTypeStr.substring(colonptr+1);
}
String uri = resolvePrefixToURI(prefix);
baseValidator = getDatatypeValidator(uri, localpart);
if (baseValidator == null) {
Element baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
traverseSimpleTypeDecl( baseTypeNode );
baseValidator = getDatatypeValidator(uri, localpart);
}
}
Integer finalValue;
if ( baseValidator == null ) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_BASE ),
elm.getAttribute(SchemaSymbols.ATT_NAME)});
} else {
finalValue = (uri.equals("")?
((Integer)fSimpleTypeFinalRegistry.get(localpart)):
((Integer)fSimpleTypeFinalRegistry.get(uri + "," +localpart)));
if((finalValue != null) &&
((finalValue.intValue() & baseRefContext) != 0)) {
//REVISIT: localize
reportGenericSchemaError("the base type " + baseTypeStr + " does not allow itself to be used as the base for a restriction and/or as a type in a list and/or union");
return baseValidator;
}
}
return baseValidator;
}
private void checkEnumerationRequiredNotation(String name, String type) throws Exception{
String localpart = type;
int colonptr = type.indexOf(":");
if ( colonptr > 0) {
localpart = type.substring(colonptr+1);
}
if (localpart.equals("NOTATION")) {
reportGenericSchemaError("[enumeration-required-notation] It is an error for NOTATION to be used "+
"directly in a schema in element/attribute '"+name+"'");
}
}
// @used in traverseSimpleType
// on return we need to pop the last simpleType name from
// the name stack
private int resetSimpleTypeNameStack(int returnValue){
if (!fSimpleTypeNameStack.empty()) {
fSimpleTypeNameStack.pop();
}
return returnValue;
}
// @used in traverseSimpleType
// report an error cos-list-of-atomic and reset the last name of the list datatype we traversing
private void reportCosListOfAtomic () throws Exception{
reportGenericSchemaError("cos-list-of-atomic: The itemType must have a {variety} of atomic or union (in which case all the {member type definitions} must be atomic)");
fListName="";
}
// @used in traverseSimpleType
// find if union datatype validator has list datatype member.
private boolean isListDatatype (DatatypeValidator validator){
if (validator instanceof UnionDatatypeValidator) {
Vector temp = ((UnionDatatypeValidator)validator).getBaseValidators();
for (int i=0;i<temp.size();i++) {
if (temp.elementAt(i) instanceof ListDatatypeValidator) {
return true;
}
if (temp.elementAt(i) instanceof UnionDatatypeValidator) {
if (isListDatatype((DatatypeValidator)temp.elementAt(i))) {
return true;
}
}
}
}
return false;
}
/**
* Traverse SimpleType declaration:
* <simpleType
* final = #all | list of (restriction, union or list)
* id = ID
* name = NCName>
* Content: (annotation? , ((list | restriction | union)))
* </simpleType>
* traverse <list>|<restriction>|<union>
*
* @param simpleTypeDecl
* @return
*/
private int traverseSimpleTypeDecl( Element simpleTypeDecl ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(simpleTypeDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleTypeDecl, scope);
String nameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME );
String qualifiedName = nameProperty;
// set qualified name
if ( nameProperty.length() == 0) { // anonymous simpleType
qualifiedName = "#S#"+(fSimpleTypeAnonCount++);
fStringPool.addSymbol(qualifiedName);
}
else {
if (fTargetNSURIString.length () != 0) {
qualifiedName = fTargetNSURIString+","+qualifiedName;
}
fStringPool.addSymbol( nameProperty );
}
//check if we have already traversed the same simpleType decl
if (fDatatypeRegistry.getDatatypeValidator(qualifiedName)!=null) {
return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName));
}
else {
if (fSimpleTypeNameStack.search(qualifiedName) != -1 ){
// cos-no-circular-unions && no circular definitions
reportGenericSchemaError("cos-no-circular-unions: no circular definitions are allowed for an element '"+ nameProperty+"'");
return resetSimpleTypeNameStack(-1);
}
}
// update _final_ registry
Attr finalAttr = simpleTypeDecl.getAttributeNode(SchemaSymbols.ATT_FINAL);
int finalProperty = 0;
if(finalAttr != null)
finalProperty = parseFinalSet(finalAttr.getValue());
else
finalProperty = parseFinalSet(null);
// if we have a nonzero final , store it in the hash...
if(finalProperty != 0)
fSimpleTypeFinalRegistry.put(qualifiedName, new Integer(finalProperty));
// remember name being traversed to
// avoid circular definitions in union
fSimpleTypeNameStack.push(qualifiedName);
//annotation?,(list|restriction|union)
Element content = XUtil.getFirstChildElement(simpleTypeDecl);
content = checkContent(simpleTypeDecl, content, false);
if (content == null) {
return resetSimpleTypeNameStack(-1);
}
// General Attribute Checking
scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope);
//use content.getLocalName for the cases there "xsd:" is a prefix, ei. "xsd:list"
String varietyProperty = content.getLocalName();
String baseTypeQNameProperty = null;
Vector dTValidators = null;
int size = 0;
StringTokenizer unionMembers = null;
boolean list = false;
boolean union = false;
boolean restriction = false;
int numOfTypes = 0; //list/restriction = 1, union = "+"
if (varietyProperty.equals(SchemaSymbols.ELT_LIST)) { //traverse List
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_ITEMTYPE );
list = true;
if (fListName.length() != 0) { // parent is <list> datatype
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
else {
fListName = qualifiedName;
}
}
else if (varietyProperty.equals(SchemaSymbols.ELT_RESTRICTION)) { //traverse Restriction
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_BASE );
restriction= true;
}
else if (varietyProperty.equals(SchemaSymbols.ELT_UNION)) { //traverse union
union = true;
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_MEMBERTYPES);
if (baseTypeQNameProperty.length() != 0) {
unionMembers = new StringTokenizer( baseTypeQNameProperty );
size = unionMembers.countTokens();
}
else {
size = 1; //at least one must be seen as <simpleType> decl
}
dTValidators = new Vector (size, 2);
}
else {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { varietyProperty });
return -1;
}
if(XUtil.getNextSiblingElement(content) != null) {
// REVISIT: Localize
reportGenericSchemaError("error in content of simpleType");
}
int typeNameIndex;
DatatypeValidator baseValidator = null;
if ( baseTypeQNameProperty.length() == 0 ) {
//must 'see' <simpleType>
//content = {annotation?,simpleType?...}
content = XUtil.getFirstChildElement(content);
//check content (annotation?, ...)
content = checkContent(simpleTypeDecl, content, false);
if (content == null) {
return resetSimpleTypeNameStack(-1);
}
if (content.getLocalName().equals( SchemaSymbols.ELT_SIMPLETYPE )) {
typeNameIndex = traverseSimpleTypeDecl(content);
if (typeNameIndex!=-1) {
baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
if (baseValidator !=null && union) {
dTValidators.addElement((DatatypeValidator)baseValidator);
}
}
if ( typeNameIndex == -1 || baseValidator == null) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { content.getAttribute( SchemaSymbols.ATT_BASE ),
content.getAttribute(SchemaSymbols.ATT_NAME) });
return resetSimpleTypeNameStack(-1);
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
return resetSimpleTypeNameStack(-1);
}
} //end - must see simpleType?
else {
//base was provided - get proper validator.
numOfTypes = 1;
if (union) {
numOfTypes= size;
}
// this loop is also where we need to find out whether the type being used as
// a base (or itemType or whatever) allows such things.
int baseRefContext = (restriction? SchemaSymbols.RESTRICTION:0);
baseRefContext = baseRefContext | (union? SchemaSymbols.UNION:0);
baseRefContext = baseRefContext | (list ? SchemaSymbols.LIST:0);
for (int i=0; i<numOfTypes; i++) { //find all validators
if (union) {
baseTypeQNameProperty = unionMembers.nextToken();
}
baseValidator = findDTValidator ( simpleTypeDecl, baseTypeQNameProperty, baseRefContext);
if ( baseValidator == null) {
return resetSimpleTypeNameStack(-1);
}
// (variety is list)cos-list-of-atomic
if (fListName.length() != 0 ) {
if (baseValidator instanceof ListDatatypeValidator) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
// if baseValidator is of type (union) need to look
// at Union validators to make sure that List is not one of them
if (isListDatatype(baseValidator)) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
}
if (union) {
dTValidators.addElement((DatatypeValidator)baseValidator); //add validator to structure
}
//REVISIT: Should we raise exception here?
// if baseValidator.isInstanceOf(LIST) and UNION
if ( list && (baseValidator instanceof UnionDatatypeValidator)) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)});
return -1;
}
}
} //end - base is available
// move to next child
// <base==empty)->[simpleType]->[facets] OR
// <base!=empty)->[facets]
if (baseTypeQNameProperty.length() == 0) {
content = XUtil.getNextSiblingElement( content );
}
else {
content = XUtil.getFirstChildElement(content);
}
//get more types for union if any
if (union) {
int index=size;
if (baseTypeQNameProperty.length() != 0 ) {
content = checkContent(simpleTypeDecl, content, true);
}
while (content!=null) {
typeNameIndex = traverseSimpleTypeDecl(content);
if (typeNameIndex!=-1) {
baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
if (baseValidator != null) {
if (fListName.length() != 0 && baseValidator instanceof ListDatatypeValidator) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
dTValidators.addElement((DatatypeValidator)baseValidator);
}
}
if ( baseValidator == null || typeNameIndex == -1) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)});
return (-1);
}
content = XUtil.getNextSiblingElement( content );
}
} // end - traverse Union
if (fListName.length() != 0) {
// reset fListName, meaning that we are done with
// traversing <list> and its itemType resolves to atomic value
if (fListName.equals(qualifiedName)) {
fListName = "";
}
}
int numFacets=0;
fFacetData.clear();
if (restriction && content != null) {
short flags = 0; // flag facets that have fixed="true"
int numEnumerationLiterals = 0;
Vector enumData = new Vector();
content = checkContent(simpleTypeDecl, content , true);
StringBuffer pattern = null;
String facet;
while (content != null) {
if (content.getNodeType() == Node.ELEMENT_NODE) {
// General Attribute Checking
contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope);
numFacets++;
facet =content.getLocalName();
if (facet.equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
String enumVal = content.getAttribute(SchemaSymbols.ATT_VALUE);
String localName;
if (baseValidator instanceof NOTATIONDatatypeValidator) {
String prefix = "";
String localpart = enumVal;
int colonptr = enumVal.indexOf(":");
if ( colonptr > 0) {
prefix = enumVal.substring(0,colonptr);
localpart = enumVal.substring(colonptr+1);
}
String uriStr = (prefix.length() != 0)?resolvePrefixToURI(prefix):fTargetNSURIString;
nameProperty=uriStr + ":" + localpart;
localName = (String)fNotationRegistry.get(nameProperty);
if(localName == null){
localName = traverseNotationFromAnotherSchema( localpart, uriStr);
if (localName == null) {
reportGenericSchemaError("Notation '" + localpart +
"' not found in the grammar "+ uriStr);
}
}
enumVal=nameProperty;
}
enumData.addElement(enumVal);
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
else if (facet.equals(SchemaSymbols.ELT_ANNOTATION) || facet.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
else if (facet.equals(SchemaSymbols.ELT_PATTERN)) {
if (pattern == null) {
pattern = new StringBuffer (content.getAttribute( SchemaSymbols.ATT_VALUE ));
}
else {
//datatypes: 5.2.4 pattern: src-multiple-pattern
pattern.append("|");
pattern.append(content.getAttribute( SchemaSymbols.ATT_VALUE ));
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
}
else {
if ( fFacetData.containsKey(facet) )
reportSchemaError(SchemaMessageProvider.DatatypeError,
new Object [] {"The facet '" + facet + "' is defined more than once."} );
fFacetData.put(facet,content.getAttribute( SchemaSymbols.ATT_VALUE ));
if (content.getAttribute( SchemaSymbols.ATT_FIXED).equals("true") ||
content.getAttribute( SchemaSymbols.ATT_FIXED).equals("1")){
// set fixed facet flags
// length - must remain const through derivation
// thus we don't care if it fixed
if ( facet.equals(SchemaSymbols.ELT_MINLENGTH) ) {
flags |= DatatypeValidator.FACET_MINLENGTH;
}
else if (facet.equals(SchemaSymbols.ELT_MAXLENGTH)) {
flags |= DatatypeValidator.FACET_MAXLENGTH;
}
else if (facet.equals(SchemaSymbols.ELT_MAXEXCLUSIVE)) {
flags |= DatatypeValidator.FACET_MAXEXCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MAXINCLUSIVE)) {
flags |= DatatypeValidator.FACET_MAXINCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MINEXCLUSIVE)) {
flags |= DatatypeValidator.FACET_MINEXCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MININCLUSIVE)) {
flags |= DatatypeValidator.FACET_MININCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_TOTALDIGITS)) {
flags |= DatatypeValidator.FACET_TOTALDIGITS;
}
else if (facet.equals(SchemaSymbols.ELT_FRACTIONDIGITS)) {
flags |= DatatypeValidator.FACET_FRACTIONDIGITS;
}
else if (facet.equals(SchemaSymbols.ELT_WHITESPACE) &&
baseValidator instanceof StringDatatypeValidator) {
flags |= DatatypeValidator.FACET_WHITESPACE;
}
}
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
}
content = XUtil.getNextSiblingElement(content);
}
if (numEnumerationLiterals > 0) {
fFacetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
if (pattern !=null) {
fFacetData.put(SchemaSymbols.ELT_PATTERN, pattern.toString());
}
if (flags != 0) {
fFacetData.put(DatatypeValidator.FACET_FIXED, new Short(flags));
}
}
else if (list && content!=null) {
// report error - must not have any children!
if (baseTypeQNameProperty.length() != 0) {
content = checkContent(simpleTypeDecl, content, true);
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
//REVISIT: should we return?
}
}
else if (union && content!=null) {
//report error - must not have any children!
if (baseTypeQNameProperty.length() != 0) {
content = checkContent(simpleTypeDecl, content, true);
if (content!=null) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
//REVISIT: should we return?
}
}
// create & register validator for "generated" type if it doesn't exist
try {
DatatypeValidator newValidator =
fDatatypeRegistry.getDatatypeValidator( qualifiedName );
if( newValidator == null ) { // not previously registered
if (list) {
fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator,
fFacetData,true);
}
else if (restriction) {
fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator,
fFacetData,false);
}
else { //union
fDatatypeRegistry.createDatatypeValidator( qualifiedName, dTValidators);
}
}
} catch (Exception e) {
reportSchemaError(SchemaMessageProvider.DatatypeError,new Object [] { e.getMessage() });
}
return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName));
}
/*
* <any
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* namespace = (##any | ##other) | List of (anyURI | (##targetNamespace | ##local))
* processContents = lax | skip | strict>
* Content: (annotation?)
* </any>
*/
private int traverseAny(Element child) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(child, scope);
Element annotation = checkContent( child, XUtil.getFirstChildElement(child), true );
if(annotation != null ) {
// REVISIT: Localize
reportGenericSchemaError("<any> elements can contain at most one <annotation> element in their children");
}
int anyIndex = -1;
String namespace = child.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
String processContents = child.getAttribute("processContents").trim();
int processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY;
int processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER;
int processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL;
if (processContents.length() > 0 && !processContents.equals("strict")) {
if (processContents.equals("lax")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_LAX;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX;
}
else if (processContents.equals("skip")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_SKIP;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP;
}
}
if (namespace.length() == 0 || namespace.equals("##any")) {
// REVISIT: Should the "any" namespace signifier also be changed
// to StringPool.EMPTY_STRING instead of -1? -Ac
// REVISIT: is this the right way to do it? EMPTY_STRING does not
// seem to work in this case -el
// Simplify! - ng
//String uri = child.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
//???String uri = fTargetNSURIString;
//???int uriIndex = fStringPool.addSymbol(uri);
//???anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false);
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, StringPool.EMPTY_STRING, false);
}
else if (namespace.equals("##other")) {
String uri = fTargetNSURIString;
int uriIndex = fStringPool.addSymbol(uri);
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyOther, -1, uriIndex, false);
}
else if (namespace.length() > 0) {
int uriIndex, leafIndex, choiceIndex;
StringTokenizer tokenizer = new StringTokenizer(namespace);
String token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false);
} else {
if (token.equals("##targetNamespace"))
token = fTargetNSURIString;
uriIndex = fStringPool.addSymbol(token);
choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false);
}
while (tokenizer.hasMoreElements()) {
token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false);
} else {
if (token.equals("##targetNamespace"))
token = fTargetNSURIString;
uriIndex = fStringPool.addSymbol(token);
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false);
}
choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, choiceIndex, leafIndex, false);
}
anyIndex = choiceIndex;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for any element");
}
return anyIndex;
}
public DatatypeValidator getDatatypeValidator(String uri, String localpart) {
DatatypeValidator dv = null;
if (uri.length()==0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) {
dv = fDatatypeRegistry.getDatatypeValidator( localpart );
}
else {
dv = fDatatypeRegistry.getDatatypeValidator( uri+","+localpart );
}
return dv;
}
/*
* <anyAttribute
* id = ID
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}>
* Content: (annotation?)
* </anyAttribute>
*/
private XMLAttributeDecl traverseAnyAttribute(Element anyAttributeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(anyAttributeDecl, scope);
Element annotation = checkContent( anyAttributeDecl, XUtil.getFirstChildElement(anyAttributeDecl), true );
if(annotation != null ) {
// REVISIT: Localize
reportGenericSchemaError("<anyAttribute> elements can contain at most one <annotation> element in their children");
}
XMLAttributeDecl anyAttDecl = new XMLAttributeDecl();
String processContents = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_PROCESSCONTENTS).trim();
String namespace = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
// simplify! NG
//String curTargetUri = anyAttributeDecl.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
String curTargetUri = fTargetNSURIString;
if ( namespace.length() == 0 || namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDANY) ) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_ANY;
}
else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDOTHER)) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_OTHER;
anyAttDecl.name.uri = fStringPool.addSymbol(curTargetUri);
}
else if (namespace.length() > 0){
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LIST;
StringTokenizer tokenizer = new StringTokenizer(namespace);
int aStringList = fStringPool.startStringList();
Vector tokens = new Vector();
int tokenStr;
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
tokenStr = fStringPool.EMPTY_STRING;
} else {
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDTARGETNS))
token = curTargetUri;
tokenStr = fStringPool.addSymbol(token);
}
if (!fStringPool.addStringToList(aStringList, tokenStr)){
reportGenericSchemaError("Internal StringPool error when reading the "+
"namespace attribute for anyattribute declaration");
}
}
fStringPool.finishStringList(aStringList);
anyAttDecl.enumeration = aStringList;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for anyattribute declaration");
}
// default processContents is "strict";
if (processContents.equals(SchemaSymbols.ATTVAL_SKIP)){
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_SKIP;
}
else if (processContents.equals(SchemaSymbols.ATTVAL_LAX)) {
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_LAX;
}
else {
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_STRICT;
}
return anyAttDecl;
}
// Schema Component Constraint: Attribute Wildcard Intersection
// For a wildcard's {namespace constraint} value to be the intensional intersection of two other such values (call them O1 and O2): the appropriate case among the following must be true:
// 1 If O1 and O2 are the same value, then that value must be the value.
// 2 If either O1 or O2 is any, then the other must be the value.
// 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then that set, minus the negated namespace name if it was in the set, must be the value.
// 4 If both O1 and O2 are sets of (namespace names or absent), then the intersection of those sets must be the value.
// 5 If the two are negations of different namespace names, then the intersection is not expressible.
// In the case where there are more than two values, the intensional intersection is determined by identifying the intensional intersection of two of the values as above, then the intensional intersection of that value with the third (providing the first intersection was expressible), and so on as required.
private XMLAttributeDecl AWildCardIntersection(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) {
// if either one is not expressible, the result is still not expressible
if (oneAny.type == -1) {
return oneAny;
}
if (anotherAny.type == -1) {
return anotherAny;
}
// 1 If O1 and O2 are the same value, then that value must be the value.
// this one is dealt with in different branches
// 2 If either O1 or O2 is any, then the other must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return anotherAny;
}
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return oneAny;
}
// 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then that set, minus the negated namespace name if it was in the set, must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST ||
oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
XMLAttributeDecl anyList, anyOther;
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
anyList = oneAny;
anyOther = anotherAny;
} else {
anyList = anotherAny;
anyOther = oneAny;
}
int[] uriList = fStringPool.stringListAsIntArray(anyList.enumeration);
if (elementInSet(anyOther.name.uri, uriList)) {
int newList = fStringPool.startStringList();
for (int i=0; i< uriList.length; i++) {
if (uriList[i] != anyOther.name.uri ) {
fStringPool.addStringToList(newList, uriList[i]);
}
}
fStringPool.finishStringList(newList);
anyList.enumeration = newList;
}
return anyList;
}
// 4 If both O1 and O2 are sets of (namespace names or absent), then the intersection of those sets must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
int[] result = intersect2sets(fStringPool.stringListAsIntArray(oneAny.enumeration),
fStringPool.stringListAsIntArray(anotherAny.enumeration));
int newList = fStringPool.startStringList();
for (int i=0; i<result.length; i++) {
fStringPool.addStringToList(newList, result[i]);
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
// 5 If the two are negations of different namespace names, then the intersection is not expressible.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (oneAny.name.uri == anotherAny.name.uri) {
return oneAny;
} else {
oneAny.type = -1;
return oneAny;
}
}
// should never go there;
return oneAny;
}
// Schema Component Constraint: Attribute Wildcard Union
// For a wildcard's {namespace constraint} value to be the intensional union of two other such values (call them O1 and O2): the appropriate case among the following must be true:
// 1 If O1 and O2 are the same value, then that value must be the value.
// 2 If either O1 or O2 is any, then any must be the value.
// 3 If both O1 and O2 are sets of (namespace names or absent), then the union of those sets must be the value.
// 4 If the two are negations of different namespace names, then any must be the value.
// 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then The appropriate case among the following must be true:
// 5.1 If the set includes the negated namespace name, then any must be the value.
// 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value.
// In the case where there are more than two values, the intensional union is determined by identifying the intensional union of two of the values as above, then the intensional union of that value with the third, and so on as required.
private XMLAttributeDecl AWildCardUnion(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) {
// if either one is not expressible, the result is still not expressible
if (oneAny.type == -1) {
return oneAny;
}
if (anotherAny.type == -1) {
return anotherAny;
}
// 1 If O1 and O2 are the same value, then that value must be the value.
// this one is dealt with in different branches
// 2 If either O1 or O2 is any, then any must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return oneAny;
}
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return anotherAny;
}
// 3 If both O1 and O2 are sets of (namespace names or absent), then the union of those sets must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
int[] result = union2sets(fStringPool.stringListAsIntArray(oneAny.enumeration),
fStringPool.stringListAsIntArray(anotherAny.enumeration));
int newList = fStringPool.startStringList();
for (int i=0; i<result.length; i++) {
fStringPool.addStringToList(newList, result[i]);
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
// 4 If the two are negations of different namespace names, then any must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (oneAny.name.uri == anotherAny.name.uri) {
return oneAny;
} else {
oneAny.type = XMLAttributeDecl.TYPE_ANY_ANY;
return oneAny;
}
}
// 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then The appropriate case among the following must be true:
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST ||
oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
XMLAttributeDecl anyList, anyOther;
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
anyList = oneAny;
anyOther = anotherAny;
} else {
anyList = anotherAny;
anyOther = oneAny;
}
// 5.1 If the set includes the negated namespace name, then any must be the value.
if (elementInSet(anyOther.name.uri,
fStringPool.stringListAsIntArray(anyList.enumeration))) {
anyOther.type = XMLAttributeDecl.TYPE_ANY_ANY;
}
// 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value.
return anyOther;
}
// should never go there;
return oneAny;
}
// Schema Component Constraint: Wildcard Subset
// For a namespace constraint (call it sub) to be an intensional subset of another namespace constraint (call it super) one of the following must be true:
// 1 super must be any.
// 2 All of the following must be true:
// 2.1 sub must be a pair of not and a namespace name or absent.
// 2.2 super must be a pair of not and the same value.
// 3 All of the following must be true:
// 3.1 sub must be a set whose members are either namespace names or absent.
// 3.2 One of the following must be true:
// 3.2.1 super must be the same set or a superset thereof.
// 3.2.2 super must be a pair of not and a namespace name or absent and that value must not be in sub's set.
private boolean AWildCardSubset(XMLAttributeDecl subAny, XMLAttributeDecl superAny) {
// if either one is not expressible, it can't be a subset
if (subAny.type == -1 || superAny.type == -1)
return false;
// 1 super must be any.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_ANY)
return true;
// 2 All of the following must be true:
// 2.1 sub must be a pair of not and a namespace name or absent.
if (subAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
// 2.2 super must be a pair of not and the same value.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
subAny.name.uri == superAny.name.uri) {
return true;
}
}
// 3 All of the following must be true:
// 3.1 sub must be a set whose members are either namespace names or absent.
if (subAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
// 3.2 One of the following must be true:
// 3.2.1 super must be the same set or a superset thereof.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
subset2sets(fStringPool.stringListAsIntArray(subAny.enumeration),
fStringPool.stringListAsIntArray(superAny.enumeration))) {
return true;
}
// 3.2.2 super must be a pair of not and a namespace name or absent and that value must not be in sub's set.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
!elementInSet(superAny.name.uri, fStringPool.stringListAsIntArray(superAny.enumeration))) {
return true;
}
}
return false;
}
// Validation Rule: Wildcard allows Namespace Name
// For a value which is either a namespace name or absent to be valid with respect to a wildcard constraint (the value of a {namespace constraint}) one of the following must be true:
// 1 The constraint must be any.
// 2 All of the following must be true:
// 2.1 The constraint is a pair of not and a namespace name or absent ([Definition:] call this the namespace test).
// 2.2 The value must not be identical to the namespace test.
// 2.3 The value must not be absent.
// 3 The constraint is a set, and the value is identical to one of the members of the set.
private boolean AWildCardAllowsNameSpace(XMLAttributeDecl wildcard, String uri) {
// if the constrain is not expressible, then nothing is allowed
if (wildcard.type == -1)
return false;
// 1 The constraint must be any.
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_ANY)
return true;
int uriStr = fStringPool.addString(uri);
// 2 All of the following must be true:
// 2.1 The constraint is a pair of not and a namespace name or absent ([Definition:] call this the namespace test).
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
// 2.2 The value must not be identical to the namespace test.
// 2.3 The value must not be absent.
if (uriStr != wildcard.name.uri && uriStr != StringPool.EMPTY_STRING)
return true;
}
// 3 The constraint is a set, and the value is identical to one of the members of the set.
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_LIST) {
if (elementInSet(uriStr, fStringPool.stringListAsIntArray(wildcard.enumeration)))
return true;
}
return false;
}
private boolean isAWildCard(XMLAttributeDecl a) {
if (a.type == XMLAttributeDecl.TYPE_ANY_ANY
||a.type == XMLAttributeDecl.TYPE_ANY_LIST
||a.type == XMLAttributeDecl.TYPE_ANY_OTHER )
return true;
else
return false;
}
int[] intersect2sets(int[] one, int[] theOther){
int[] result = new int[(one.length>theOther.length?one.length:theOther.length)];
// simple implemention,
int count = 0;
for (int i=0; i<one.length; i++) {
if (elementInSet(one[i], theOther))
result[count++] = one[i];
}
int[] result2 = new int[count];
System.arraycopy(result, 0, result2, 0, count);
return result2;
}
int[] union2sets(int[] one, int[] theOther){
int[] result1 = new int[one.length];
// simple implemention,
int count = 0;
for (int i=0; i<one.length; i++) {
if (!elementInSet(one[i], theOther))
result1[count++] = one[i];
}
int[] result2 = new int[count+theOther.length];
System.arraycopy(result1, 0, result2, 0, count);
System.arraycopy(theOther, 0, result2, count, theOther.length);
return result2;
}
boolean subset2sets(int[] subSet, int[] superSet){
for (int i=0; i<subSet.length; i++) {
if (!elementInSet(subSet[i], superSet))
return false;
}
return true;
}
boolean elementInSet(int ele, int[] set){
boolean found = false;
for (int i=0; i<set.length && !found; i++) {
if (ele==set[i])
found = true;
}
return found;
}
// wrapper traverseComplexTypeDecl method
private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception {
return traverseComplexTypeDecl (complexTypeDecl, false);
}
/**
* Traverse ComplexType Declaration - Rec Implementation.
*
* <complexType
* abstract = boolean
* block = #all or (possibly empty) subset of {extension, restriction}
* final = #all or (possibly empty) subset of {extension, restriction}
* id = ID
* mixed = boolean : false
* name = NCName>
* Content: (annotation? , (simpleContent | complexContent |
* ( (group | all | choice | sequence)? ,
* ( (attribute | attributeGroup)* , anyAttribute?))))
* </complexType>
* @param complexTypeDecl
* @param forwardRef
* @return
*/
private int traverseComplexTypeDecl( Element complexTypeDecl, boolean forwardRef)
throws Exception {
// General Attribute Checking
int scope = isTopLevel(complexTypeDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexTypeDecl, scope);
// Get the attributes of the type
String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT );
String blockSet = null;
Attr blockAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_BLOCK );
if (blockAttr != null)
blockSet = blockAttr.getValue();
String finalSet = null;
Attr finalAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_FINAL );
if (finalAttr != null)
finalSet = finalAttr.getValue();
String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID );
String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME);
String mixed = complexTypeDecl.getAttribute(SchemaSymbols.ATT_MIXED);
boolean isNamedType = false;
// Generate a type name, if one wasn't specified
if (typeName.equals("")) { // gensym a unique name
typeName = genAnonTypeName(complexTypeDecl);
}
if ( DEBUGGING )
System.out.println("traversing complex Type : " + typeName);
fCurrentTypeNameStack.push(typeName);
int typeNameIndex = fStringPool.addSymbol(typeName);
// Check if the type has already been registered
if (isTopLevel(complexTypeDecl)) {
String fullName = fTargetNSURIString+","+typeName;
ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName);
if (temp != null ) {
// check for duplicate declarations
if (!forwardRef) {
if (temp.declSeen())
reportGenericSchemaError("sch-props-correct: Duplicate declaration for complexType " +
typeName);
else
temp.setDeclSeen();
}
return fStringPool.addSymbol(fullName);
}
else {
// check if the type is the name of a simple type
if (getDatatypeValidator(fTargetNSURIString,typeName)!=null)
reportGenericSchemaError("sch-props-correct: Duplicate type declaration - type is " +
typeName);
}
}
int scopeDefined = fScopeCount++;
int previousScope = fCurrentScope;
fCurrentScope = scopeDefined;
Element child = null;
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
try {
// First, handle any ANNOTATION declaration and get next child
child = checkContent(complexTypeDecl,XUtil.getFirstChildElement(complexTypeDecl),
true);
// Process the content of the complex type declaration
if (child==null) {
// EMPTY complexType with complexContent
processComplexContent(typeNameIndex, child, typeInfo, null, false);
}
else {
String childName = child.getLocalName();
int index = -2;
if (childName.equals(SchemaSymbols.ELT_SIMPLECONTENT)) {
// SIMPLE CONTENT element
traverseSimpleContentDecl(typeNameIndex, child, typeInfo);
if (XUtil.getNextSiblingElement(child) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the simpleContent child in the complexType");
}
else if (childName.equals(SchemaSymbols.ELT_COMPLEXCONTENT)) {
// COMPLEX CONTENT element
traverseComplexContentDecl(typeNameIndex, child, typeInfo,
mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false);
if (XUtil.getNextSiblingElement(child) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the complexContent child in the complexType");
}
else {
// We must have ....
// GROUP, ALL, SEQUENCE or CHOICE, followed by optional attributes
// Note that it's possible that only attributes are specified.
processComplexContent(typeNameIndex, child, typeInfo, null,
mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false);
}
}
typeInfo.blockSet = parseBlockSet(blockSet);
// make sure block's value was absent, #all or in {extension, restriction}
if( (blockSet != null ) && !blockSet.equals("") &&
(!blockSet.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((typeInfo.blockSet & SchemaSymbols.RESTRICTION) == 0) &&
((typeInfo.blockSet & SchemaSymbols.EXTENSION) == 0))))
throw new ComplexTypeRecoverableError("The values of the 'block' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + blockSet + " was found");
typeInfo.finalSet = parseFinalSet(finalSet);
// make sure final's value was absent, #all or in {extension, restriction}
if( (finalSet != null ) && !finalSet.equals("") &&
(!finalSet.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((typeInfo.finalSet & SchemaSymbols.RESTRICTION) == 0) &&
((typeInfo.finalSet & SchemaSymbols.EXTENSION) == 0))))
throw new ComplexTypeRecoverableError("The values of the 'final' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + finalSet + " was found");
}
catch (ComplexTypeRecoverableError e) {
String message = e.getMessage();
handleComplexTypeError(message,typeNameIndex,typeInfo);
}
// Finish the setup of the typeInfo and register the type
typeInfo.scopeDefined = scopeDefined;
if (isAbstract.equals(SchemaSymbols.ATTVAL_TRUE))
typeInfo.setIsAbstractType();
if (!forwardRef)
typeInfo.setDeclSeen();
typeName = fTargetNSURIString + "," + typeName;
typeInfo.typeName = new String(typeName);
if ( DEBUGGING )
System.out.println(">>>add complex Type to Registry: " + typeName +
" baseDTValidator=" + typeInfo.baseDataTypeValidator +
" baseCTInfo=" + typeInfo.baseComplexTypeInfo +
" derivedBy=" + typeInfo.derivedBy +
" contentType=" + typeInfo.contentType +
" contentSpecHandle=" + typeInfo.contentSpecHandle +
" datatypeValidator=" + typeInfo.datatypeValidator);
fComplexTypeRegistry.put(typeName,typeInfo);
// Before exiting, restore the scope, mainly for nested anonymous types
fCurrentScope = previousScope;
fCurrentTypeNameStack.pop();
checkRecursingComplexType();
//set template element's typeInfo
fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo);
typeNameIndex = fStringPool.addSymbol(typeName);
return typeNameIndex;
} // end traverseComplexTypeDecl
/**
* Traverse SimpleContent Declaration
*
* <simpleContent
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (restriction | extension))
* </simpleContent>
*
* <restriction
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation?,(simpleType?, (minExclusive|minInclusive|maxExclusive
* | maxInclusive | totalDigits | fractionDigits | length | minLength
* | maxLength | encoding | period | duration | enumeration
* | pattern | whiteSpace)*) ? ,
* ((attribute | attributeGroup)* , anyAttribute?))
* </restriction>
*
* <extension
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
* Content: (annotation? , ((attribute | attributeGroup)* , anyAttribute?))
* </extension>
*
* @param typeNameIndex
* @param simpleContentTypeDecl
* @param typeInfo
* @return
*/
private void traverseSimpleContentDecl(int typeNameIndex,
Element simpleContentDecl, ComplexTypeInfo typeInfo)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleContentDecl, scope);
String typeName = fStringPool.toString(typeNameIndex);
// Get attributes.
String simpleContentTypeId = simpleContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID);
// Set the content type to be simple, and initialize content spec handle
typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
typeInfo.contentSpecHandle = -1;
Element simpleContent = checkContent(simpleContentDecl,
XUtil.getFirstChildElement(simpleContentDecl),false);
// If there are no children, return
if (simpleContent==null) {
throw new ComplexTypeRecoverableError();
}
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(simpleContent, scope);
// The content should be either "restriction" or "extension"
String simpleContentName = simpleContent.getLocalName();
if (simpleContentName.equals(SchemaSymbols.ELT_RESTRICTION))
typeInfo.derivedBy = SchemaSymbols.RESTRICTION;
else if (simpleContentName.equals(SchemaSymbols.ELT_EXTENSION))
typeInfo.derivedBy = SchemaSymbols.EXTENSION;
else {
throw new ComplexTypeRecoverableError(
"The content of the simpleContent element is invalid. The " +
"content must be RESTRICTION or EXTENSION");
}
// Get the attributes of the restriction/extension element
String base = simpleContent.getAttribute(SchemaSymbols.ATT_BASE);
String typeId = simpleContent.getAttribute(SchemaSymbols.ATTVAL_ID);
// Skip over any annotations in the restriction or extension elements
Element content = checkContent(simpleContent,
XUtil.getFirstChildElement(simpleContent),true);
// Handle the base type name
if (base.length() == 0) {
throw new ComplexTypeRecoverableError(
"The BASE attribute must be specified for the " +
"RESTRICTION or EXTENSION element");
}
QName baseQName = parseBase(base);
// check if we're extending a simpleType which has a "final" setting which precludes this
Integer finalValue = (baseQName.uri == StringPool.EMPTY_STRING?
((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.localpart))):
((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.uri) + "," +fStringPool.toString(baseQName.localpart))));
if(finalValue != null &&
(finalValue.intValue() == typeInfo.derivedBy))
throw new ComplexTypeRecoverableError(
"The simpleType " + base + " that " + typeName + " uses has a value of \"final\" which does not permit extension");
processBaseTypeInfo(baseQName,typeInfo);
// check that the base isn't a complex type with complex content
if (typeInfo.baseComplexTypeInfo != null) {
if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_SIMPLE) {
throw new ComplexTypeRecoverableError(
"The type '"+ base +"' specified as the " +
"base in the simpleContent element must not have complexContent");
}
}
// Process the content of the derivation
Element attrNode = null;
// RESTRICTION
if (typeInfo.derivedBy==SchemaSymbols.RESTRICTION) {
//Schema Spec : Complex Type Definition Properties Correct : 2
if (typeInfo.baseDataTypeValidator != null) {
throw new ComplexTypeRecoverableError(
"ct-props-correct.2: The type '" + base +"' is a simple type. It cannot be used in a "+
"derivation by RESTRICTION for a complexType");
}
else {
typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator;
}
// Check that the base's final set does not include RESTRICTION
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0) {
throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + base + " or the schema");
}
// There may be a simple type definition in the restriction element
// The data type validator will be based on it, if specified
if (content.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE )) {
int simpleTypeNameIndex = traverseSimpleTypeDecl(content);
if (simpleTypeNameIndex!=-1) {
typeInfo.baseDataTypeValidator=fDatatypeRegistry.getDatatypeValidator(
fStringPool.toString(simpleTypeNameIndex));
content = XUtil.getNextSiblingElement(content);
}
else {
throw new ComplexTypeRecoverableError();
}
}
// Build up facet information
int numEnumerationLiterals = 0;
int numFacets = 0;
Hashtable facetData = new Hashtable();
Vector enumData = new Vector();
Element child;
// General Attribute Checking
scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable contentAttrs;
//REVISIT: there is a better way to do this,
for (child = content;
child != null && (child.getLocalName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MININCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_TOTALDIGITS) ||
child.getLocalName().equals(SchemaSymbols.ELT_FRACTIONDIGITS) ||
child.getLocalName().equals(SchemaSymbols.ELT_LENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_MINLENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXLENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_PERIOD) ||
child.getLocalName().equals(SchemaSymbols.ELT_DURATION) ||
child.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION) ||
child.getLocalName().equals(SchemaSymbols.ELT_PATTERN) ||
child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION));
child = XUtil.getNextSiblingElement(child))
{
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element facetElt = (Element) child;
// General Attribute Checking
contentAttrs = fGeneralAttrCheck.checkAttributes(facetElt, scope);
numFacets++;
if (facetElt.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE));
//Enumerations can have annotations ? ( 0 | 1 )
Element enumContent = XUtil.getFirstChildElement( facetElt );
if( enumContent != null &&
enumContent.getLocalName().equals
( SchemaSymbols.ELT_ANNOTATION )){
traverseAnnotationDecl( child );
}
// TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over
}
else {
facetData.put(facetElt.getLocalName(),
facetElt.getAttribute( SchemaSymbols.ATT_VALUE ));
}
}
} // end of for loop thru facets
if (numEnumerationLiterals > 0) {
facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
// If there were facets, create a new data type validator, otherwise
// the data type validator is from the base
if (numFacets > 0) {
try{
typeInfo.datatypeValidator = fDatatypeRegistry.createDatatypeValidator(
typeName,
typeInfo.baseDataTypeValidator, facetData, false);
} catch (Exception e) {
throw new ComplexTypeRecoverableError(e.getMessage());
}
}
else
typeInfo.datatypeValidator =
typeInfo.baseDataTypeValidator;
if (child != null) {
// Check that we have attributes
if (!isAttrOrAttrGroup(child)) {
throw new ComplexTypeRecoverableError(
"Invalid child in the RESTRICTION element of simpleContent");
}
else
attrNode = child;
}
} // end RESTRICTION
// EXTENSION
else {
if (typeInfo.baseComplexTypeInfo != null) {
typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator;
// Check that the base's final set does not include EXTENSION
if((typeInfo.baseComplexTypeInfo.finalSet &
SchemaSymbols.EXTENSION) != 0) {
throw new ComplexTypeRecoverableError("Derivation by extension is forbidden by either the base type " + base + " or the schema");
}
}
typeInfo.datatypeValidator = typeInfo.baseDataTypeValidator;
// Look for attributes
if (content != null) {
// Check that we have attributes
if (!isAttrOrAttrGroup(content)) {
throw new ComplexTypeRecoverableError(
"Only annotations and attributes are allowed in the " +
"content of an EXTENSION element for a complexType with simpleContent");
}
else {
attrNode = content;
}
}
}
// add a template element to the grammar element decl pool for the type
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
// Process attributes
processAttributes(attrNode,baseQName,typeInfo);
if (XUtil.getNextSiblingElement(simpleContent) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the RESTRICTION or EXTENSION element in the " +
"complex type definition");
} // end traverseSimpleContentDecl
/**
* Traverse complexContent Declaration
*
* <complexContent
* id = ID
* mixed = boolean
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (restriction | extension))
* </complexContent>
*
* <restriction
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (group | all | choice | sequence)?,
* ((attribute | attributeGroup)* , anyAttribute?))
* </restriction>
*
* <extension
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
* Content: (annotation? , (group | all | choice | sequence)?,
* ((attribute | attributeGroup)* , anyAttribute?))
* </extension>
*
* @param typeNameIndex
* @param simpleContentTypeDecl
* @param typeInfo
* @param mixedOnComplexTypeDecl
* @return
*/
private void traverseComplexContentDecl(int typeNameIndex,
Element complexContentDecl, ComplexTypeInfo typeInfo,
boolean mixedOnComplexTypeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexContentDecl, scope);
String typeName = fStringPool.toString(typeNameIndex);
// Get the attributes
String typeId = complexContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID);
String mixed = complexContentDecl.getAttribute(SchemaSymbols.ATT_MIXED);
// Determine whether the content is mixed, or element-only
// Setting here overrides any setting on the complex type decl
boolean isMixed = mixedOnComplexTypeDecl;
if (mixed.equals(SchemaSymbols.ATTVAL_TRUE))
isMixed = true;
else if (mixed.equals(SchemaSymbols.ATTVAL_FALSE))
isMixed = false;
// Since the type must have complex content, set the simple type validators
// to null
typeInfo.datatypeValidator = null;
typeInfo.baseDataTypeValidator = null;
Element complexContent = checkContent(complexContentDecl,
XUtil.getFirstChildElement(complexContentDecl),false);
// If there are no children, return
if (complexContent==null) {
throw new ComplexTypeRecoverableError();
}
// The content should be either "restriction" or "extension"
String complexContentName = complexContent.getLocalName();
if (complexContentName.equals(SchemaSymbols.ELT_RESTRICTION))
typeInfo.derivedBy = SchemaSymbols.RESTRICTION;
else if (complexContentName.equals(SchemaSymbols.ELT_EXTENSION))
typeInfo.derivedBy = SchemaSymbols.EXTENSION;
else {
throw new ComplexTypeRecoverableError(
"The content of the complexContent element is invalid. " +
"The content must be RESTRICTION or EXTENSION");
}
// Get the attributes of the restriction/extension element
String base = complexContent.getAttribute(SchemaSymbols.ATT_BASE);
String complexContentTypeId=complexContent.getAttribute(SchemaSymbols.ATTVAL_ID);
// Skip over any annotations in the restriction or extension elements
Element content = checkContent(complexContent,
XUtil.getFirstChildElement(complexContent),true);
// Handle the base type name
if (base.length() == 0) {
throw new ComplexTypeRecoverableError(
"The BASE attribute must be specified for the " +
"RESTRICTION or EXTENSION element");
}
QName baseQName = parseBase(base);
// check if the base is "anyType"
String baseTypeURI = fStringPool.toString(baseQName.uri);
String baseLocalName = fStringPool.toString(baseQName.localpart);
if (!(baseTypeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) &&
baseLocalName.equals("anyType"))) {
processBaseTypeInfo(baseQName,typeInfo);
//Check that the base is a complex type
if (typeInfo.baseComplexTypeInfo == null) {
throw new ComplexTypeRecoverableError(
"The base type specified in the complexContent element must be a complexType");
}
}
// Process the elements that make up the content
processComplexContent(typeNameIndex,content,typeInfo,baseQName,isMixed);
if (XUtil.getNextSiblingElement(complexContent) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the RESTRICTION or EXTENSION element in the " +
"complex type definition");
} // end traverseComplexContentDecl
/**
* Handle complexType error
*
* @param message
* @param typeNameIndex
* @param typeInfo
* @return
*/
private void handleComplexTypeError(String message, int typeNameIndex,
ComplexTypeInfo typeInfo) throws Exception {
String typeName = fStringPool.toString(typeNameIndex);
if (message != null) {
if (typeName.startsWith("
reportGenericSchemaError("Anonymous complexType: " + message);
else
reportGenericSchemaError("ComplexType '" + typeName + "': " + message);
}
// Mock up the typeInfo structure so that there won't be problems during
// validation
typeInfo.contentType = XMLElementDecl.TYPE_ANY; // this should match anything
typeInfo.contentSpecHandle = -1;
typeInfo.derivedBy = 0;
typeInfo.datatypeValidator = null;
typeInfo.attlistHead = -1;
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
return;
}
/**
* Generate a name for an anonymous type
*
* @param Element
* @return String
*/
private String genAnonTypeName(Element complexTypeDecl) throws Exception {
String typeName;
// If the anonymous type is not nested within another type, we can
// simply assign the type a numbered name
if (fCurrentTypeNameStack.empty())
typeName = "#"+fAnonTypeCount++;
// Otherwise, we must generate a name that can be looked up later
// Do this by concatenating outer type names with the name of the parent
// element
else {
String parentName = ((Element)complexTypeDecl.getParentNode()).getAttribute(
SchemaSymbols.ATT_NAME);
typeName = parentName + "_AnonType";
int index=fCurrentTypeNameStack.size() -1;
for (int i = index; i > -1; i
String parentType = (String)fCurrentTypeNameStack.elementAt(i);
typeName = parentType + "_" + typeName;
if (!(parentType.startsWith("
break;
}
typeName = "#" + typeName;
}
return typeName;
}
/**
* Parse base string
*
* @param base
* @return QName
*/
private QName parseBase(String base) throws Exception {
String prefix = "";
String localpart = base;
int colonptr = base.indexOf(":");
if ( colonptr > 0) {
prefix = base.substring(0,colonptr);
localpart = base.substring(colonptr+1);
}
int nameIndex = fStringPool.addSymbol(base);
int prefixIndex = fStringPool.addSymbol(prefix);
int localpartIndex = fStringPool.addSymbol(localpart);
int URIindex = fStringPool.addSymbol(resolvePrefixToURI(prefix));
return new QName(prefixIndex,localpartIndex,nameIndex,URIindex);
}
/**
* Check if base is from another schema
*
* @param baseName
* @return boolean
*/
private boolean baseFromAnotherSchema(QName baseName) throws Exception {
String typeURI = fStringPool.toString(baseName.uri);
if ( ! typeURI.equals(fTargetNSURIString)
&& ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0 )
//REVISIT, !!!! a hack: for schema that has no
//target namespace, e.g. personal-schema.xml
return true;
else
return false;
}
/**
* Process "base" information for a complexType
*
* @param baseTypeInfo
* @param baseName
* @param typeInfo
* @return
*/
private void processBaseTypeInfo(QName baseName, ComplexTypeInfo typeInfo) throws Exception {
ComplexTypeInfo baseComplexTypeInfo = null;
DatatypeValidator baseDTValidator = null;
String typeURI = fStringPool.toString(baseName.uri);
String localpart = fStringPool.toString(baseName.localpart);
String base = fStringPool.toString(baseName.rawname);
// check if the base type is from another schema
if (baseFromAnotherSchema(baseName)) {
baseComplexTypeInfo = getTypeInfoFromNS(typeURI, localpart);
if (baseComplexTypeInfo == null) {
baseDTValidator = getTypeValidatorFromNS(typeURI, localpart);
if (baseDTValidator == null) {
throw new ComplexTypeRecoverableError(
"Could not find base type " +localpart
+ " in schema " + typeURI);
}
}
}
// type must be from same schema
else {
String fullBaseName = typeURI+","+localpart;
// assume the base is a complexType and try to locate the base type first
baseComplexTypeInfo= (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName);
// if not found, 2 possibilities:
// 1: ComplexType in question has not been compiled yet;
// 2: base is SimpleTYpe;
if (baseComplexTypeInfo == null) {
baseDTValidator = getDatatypeValidator(typeURI, localpart);
if (baseDTValidator == null) {
int baseTypeSymbol;
Element baseTypeNode = getTopLevelComponentByName(
SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (baseTypeNode != null) {
// Before traversing the base, make sure we're not already
// doing so..
// ct-props-correct 3
if (fCurrentTypeNameStack.search((Object)localpart) > - 1) {
throw new ComplexTypeRecoverableError(
"ct-props-correct.3: Recursive type definition");
}
baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode, true );
baseComplexTypeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol));
//REVISIT: should it be fullBaseName;
}
else {
baseTypeNode = getTopLevelComponentByName(
SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode );
baseDTValidator = getDatatypeValidator(typeURI, localpart);
if (baseDTValidator == null) {
//TO DO: signal error here.
}
}
else {
throw new ComplexTypeRecoverableError(
"Base type could not be found : " + base);
}
}
}
}
} // end else (type must be from same schema)
typeInfo.baseComplexTypeInfo = baseComplexTypeInfo;
typeInfo.baseDataTypeValidator = baseDTValidator;
} // end processBaseTypeInfo
/**
* Process content which is complex
*
* (group | all | choice | sequence) ? ,
* ((attribute | attributeGroup)* , anyAttribute?))
*
* @param typeNameIndex
* @param complexContentChild
* @param typeInfo
* @return
*/
private void processComplexContent(int typeNameIndex,
Element complexContentChild, ComplexTypeInfo typeInfo, QName baseName,
boolean isMixed) throws Exception {
Element attrNode = null;
int index=-2;
String typeName = fStringPool.toString(typeNameIndex);
if (complexContentChild != null) {
// GROUP, ALL, SEQUENCE or CHOICE, followed by attributes, if specified.
// Note that it's possible that only attributes are specified.
String childName = complexContentChild.getLocalName();
if (childName.equals(SchemaSymbols.ELT_GROUP)) {
int groupIndex = traverseGroupDecl(complexContentChild);
index = handleOccurrences(groupIndex,
complexContentChild,
hasAllContent(groupIndex) ? GROUP_REF_WITH_ALL :
NOT_ALL_CONTEXT);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = handleOccurrences(traverseSequence(complexContentChild),
complexContentChild);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = handleOccurrences(traverseChoice(complexContentChild),
complexContentChild);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = handleOccurrences(traverseAll(complexContentChild),
complexContentChild, PROCESSING_ALL);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (isAttrOrAttrGroup(complexContentChild)) {
// reset the contentType
typeInfo.contentType = XMLElementDecl.TYPE_ANY;
attrNode = complexContentChild;
}
else {
throw new ComplexTypeRecoverableError(
"Invalid child '"+ childName +"' in the complex type");
}
}
typeInfo.contentSpecHandle = index;
// Merge in information from base, if it exists
if (typeInfo.baseComplexTypeInfo != null) {
int baseContentSpecHandle = typeInfo.baseComplexTypeInfo.contentSpecHandle;
// RESTRICTION
if (typeInfo.derivedBy == SchemaSymbols.RESTRICTION) {
// check to see if the baseType permits derivation by restriction
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0)
throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema");
// if the content is EMPTY, check that the base is correct
// according to derivation-ok-restriction 5.2
if (typeInfo.contentSpecHandle==-2) {
if (!(typeInfo.baseComplexTypeInfo.contentType==XMLElementDecl.TYPE_EMPTY ||
particleEmptiable(baseContentSpecHandle))) {
throw new ComplexTypeRecoverableError("derivation-ok-restrictoin.5.2 Content type of complexType is EMPTY but base is not EMPTY or does not have a particle which is emptiable");
}
}
// The hairy derivation by restriction particle constraints
// derivation-ok-restriction 5.3
else {
try {
checkParticleDerivationOK(typeInfo.contentSpecHandle,fCurrentScope,
baseContentSpecHandle,typeInfo.baseComplexTypeInfo.scopeDefined,
typeInfo.baseComplexTypeInfo);
}
catch (ParticleRecoverableError e) {
String message = e.getMessage();
throw new ComplexTypeRecoverableError(message);
}
}
}
// EXTENSION
else {
// check to see if the baseType permits derivation by extension
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.EXTENSION) != 0)
throw new ComplexTypeRecoverableError("cos-ct-extends.1.1: Derivation by extension is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema");
// Check if the contentType of the base is consistent with the new type
// cos-ct-extends.1.4.2.2
if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_EMPTY) {
if (((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_CHILDREN) &&
isMixed) ||
((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX) &&
!isMixed)) {
throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.2.2.1: The content type of the base type " +
fStringPool.toString(baseName.localpart) + " and derived type " +
typeName + " must both be mixed or element-only");
}
}
// Compose the final content model by concatenating the base and the
// current in sequence
if (baseFromAnotherSchema(baseName)) {
String baseSchemaURI = fStringPool.toString(baseName.uri);
SchemaGrammar aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar(
baseSchemaURI);
baseContentSpecHandle = importContentSpec(aGrammar, baseContentSpecHandle);
}
if (typeInfo.contentSpecHandle == -2) {
typeInfo.contentSpecHandle = baseContentSpecHandle;
}
else if (baseContentSpecHandle > -1) {
if (typeInfo.contentSpecHandle > -1 &&
(hasAllContent(typeInfo.contentSpecHandle) ||
hasAllContent(baseContentSpecHandle))) {
throw new ComplexTypeRecoverableError("cos-all-limited: An \"all\" model group that is part of a complex type definition must constitute the entire {content type} of the definition.");
}
typeInfo.contentSpecHandle =
fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
baseContentSpecHandle,
typeInfo.contentSpecHandle,
false);
}
// Check that there is a particle in the final content
// cos-ct-extends.1.4.2.1
// LM - commented out until I get a clarification from HT
if (typeInfo.contentSpecHandle <0) {
throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.1: The content of a type derived by EXTENSION must contain a particle");
}
}
}
else {
typeInfo.derivedBy = 0;
}
// Set the content type
if (isMixed) {
// if there are no children, detect an error
// See the definition of content type in Structures 3.4.1
if (typeInfo.contentSpecHandle == -2) {
throw new ComplexTypeRecoverableError("Type '" + typeName + "': The content of a mixed complexType must not be empty");
}
else
typeInfo.contentType = XMLElementDecl.TYPE_MIXED_COMPLEX;
}
else if (typeInfo.contentSpecHandle == -2)
typeInfo.contentType = XMLElementDecl.TYPE_EMPTY;
else
typeInfo.contentType = XMLElementDecl.TYPE_CHILDREN;
// add a template element to the grammar element decl pool.
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
// Now, check attributes and handle
if (attrNode !=null) {
if (!isAttrOrAttrGroup(attrNode)) {
throw new ComplexTypeRecoverableError(
"Invalid child "+ attrNode.getLocalName() + " in the complexType or complexContent");
}
else
processAttributes(attrNode,baseName,typeInfo);
}
else if (typeInfo.baseComplexTypeInfo != null)
processAttributes(null,baseName,typeInfo);
} // end processComplexContent
/**
* Process attributes of a complex type
*
* @param attrNode
* @param typeInfo
* @return
*/
private void processAttributes(Element attrNode, QName baseName,
ComplexTypeInfo typeInfo) throws Exception {
XMLAttributeDecl attWildcard = null;
Vector anyAttDecls = new Vector();
Element child;
for (child = attrNode;
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
traverseAttributeDecl(child, typeInfo, false);
}
else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child,typeInfo,anyAttDecls);
}
else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
attWildcard = traverseAnyAttribute(child);
}
else {
throw new ComplexTypeRecoverableError( "Invalid child among the children of the complexType definition");
}
}
if (attWildcard != null) {
XMLAttributeDecl fromGroup = null;
final int count = anyAttDecls.size();
if ( count > 0) {
fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0);
for (int i=1; i<count; i++) {
fromGroup = AWildCardIntersection(
fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i));
}
}
if (fromGroup != null) {
int saveProcessContents = attWildcard.defaultType;
attWildcard = AWildCardIntersection(attWildcard, fromGroup);
attWildcard.defaultType = saveProcessContents;
}
}
else {
//REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case
if (anyAttDecls.size()>0) {
attWildcard = (XMLAttributeDecl)anyAttDecls.elementAt(0);
}
}
// merge in base type's attribute decls
XMLAttributeDecl baseAttWildcard = null;
ComplexTypeInfo baseTypeInfo = typeInfo.baseComplexTypeInfo;
SchemaGrammar aGrammar=null;
if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) {
int attDefIndex = baseTypeInfo.attlistHead;
aGrammar = fSchemaGrammar;
String baseTypeSchemaURI = baseFromAnotherSchema(baseName)?
fStringPool.toString(baseName.uri):null;
if (baseTypeSchemaURI != null) {
aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(baseTypeSchemaURI);
}
if (aGrammar == null) {
//reportGenericSchemaError("In complexType "+typeName+", can NOT find the grammar "+
// "with targetNamespace" + baseTypeSchemaURI+
// "for the base type");
}
else
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
aGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) {
if (attWildcard == null) {
baseAttWildcard = fTempAttributeDecl;
}
attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
// if found a duplicate, if it is derived by restriction,
// then skip the one from the base type
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name);
if ( temp > -1) {
if (typeInfo.derivedBy==SchemaSymbols.EXTENSION) {
reportGenericSchemaError("Attribute that appeared in the base should nnot appear in a derivation by extension");
}
else {
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
fTempAttributeDecl.name, fTempAttributeDecl.type,
fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType,
fTempAttributeDecl.defaultValue,
fTempAttributeDecl.datatypeValidator,
fTempAttributeDecl.list);
attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
// att wildcard will inserted after all attributes were processed
if (attWildcard != null) {
if (attWildcard.type != -1) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attWildcard.name, attWildcard.type,
attWildcard.enumeration, attWildcard.defaultType,
attWildcard.defaultValue,
attWildcard.datatypeValidator,
attWildcard.list);
}
else {
//REVISIT: unclear in Schema spec if should report error here.
reportGenericSchemaError("The intensional intersection for {attribute wildcard}s must be expressible");
}
}
else if (baseAttWildcard != null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
baseAttWildcard.name, baseAttWildcard.type,
baseAttWildcard.enumeration, baseAttWildcard.defaultType,
baseAttWildcard.defaultValue,
baseAttWildcard.datatypeValidator,
baseAttWildcard.list);
}
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex
(typeInfo.templateElementIndex);
// For derivation by restriction, ensure that the resulting attribute list
// satisfies the constraints in derivation-ok-restriction 2,3,4
if ((typeInfo.derivedBy==SchemaSymbols.RESTRICTION) &&
(typeInfo.attlistHead>-1 && baseTypeInfo != null)) {
checkAttributesDerivationOKRestriction(typeInfo.attlistHead,fSchemaGrammar,
attWildcard,baseTypeInfo.attlistHead,aGrammar,baseAttWildcard);
}
} // end processAttributes
// Check that the attributes of a type derived by restriction satisfy the
// constraints of derivation-ok-restriction
private void checkAttributesDerivationOKRestriction(int dAttListHead, SchemaGrammar dGrammar, XMLAttributeDecl dAttWildCard, int bAttListHead, SchemaGrammar bGrammar, XMLAttributeDecl bAttWildCard) throws ComplexTypeRecoverableError {
int attDefIndex = dAttListHead;
if (bAttListHead < 0) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2: Base type definition does not have any attributes");
}
// Loop thru the attributes
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
dGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (isAWildCard(fTempAttributeDecl)) {
attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
int bAttDefIndex = bGrammar.findAttributeDecl(bAttListHead, fTempAttributeDecl.name);
if (bAttDefIndex > -1) {
fTemp2AttributeDecl.clear();
bGrammar.getAttributeDecl(bAttDefIndex, fTemp2AttributeDecl);
// derivation-ok-restriction. Constraint 2.1.1
if ((fTemp2AttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) > 0 &&
(fTempAttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) <= 0) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.1: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation has an inconsistent REQUIRED setting to that of attribute in base");
}
// derivation-ok-restriction. Constraint 2.1.2
if (!(checkSimpleTypeDerivationOK(
fTempAttributeDecl.datatypeValidator,
fTemp2AttributeDecl.datatypeValidator))) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.2: Type of attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation must be a restriction of type of attribute in base");
}
// derivation-ok-restriction. Constraint 2.1.3
if ((fTemp2AttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) {
if (!((fTempAttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) ||
!fTempAttributeDecl.defaultValue.equals(fTemp2AttributeDecl.defaultValue)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.3: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' is either not fixed, or is not fixed with the same value as the attribute in the base");
}
}
}
else {
// derivation-ok-restriction. Constraint 2.2
if ((bAttWildCard==null) ||
!AWildCardAllowsNameSpace(bAttWildCard, dGrammar.getTargetNamespaceURI())) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.2: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' has a target namespace which is not valid with respect to a base type definition's wildcard or, the base does not contain a wildcard");
}
}
attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex);
}
// derivation-ok-restriction. Constraint 4
if (dAttWildCard!=null) {
if (bAttWildCard==null) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.1: An attribute wildcard is present in the derived type, but not the base");
}
if (!AWildCardSubset(dAttWildCard,bAttWildCard)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.2: The attribute wildcard in the derived type is not a valid subset of that in the base");
}
}
}
private boolean isAttrOrAttrGroup(Element e)
{
String elementName = e.getLocalName();
if (elementName.equals(SchemaSymbols.ELT_ATTRIBUTE) ||
elementName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ||
elementName.equals(SchemaSymbols.ELT_ANYATTRIBUTE))
return true;
else
return false;
}
private void checkRecursingComplexType() throws Exception {
if ( fCurrentTypeNameStack.empty() ) {
if (! fElementRecurseComplex.isEmpty() ) {
Enumeration e = fElementRecurseComplex.keys();
while( e.hasMoreElements() ) {
QName nameThenScope = (QName) e.nextElement();
String typeName = (String) fElementRecurseComplex.get(nameThenScope);
int eltUriIndex = nameThenScope.uri;
int eltNameIndex = nameThenScope.localpart;
int enclosingScope = nameThenScope.prefix;
ComplexTypeInfo typeInfo =
(ComplexTypeInfo) fComplexTypeRegistry.get(fTargetNSURIString+","+typeName);
if (typeInfo==null) {
throw new Exception ( "Internal Error in void checkRecursingComplexType(). " );
}
else {
int elementIndex = fSchemaGrammar.addElementDecl(new QName(-1, eltNameIndex, eltNameIndex, eltUriIndex),
enclosingScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle,
typeInfo.attlistHead,
typeInfo.datatypeValidator);
fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo);
}
}
fElementRecurseComplex.clear();
}
}
}
// Check that the particle defined by the derived ct tree is a valid restriction of
// that specified by baseContentSpecIndex. derivedScope and baseScope are the
// scopes of the particles, respectively. bInfo is supplied when the base particle
// is from a base type definition, and may be null - it helps determine other scopes
// that elements should be looked up in.
private void checkParticleDerivationOK(int derivedContentSpecIndex, int derivedScope, int baseContentSpecIndex, int baseScope, ComplexTypeInfo bInfo) throws Exception {
// Only do this if full checking is enabled
if (!fFullConstraintChecking)
return;
// Check for pointless occurrences of all, choice, sequence. The result is the
// contentspec which is not pointless. If the result is a non-pointless
// group, Vector is filled in with the children of interest
int csIndex1 = derivedContentSpecIndex;
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
int csIndex2 = baseContentSpecIndex;
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
Vector tempVector1 = new Vector();
Vector tempVector2 = new Vector();
if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_CHOICE ||
tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_ALL) {
csIndex1 = checkForPointlessOccurrences(csIndex1,tempVector1);
}
if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_CHOICE ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL) {
csIndex2 = checkForPointlessOccurrences(csIndex2,tempVector2);
}
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
switch (tempContentSpec1.type & 0x0f) {
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
switch (tempContentSpec2.type & 0x0f) {
// Elt:Elt NameAndTypeOK
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
checkNameAndTypeOK(csIndex1, derivedScope, csIndex2, baseScope, bInfo);
return;
}
// Elt:Any NSCompat
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL:
{
checkNSCompat(csIndex1, derivedScope, csIndex2);
return;
}
// Elt:All RecurseAsIfGroup
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurseAsIfGroup(csIndex1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL:
{
switch (tempContentSpec2.type & 0x0f) {
// Any:Any NSSubset
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL:
{
checkNSSubset(csIndex1, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_ALL:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Any: Choice,Seq,All,Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
switch (tempContentSpec2.type & 0x0f) {
// All:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: All:Choice,Seq,Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
switch (tempContentSpec2.type & 0x0f) {
// Choice:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
checkRecurseLax(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Choice:All,Seq,Leaf");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_SEQ:
{
switch (tempContentSpec2.type & 0x0f) {
// Choice:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurseUnordered(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_SEQ:
{
checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
checkMapAndSum(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Seq:Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
}
}
private int checkForPointlessOccurrences(int csIndex, Vector tempVector) {
// Note: instead of using a Vector, we should use a growable array of int.
// To be cleaned up in release 1.4.1. (LM)
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
if (tempContentSpec1.otherValue == -2) {
gatherChildren(tempContentSpec1.type,tempContentSpec1.value,tempVector);
if (tempVector.size() == 1) {
Integer returnVal = (Integer)(tempVector.elementAt(0));
return returnVal.intValue();
}
}
int type = tempContentSpec1.type;
int value = tempContentSpec1.value;
int otherValue = tempContentSpec1.otherValue;
gatherChildren(type,value, tempVector);
gatherChildren(type,otherValue, tempVector);
return csIndex;
}
private void gatherChildren(int parentType, int csIndex, Vector tempVector) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER ) {
tempVector.addElement(new Integer(csIndex));
}
else if (! (min==1 && max==1)) {
tempVector.addElement(new Integer(csIndex));
}
else if (right == -2) {
gatherChildren(type,left,tempVector);
}
else if (parentType == type) {
gatherChildren(type,left,tempVector);
gatherChildren(type,right,tempVector);
}
else {
tempVector.addElement(new Integer(csIndex));
}
}
private void checkNameAndTypeOK(int csIndex1, int derivedScope, int csIndex2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
int localpart1 = tempContentSpec1.value;
int uri1 = tempContentSpec1.otherValue;
int localpart2 = tempContentSpec2.value;
int uri2 = tempContentSpec2.otherValue;
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
//start the checking...
if (!(localpart1==localpart2 && uri1==uri2)) {
// we have non-matching names. Check substitution groups.
if (fSComp == null)
fSComp = new SubstitutionGroupComparator(fGrammarResolver,fStringPool,fErrorReporter);
if (!checkSubstitutionGroups(localpart1,uri1,localpart2,uri2))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.1: Element name/uri in restriction does not match that of corresponding base element");
}
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.3: Element occurrence range not a restriction of base element's range: element is " + fStringPool.toString(localpart1));
}
SchemaGrammar aGrammar = fSchemaGrammar;
// get the element decl indices for the remainder...
String schemaURI = fStringPool.toString(uri1);
if ( !schemaURI.equals(fTargetNSURIString)
&& schemaURI.length() != 0 )
aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar(schemaURI);
int eltndx1 = findElement(derivedScope, localpart1, aGrammar, null);
if (eltndx1 < 0)
return;
int eltndx2 = findElement(baseScope, localpart2, aGrammar, bInfo);
if (eltndx2 < 0)
return;
int miscFlags1 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx1);
int miscFlags2 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx2);
boolean element1IsNillable = (miscFlags1 & SchemaSymbols.NILLABLE) !=0;
boolean element2IsNillable = (miscFlags2 & SchemaSymbols.NILLABLE) !=0;
boolean element2IsFixed = (miscFlags2 & SchemaSymbols.FIXED) !=0;
boolean element1IsFixed = (miscFlags1 & SchemaSymbols.FIXED) !=0;
String element1Value = aGrammar.getElementDefaultValue(eltndx1);
String element2Value = aGrammar.getElementDefaultValue(eltndx2);
if (! (element2IsNillable || !element1IsNillable)) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.2: Element " +fStringPool.toString(localpart1) + " is nillable in the restriction but not the base");
}
if (! (element2Value == null || !element2IsFixed ||
(element1IsFixed && element1Value.equals(element2Value)))) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.4: Element " +fStringPool.toString(localpart1) + " is either not fixed, or is not fixed with the same value as in the base");
}
// check disallowed substitutions
int blockSet1 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx1);
int blockSet2 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx2);
if (((blockSet1 & blockSet2)!=blockSet2) ||
(blockSet1==0 && blockSet2!=0))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Element " +fStringPool.toString(localpart1) + "'s disallowed subsitutions are not a superset of those of the base element's");
// Need element decls for the remainder of the checks
aGrammar.getElementDecl(eltndx1, fTempElementDecl);
aGrammar.getElementDecl(eltndx2, fTempElementDecl2);
// check identity constraints
checkIDConstraintRestriction(fTempElementDecl, fTempElementDecl2, aGrammar, localpart1, localpart2);
// check that the derived element's type is derived from the base's. - TO BE DONE
checkTypesOK(fTempElementDecl,fTempElementDecl2,eltndx1,eltndx2,aGrammar,fStringPool.toString(localpart1));
}
private void checkTypesOK(XMLElementDecl derived, XMLElementDecl base, int dndx, int bndx, SchemaGrammar aGrammar, String elementName) throws Exception {
ComplexTypeInfo tempType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(dndx);
if (derived.type == XMLElementDecl.TYPE_SIMPLE ) {
if (base.type != XMLElementDecl.TYPE_SIMPLE)
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derive from that of the base");
if (tempType == null) {
if (!(checkSimpleTypeDerivationOK(derived.datatypeValidator,
base.datatypeValidator)))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
return;
}
}
ComplexTypeInfo bType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(bndx);
for(; tempType != null; tempType = tempType.baseComplexTypeInfo) {
if (tempType.derivedBy != SchemaSymbols.RESTRICTION) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
}
if (tempType.typeName.equals(bType.typeName))
break;
}
if(tempType == null) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
}
}
private void checkIDConstraintRestriction(XMLElementDecl derivedElemDecl, XMLElementDecl baseElemDecl,
SchemaGrammar grammar, int derivedElemName, int baseElemName) throws Exception {
// this method throws no errors if the ID constraints on
// the derived element are a logical subset of those on the
// base element--that is, those that are present are
// identical to ones in the base element.
Vector derivedUnique = derivedElemDecl.unique;
Vector baseUnique = baseElemDecl.unique;
if(derivedUnique.size() > baseUnique.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <unique> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedUnique.size() && found; i++) {
Unique id = (Unique)derivedUnique.elementAt(i);
found = false;
for(int j=0; j<baseUnique.size(); j++) {
if(id.equals((Unique)baseUnique.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <unique> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
Vector derivedKey = derivedElemDecl.key;
Vector baseKey = baseElemDecl.key;
if(derivedKey.size() > baseKey.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <key> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedKey.size() && found; i++) {
Key id = (Key)derivedKey.elementAt(i);
found = false;
for(int j=0; j<baseKey.size(); j++) {
if(id.equals((Key)baseKey.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <key> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
Vector derivedKeyRef = derivedElemDecl.keyRef;
Vector baseKeyRef = baseElemDecl.keyRef;
if(derivedKeyRef.size() > baseKeyRef.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <keyref> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedKeyRef.size() && found; i++) {
KeyRef id = (KeyRef)derivedKeyRef.elementAt(i);
found = false;
for(int j=0; j<baseKeyRef.size(); j++) {
if(id.equals((KeyRef)baseKeyRef.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <keyref> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
} // checkIDConstraintRestriction
private boolean checkSubstitutionGroups(int local1, int uri1, int local2, int uri2)
throws Exception {
// check if either name is in the other's substitution group
QName name1 = new QName(-1,local1,local1,uri1);
QName name2 = new QName(-1,local2,local2,uri2);
if (fSComp.isEquivalentTo(name1,name2) ||
fSComp.isEquivalentTo(name2,name1))
return true;
else
return false;
}
private boolean checkOccurrenceRange(int min1, int max1, int min2, int max2) {
if ((min1 >= min2) &&
((max2==SchemaSymbols.OCCURRENCE_UNBOUNDED) || (max1!=SchemaSymbols.OCCURRENCE_UNBOUNDED && max1<=max2)))
return true;
else
return false;
}
private int findElement(int scope, int nameIndex, SchemaGrammar gr, ComplexTypeInfo bInfo) {
// check for element at given scope first
int elementDeclIndex = gr.getElementDeclIndex(nameIndex,scope);
// if not found, check at global scope
if (elementDeclIndex == -1) {
elementDeclIndex = gr.getElementDeclIndex(nameIndex, -1);
// if still not found, and base is specified, look it up there
if (elementDeclIndex == -1 && bInfo != null) {
ComplexTypeInfo baseInfo = bInfo;
while (baseInfo != null) {
elementDeclIndex = gr.getElementDeclIndex(nameIndex,baseInfo.scopeDefined);
if (elementDeclIndex > -1)
break;
baseInfo = baseInfo.baseComplexTypeInfo;
}
}
}
return elementDeclIndex;
}
private void checkNSCompat(int csIndex1, int derivedScope, int csIndex2) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSCompat.2: Element occurrence range not a restriction of base any element's range");
}
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
int uri = tempContentSpec1.otherValue;
// check wildcard subset
if (!wildcardEltAllowsNamespace(csIndex2, uri))
throw new ParticleRecoverableError("rcase-NSCompat.1: Element's namespace not allowed by wildcard in base");
}
private boolean wildcardEltAllowsNamespace(int wildcardNode, int uriIndex) {
fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1);
if ((tempContentSpec1.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY)
return true;
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if (uriIndex == tempContentSpec1.otherValue)
return true;
}
else { // must be ANY_OTHER
if (uriIndex != tempContentSpec1.otherValue && uriIndex != StringPool.EMPTY_STRING)
return true;
}
return false;
}
private void checkNSSubset(int csIndex1, int csIndex2) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range");
}
if (!wildcardEltSubset(csIndex1, csIndex2))
throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base");
}
private boolean wildcardEltSubset(int wildcardNode, int wildcardBaseNode) {
fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1);
fSchemaGrammar.getContentSpec(wildcardBaseNode, tempContentSpec2);
if ((tempContentSpec2.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY)
return true;
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER &&
tempContentSpec1.otherValue == tempContentSpec2.otherValue)
return true;
}
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL &&
tempContentSpec1.otherValue == tempContentSpec2.otherValue)
return true;
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER &&
tempContentSpec1.otherValue != tempContentSpec2.otherValue)
return true;
}
return false;
}
private void checkRecurseAsIfGroup(int csIndex1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
// Treat the element as if it were in a group of the same type as csindex2
int indexOfGrp=fSchemaGrammar.addContentSpecNode(tempContentSpec2.type,
csIndex1,-2, false);
Vector tmpVector = new Vector();
tmpVector.addElement(new Integer(csIndex1));
if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ)
checkRecurse(indexOfGrp, tmpVector, derivedScope, csIndex2,
tempVector2, baseScope, bInfo);
else
checkRecurseLax(indexOfGrp, tmpVector, derivedScope, csIndex2,
tempVector2, baseScope, bInfo);
tmpVector = null;
}
private void checkNSRecurseCheckCardinality(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2) throws Exception {
// Implement total range check
int min1 = minEffectiveTotalRange(csIndex1);
int max1 = maxEffectiveTotalRange(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range");
}
if (!wildcardEltSubset(csIndex1, csIndex2))
throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base");
// Check that each member of the group is a valid restriction of the wildcard
int count = tempVector1.size();
for (int i = 0; i < count; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
checkParticleDerivationOK(particle1.intValue(),derivedScope,csIndex2,-1,null);
}
}
private void checkRecurse(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-Recurse.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2= tempVector2.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = current; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
current +=1;
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
continue label;
}
catch (ParticleRecoverableError e) {
if (!particleEmptiable(particle2.intValue()))
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
// Now, see if there are some elements in the base we didn't match up
for (int j=current; j < count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
if (!particleEmptiable(particle2.intValue())) {
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
}
private void checkRecurseUnordered(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-RecurseUnordered.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2 = tempVector2.size();
boolean foundIt[] = new boolean[count2];
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = 0; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
if (foundIt[j])
throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles");
else
foundIt[j]=true;
continue label;
}
catch (ParticleRecoverableError e) {
}
}
// didn't find a match. Detect an error
throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles");
}
}
private void checkRecurseLax(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-RecurseLax.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2 = tempVector2.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = current; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
current +=1;
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
continue label;
}
catch (ParticleRecoverableError e) {
}
}
// didn't find a match. Detect an error
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
private void checkMapAndSum(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
// See if the sequence group particle is a valid restriction of one of the particles
// of the choice
// This isn't what the spec says, but I can't make heads or tails of the
// algorithm in structures
int count2 = tempVector2.size();
boolean foundit = false;
for (int i=0; i<count2; i++) {
Integer particle = (Integer)tempVector2.elementAt(i);
fSchemaGrammar.getContentSpec(particle.intValue(),tempContentSpec1);
if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ)
try {
checkParticleDerivationOK(csIndex1,derivedScope,particle.intValue(),
baseScope, bInfo);
foundit = true;
break;
}
catch (ParticleRecoverableError e) {
}
}
if (!foundit)
throw new ParticleRecoverableError("rcase-MapAndSum: There is not a complete functional mapping between the particles");
}
private int importContentSpec(SchemaGrammar aGrammar, int contentSpecHead ) throws Exception {
XMLContentSpec ctsp = new XMLContentSpec();
aGrammar.getContentSpec(contentSpecHead, ctsp);
int left = -1;
int right = -1;
if ( ctsp.type == ctsp.CONTENTSPECNODE_LEAF
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_LOCAL
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_OTHER ) {
return fSchemaGrammar.addContentSpecNode(ctsp.type, ctsp.value, ctsp.otherValue, false);
}
else if (ctsp.type == -1)
// case where type being extended has no content
return -2;
else {
if ( ctsp.value == -1 ) {
left = -1;
}
else {
left = importContentSpec(aGrammar, ctsp.value);
}
if ( ctsp.otherValue == -1 ) {
right = -1;
}
else {
right = importContentSpec(aGrammar, ctsp.otherValue);
}
return fSchemaGrammar.addContentSpecNode(ctsp.type, left, right, false);
}
}
private int handleOccurrences(int index,
Element particle) throws Exception {
// Pass through, indicating we're not processing an <all>
return handleOccurrences(index, particle, NOT_ALL_CONTEXT);
}
// Checks constraints for minOccurs, maxOccurs and expands content model
// accordingly
private int handleOccurrences(int index, Element particle,
int allContextFlags) throws Exception {
// if index is invalid, return
if (index < 0)
return index;
String minOccurs =
particle.getAttribute(SchemaSymbols.ATT_MINOCCURS).trim();
String maxOccurs =
particle.getAttribute(SchemaSymbols.ATT_MAXOCCURS).trim();
boolean processingAll = ((allContextFlags & PROCESSING_ALL) != 0);
boolean groupRefWithAll = ((allContextFlags & GROUP_REF_WITH_ALL) != 0);
boolean isGroupChild = ((allContextFlags & CHILD_OF_GROUP) != 0);
// Neither minOccurs nor maxOccurs may be specified
// for the child of a model group definition.
if (isGroupChild && (!minOccurs.equals("") || !maxOccurs.equals(""))) {
reportSchemaError(SchemaMessageProvider.MinMaxOnGroupChild, null);
minOccurs = (maxOccurs = "1");
}
// If minOccurs=maxOccurs=0, no component is specified
if(minOccurs.equals("0") && maxOccurs.equals("0")){
return -2;
}
int min=1, max=1;
if (minOccurs.equals("")) {
minOccurs = "1";
}
if (maxOccurs.equals("")) {
maxOccurs = "1";
}
// For the elements referenced in an <all>, minOccurs attribute
// must be zero or one, and maxOccurs attribute must be one.
if (processingAll || groupRefWithAll) {
if ((groupRefWithAll || !minOccurs.equals("0")) &&
!minOccurs.equals("1")) {
int minMsg = processingAll ?
SchemaMessageProvider.BadMinMaxForAll :
SchemaMessageProvider.BadMinMaxForGroupWithAll;
reportSchemaError(minMsg, new Object [] { "minOccurs",
minOccurs });
minOccurs = "1";
}
if (!maxOccurs.equals("1")) {
int maxMsg = processingAll ?
SchemaMessageProvider.BadMinMaxForAll :
SchemaMessageProvider.BadMinMaxForGroupWithAll;
reportSchemaError(maxMsg, new Object [] { "maxOccurs",
maxOccurs });
maxOccurs = "1";
}
}
try {
min = Integer.parseInt(minOccurs);
}
catch (Exception e){
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "});
}
if (maxOccurs.equals("unbounded")) {
max = SchemaSymbols.OCCURRENCE_UNBOUNDED;
}
else {
try {
max = Integer.parseInt(maxOccurs);
}
catch (Exception e){
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "});
}
// Check that minOccurs isn't greater than maxOccurs.
// p-props-correct 2.1
if (min > max) {
reportGenericSchemaError("p-props-correct:2.1 Value of minOccurs '" + minOccurs + "' must not be greater than value of maxOccurs '" + maxOccurs +"'");
}
if (max < 1) {
reportGenericSchemaError("p-props-correct:2.2 Value of maxOccurs " + maxOccurs + " is invalid. It must be greater than or equal to 1");
}
}
if (fSchemaGrammar.getDeferContentSpecExpansion()) {
fSchemaGrammar.setContentSpecMinOccurs(index,min);
fSchemaGrammar.setContentSpecMaxOccurs(index,max);
return index;
}
else {
return fSchemaGrammar.expandContentModel(index,min,max);
}
}
/**
* Traverses Schema attribute declaration.
*
* <attribute
* default = string
* fixed = string
* form = (qualified | unqualified)
* id = ID
* name = NCName
* ref = QName
* type = QName
* use = (optional | prohibited | required) : optional
* {any attributes with non-schema namespace ...}>
* Content: (annotation? , simpleType?)
* <attribute/>
*
* @param attributeDecl: the declaration of the attribute under
* consideration
* @param typeInfo: Contains the index of the element to which
* the attribute declaration is attached.
* @param referredTo: true iff traverseAttributeDecl was called because
* of encountering a ``ref''property (used
* to suppress error-reporting).
* @return 0 if the attribute schema is validated successfully, otherwise -1
* @exception Exception
*/
private int traverseAttributeDecl( Element attrDecl, ComplexTypeInfo typeInfo, boolean referredTo ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(attrDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrDecl, scope);
////// Get declared fields of the attribute
String defaultStr = attrDecl.getAttribute(SchemaSymbols.ATT_DEFAULT);
String fixedStr = attrDecl.getAttribute(SchemaSymbols.ATT_FIXED);
String formStr = attrDecl.getAttribute(SchemaSymbols.ATT_FORM);//form attribute
String attNameStr = attrDecl.getAttribute(SchemaSymbols.ATT_NAME);
String refStr = attrDecl.getAttribute(SchemaSymbols.ATT_REF);
String datatypeStr = attrDecl.getAttribute(SchemaSymbols.ATT_TYPE);
String useStr = attrDecl.getAttribute(SchemaSymbols.ATT_USE);
Element simpleTypeChild = findAttributeSimpleType(attrDecl);
Attr defaultAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT);
Attr fixedAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FIXED);
Attr formAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FORM);
Attr attNameAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_NAME);
Attr refAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_REF);
Attr datatypeAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_TYPE);
Attr useAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_USE);
checkEnumerationRequiredNotation(attNameStr, datatypeStr);
////// define attribute declaration Schema components
int attName; // attribute name indexed in the string pool
int uriIndex; // indexed for target namespace uri
QName attQName; // QName combining attName and uriIndex
// attribute type
int attType;
boolean attIsList = false;
int dataTypeSymbol = -1;
String localpart = null;
// validator
DatatypeValidator dv;
boolean dvIsDerivedFromID = false;
// value constraints and use type
int attValueAndUseType = 0;
int attValueConstraint = -1; // indexed value in a string pool
////// Check W3C's PR-Structure 3.2.3
boolean isAttrTopLevel = isTopLevel(attrDecl);
boolean isOptional = false;
boolean isProhibited = false;
boolean isRequired = false;
StringBuffer errorContext = new StringBuffer(30);
errorContext.append("
if(typeInfo == null) {
errorContext.append("(global attribute) ");
}
else if(typeInfo.typeName == null) {
errorContext.append("(local attribute) ");
}
else {
errorContext.append("(attribute) ").append(typeInfo.typeName).append("/");
}
errorContext.append(attNameStr).append(' ').append(refStr);
if(useStr.equals("") || useStr.equals(SchemaSymbols.ATTVAL_OPTIONAL)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_OPTIONAL;
isOptional = true;
}
else if(useStr.equals(SchemaSymbols.ATTVAL_PROHIBITED)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_PROHIBITED;
isProhibited = true;
}
else if(useStr.equals(SchemaSymbols.ATTVAL_REQUIRED)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_REQUIRED;
isRequired = true;
}
else {
reportGenericSchemaError("An attribute cannot declare \"" +
SchemaSymbols.ATT_USE + "\" as \"" + useStr + "\"" + errorContext);
}
if(defaultAtt != null && fixedAtt != null) {
reportGenericSchemaError("src-attribute.1: \"" + SchemaSymbols.ATT_DEFAULT +
"\" and \"" + SchemaSymbols.ATT_FIXED +
"\" cannot be both present" + errorContext);
}
else if(defaultAtt != null && !isOptional) {
reportGenericSchemaError("src-attribute.2: If both \"" + SchemaSymbols.ATT_DEFAULT +
"\" and \"" + SchemaSymbols.ATT_USE + "\" " +
"are present for an attribute declaration, \"" +
SchemaSymbols.ATT_USE + "\" can only be \"" +
SchemaSymbols.ATTVAL_OPTIONAL + "\", not \"" + useStr + "\"." + errorContext);
}
if(!isAttrTopLevel) {
if((refAtt == null) == (attNameAtt == null)) {
reportGenericSchemaError("src-attribute.3.1: When the attribute's parent is not <schema> , one of \"" +
SchemaSymbols.ATT_REF + "\" and \"" + SchemaSymbols.ATT_NAME +
"\" should be declared, but not both."+ errorContext);
return -1;
}
else if((refAtt != null) && (simpleTypeChild != null || formAtt != null || datatypeAtt != null)) {
reportGenericSchemaError("src-attribute.3.2: When the attribute's parent is not <schema> and \"" +
SchemaSymbols.ATT_REF + "\" is present, " +
"all of <" + SchemaSymbols.ELT_SIMPLETYPE + ">, " +
SchemaSymbols.ATT_FORM + " and " + SchemaSymbols.ATT_TYPE +
" must be absent."+ errorContext);
}
}
if(datatypeAtt != null && simpleTypeChild != null) {
reportGenericSchemaError("src-attribute.4: \"" + SchemaSymbols.ATT_TYPE + "\" and <" +
SchemaSymbols.ELT_SIMPLETYPE + "> cannot both be present"+ errorContext);
}
////// Check W3C's PR-Structure 3.2.2
// check case-dependent attribute declaration schema components
if (isAttrTopLevel) {
//// global attributes
// set name component
attName = fStringPool.addSymbol(attNameStr);
if(fTargetNSURIString.length() == 0) {
uriIndex = StringPool.EMPTY_STRING;
}
else {
uriIndex = fTargetNSURI;
}
// attQName = new QName(-1,attName,attName,uriIndex);
// Above line replaced by following 2 to work around a JIT problem.
attQName = new QName();
attQName.setValues(-1,attName,attName,uriIndex);
}
else if(refAtt == null) {
//// local attributes
// set name component
attName = fStringPool.addSymbol(attNameStr);
if((formStr.length() > 0 && formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)) ||
(formStr.length() == 0 && fAttributeDefaultQualified)) {
uriIndex = fTargetNSURI;
}
else {
uriIndex = StringPool.EMPTY_STRING;
}
// attQName = new QName(-1,attName,attName,uriIndex);
// Above line replaced by following 2 to work around a JIT problem.
attQName = new QName();
attQName.setValues(-1,attName,attName,uriIndex);
}
else {
//// locally referenced global attributes
String prefix;
int colonptr = refStr.indexOf(":");
if ( colonptr > 0) {
prefix = refStr.substring(0,colonptr);
localpart = refStr.substring(colonptr+1);
}
else {
prefix = "";
localpart = refStr;
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo);
return 0;
}
Element referredAttribute = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTE,localpart);
if (referredAttribute != null) {
// don't need to traverse ref'd attribute if we're global; just make sure it's there...
traverseAttributeDecl(referredAttribute, typeInfo, true);
Attr referFixedAttr = referredAttribute.getAttributeNode(SchemaSymbols.ATT_FIXED);
String referFixed = referFixedAttr == null ? null : referFixedAttr.getValue();
if (referFixed != null && (defaultAtt != null || fixedAtt != null && !referFixed.equals(fixedStr))) {
reportGenericSchemaError("au-props-correct.2: If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}" + errorContext);
}
// this nasty hack needed to ``override'' the
// global attribute with "use" and "fixed" on the ref'ing attribute
if(!isOptional || fixedStr.length() > 0) {
int referredAttName = fStringPool.addSymbol(referredAttribute.getAttribute(SchemaSymbols.ATT_NAME));
uriIndex = StringPool.EMPTY_STRING;
if ( fTargetNSURIString.length() > 0) {
uriIndex = fTargetNSURI;
}
QName referredAttQName = new QName(-1,referredAttName,referredAttName,uriIndex);
int tempIndex = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, referredAttQName);
XMLAttributeDecl referredAttrDecl = new XMLAttributeDecl();
fSchemaGrammar.getAttributeDecl(tempIndex, referredAttrDecl);
boolean updated = false;
int useDigits = XMLAttributeDecl.USE_TYPE_OPTIONAL |
XMLAttributeDecl.USE_TYPE_PROHIBITED |
XMLAttributeDecl.USE_TYPE_REQUIRED;
int valueDigits = XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT |
XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
if(!isOptional &&
(referredAttrDecl.defaultType & useDigits) !=
(attValueAndUseType & useDigits))
{
if(referredAttrDecl.defaultType != XMLAttributeDecl.USE_TYPE_PROHIBITED) {
referredAttrDecl.defaultType |= useDigits;
referredAttrDecl.defaultType ^= useDigits; // clear the use
referredAttrDecl.defaultType |= (attValueAndUseType & useDigits);
updated = true;
}
}
if(fixedStr.length() > 0) {
if((referredAttrDecl.defaultType & XMLAttributeDecl.VALUE_CONSTRAINT_FIXED) == 0) {
referredAttrDecl.defaultType |= valueDigits;
referredAttrDecl.defaultType ^= valueDigits; // clear the value
referredAttrDecl.defaultType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
referredAttrDecl.defaultValue = fStringPool.toString(attValueConstraint);
updated = true;
}
}
if(updated) {
fSchemaGrammar.setAttributeDecl(typeInfo.templateElementIndex, tempIndex, referredAttrDecl);
}
}
}
else if (fAttributeDeclRegistry.get(localpart) != null) {
addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attribute " + refStr + errorContext);
}
return 0;
}
if (uriIndex == fXsiURI) {
reportGenericSchemaError("no-xsi: The {target namespace} of an attribute declaration must not match " + SchemaSymbols.URI_XSI + errorContext);
}
// validation of attribute type is same for each case of declaration
if (simpleTypeChild != null) {
attType = XMLAttributeDecl.TYPE_SIMPLE;
dataTypeSymbol = traverseSimpleTypeDecl(simpleTypeChild);
localpart = fStringPool.toString(dataTypeSymbol);
dv = fDatatypeRegistry.getDatatypeValidator(localpart);
}
else if (datatypeStr.length() != 0) {
dataTypeSymbol = fStringPool.addSymbol(datatypeStr);
String prefix;
int colonptr = datatypeStr.indexOf(":");
if ( colonptr > 0) {
prefix = datatypeStr.substring(0,colonptr);
localpart = datatypeStr.substring(colonptr+1);
}
else {
prefix = "";
localpart = datatypeStr;
}
String typeURI = resolvePrefixToURI(prefix);
if ( typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
|| typeURI.length()==0) {
dv = getDatatypeValidator("", localpart);
if (localpart.equals("ID")) {
attType = XMLAttributeDecl.TYPE_ID;
} else if (localpart.equals("IDREF")) {
attType = XMLAttributeDecl.TYPE_IDREF;
} else if (localpart.equals("IDREFS")) {
attType = XMLAttributeDecl.TYPE_IDREF;
attIsList = true;
} else if (localpart.equals("ENTITY")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
} else if (localpart.equals("ENTITIES")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
attIsList = true;
} else if (localpart.equals("NMTOKEN")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
} else if (localpart.equals("NMTOKENS")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
attIsList = true;
} else if (localpart.equals(SchemaSymbols.ELT_NOTATION)) {
attType = XMLAttributeDecl.TYPE_NOTATION;
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
if (dv == null && typeURI.length() == 0) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else if (!referredTo) {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+localpart+")"+ errorContext);
}
}
}
} else { //isn't of the schema for schemas namespace...
attType = XMLAttributeDecl.TYPE_SIMPLE;
// check if the type is from the same Schema
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null && typeURI.equals(fTargetNSURIString) ) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else if (!referredTo) {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+ localpart+")"+ errorContext);
}
}
}
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
localpart = "string";
dataTypeSymbol = fStringPool.addSymbol(localpart);
dv = fDatatypeRegistry.getDatatypeValidator(localpart);
} // if(...Type)
// validation of data constraint is same for each case of declaration
if(defaultStr.length() > 0) {
attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT;
attValueConstraint = fStringPool.addString(defaultStr);
}
else if(fixedStr.length() > 0) {
attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
attValueConstraint = fStringPool.addString(fixedStr);
}
////// Check W3C's PR-Structure 3.2.6
// check default value is valid for the datatype.
if (attType == XMLAttributeDecl.TYPE_SIMPLE && attValueConstraint != -1) {
try {
if (dv != null) {
if(defaultStr.length() > 0) {
//REVISIT
dv.validate(defaultStr, null);
}
else {
dv.validate(fixedStr, null);
}
}
else if (!referredTo)
reportSchemaError(SchemaMessageProvider.NoValidatorFor,
new Object [] { datatypeStr });
} catch (InvalidDatatypeValueException idve) {
if (!referredTo)
reportSchemaError(SchemaMessageProvider.IncorrectDefaultType,
new Object [] { attrDecl.getAttribute(SchemaSymbols.ATT_NAME), idve.getMessage() }); //a-props-correct.2
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in attribute datatype validation");
}
}
// check the coexistence of ID and value constraint
dvIsDerivedFromID =
((dv != null) && dv instanceof IDDatatypeValidator);
if (dvIsDerivedFromID && attValueConstraint != -1)
{
reportGenericSchemaError("a-props-correct.3: If type definition is or is derived from ID ," +
"there must not be a value constraint" + errorContext);
}
if (attNameStr.equals("xmlns")) {
reportGenericSchemaError("no-xmlns: The {name} of an attribute declaration must not match 'xmlns'" + errorContext);
}
////// every contraints were matched. Now register the attribute declaration
//put the top-levels in the attribute decl registry.
if (isAttrTopLevel) {
fTempAttributeDecl.datatypeValidator = dv;
fTempAttributeDecl.name.setValues(attQName);
fTempAttributeDecl.type = attType;
fTempAttributeDecl.defaultType = attValueAndUseType;
fTempAttributeDecl.list = attIsList;
if (attValueConstraint != -1 ) {
fTempAttributeDecl.defaultValue = fStringPool.toString(attValueConstraint);
}
fAttributeDeclRegistry.put(attNameStr, new XMLAttributeDecl(fTempAttributeDecl));
}
// add attribute to attr decl pool in fSchemaGrammar,
if (typeInfo != null) {
// check that there aren't duplicate attributes
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, attQName);
if (temp > -1) {
reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " +
fStringPool.toString(attQName.rawname) + " in type definition");
}
// check that there aren't multiple attributes with type derived from ID
if (dvIsDerivedFromID) {
if (typeInfo.containsAttrTypeID()) {
reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition.");
}
typeInfo.setContainsAttrTypeID();
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attQName, attType,
dataTypeSymbol, attValueAndUseType,
fStringPool.toString( attValueConstraint), dv, attIsList);
}
return 0;
} // end of method traverseAttribute
private int addAttributeDeclFromAnotherSchema( String name, String uriStr, ComplexTypeInfo typeInfo) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
Hashtable attrRegistry = aGrammar.getAttributeDeclRegistry();
if (attrRegistry == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
XMLAttributeDecl tempAttrDecl = (XMLAttributeDecl) attrRegistry.get(name);
if (tempAttrDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
if (typeInfo!= null) {
// check that there aren't duplicate attributes
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, tempAttrDecl.name);
if (temp > -1) {
reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " +
fStringPool.toString(tempAttrDecl.name.rawname) + " in type definition");
}
// check that there aren't multiple attributes with type derived from ID
if (tempAttrDecl.datatypeValidator != null &&
tempAttrDecl.datatypeValidator instanceof IDDatatypeValidator) {
if (typeInfo.containsAttrTypeID()) {
reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition");
}
typeInfo.setContainsAttrTypeID();
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
tempAttrDecl.name, tempAttrDecl.type,
-1, tempAttrDecl.defaultType,
tempAttrDecl.defaultValue,
tempAttrDecl.datatypeValidator,
tempAttrDecl.list);
}
return 0;
}
/*
*
* <attributeGroup
* id = ID
* name = NCName
* ref = QName>
* Content: (annotation?, (attribute|attributeGroup)*, anyAttribute?)
* </>
*
*/
private int traverseAttributeGroupDecl( Element attrGrpDecl, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(attrGrpDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrGrpDecl, scope);
// attributeGroup name
String attGrpNameStr = attrGrpDecl.getAttribute(SchemaSymbols.ATT_NAME);
int attGrpName = fStringPool.addSymbol(attGrpNameStr);
String ref = attrGrpDecl.getAttribute(SchemaSymbols.ATT_REF);
Element child = checkContent( attrGrpDecl, XUtil.getFirstChildElement(attrGrpDecl), true );
if (!ref.equals("")) {
if(isTopLevel(attrGrpDecl))
// REVISIT: localize
reportGenericSchemaError ( "An attributeGroup with \"ref\" present must not have <schema> or <redefine> as its parent");
if(!attGrpNameStr.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "attributeGroup " + attGrpNameStr + " cannot refer to another attributeGroup, but it refers to " + ref);
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
traverseAttributeGroupDeclFromAnotherSchema(localpart, uriStr, typeInfo, anyAttDecls);
return -1;
// TO DO
// REVISIST: different NS, not supported yet.
// REVISIT: Localize
//reportGenericSchemaError("Feature not supported: see an attribute from different NS");
} else {
Element parent = (Element)attrGrpDecl.getParentNode();
if (parent.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) &&
parent.getAttribute(SchemaSymbols.ATT_NAME).equals(localpart)) {
if (!((Element)parent.getParentNode()).getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) {
reportGenericSchemaError("src-attribute_group.3: Circular group reference is disallowed outside <redefine> -- "+ref);
}
return -1;
}
}
if(typeInfo != null) {
// only do this if we're traversing because we were ref'd here; when we come
// upon this decl by itself we're just validating.
Element referredAttrGrp = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTEGROUP,localpart);
if (referredAttrGrp != null) {
traverseAttributeGroupDecl(referredAttrGrp, typeInfo, anyAttDecls);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attributeGroup " + ref);
}
return -1;
}
} else if (attGrpNameStr.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "an attributeGroup must have a name or a ref attribute present");
for (;
child != null ; child = XUtil.getNextSiblingElement(child)) {
if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
traverseAttributeDecl(child, typeInfo, false);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
if(typeInfo != null)
// only do this if we're traversing because we were ref'd here; when we come
// upon this decl by itself we're just validating.
traverseAttributeGroupDecl(child, typeInfo,anyAttDecls);
}
else
break;
}
if (child != null) {
if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
if (anyAttDecls != null) {
anyAttDecls.addElement(traverseAnyAttribute(child));
}
if (XUtil.getNextSiblingElement(child) != null)
// REVISIT: localize
reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))");
return -1;
}
else
// REVISIT: localize
reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))");
}
return -1;
} // end of method traverseAttributeGroup
private int traverseAttributeGroupDeclFromAnotherSchema( String attGrpName , String uriStr,
ComplexTypeInfo typeInfo,
Vector anyAttDecls ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseAttributeGroupDeclFromAnotherSchema, schema uri : " + uriStr);
return -1;
}
// attribute name
Element attGrpDecl = (Element) aGrammar.topLevelAttrGrpDecls.get((Object)attGrpName);
if (attGrpDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute group named \"" + attGrpName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
// attribute type
int attType = -1;
int enumeration = -1;
Element child = checkContent(attGrpDecl, XUtil.getFirstChildElement(attGrpDecl), true);
for (;
child != null ; child = XUtil.getNextSiblingElement(child)) {
//child attribute couldn't be a top-level attribute DEFINITION,
if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
String childAttName = child.getAttribute(SchemaSymbols.ATT_NAME);
if ( childAttName.length() > 0 ) {
Hashtable attDeclRegistry = aGrammar.getAttributeDeclRegistry();
if (attDeclRegistry != null) {
if (attDeclRegistry.get((Object)childAttName) != null ){
addAttributeDeclFromAnotherSchema(childAttName, uriStr, typeInfo);
return -1;
}
}
}
else
traverseAttributeDecl(child, typeInfo, false);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child, typeInfo, anyAttDecls);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
anyAttDecls.addElement(traverseAnyAttribute(child));
break;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Invalid content for attributeGroup");
}
}
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
if(child != null) {
// REVISIT: Localize
reportGenericSchemaError("Invalid content for attributeGroup");
}
return -1;
} // end of method traverseAttributeGroupFromAnotherSchema
// This simple method takes an attribute declaration as a parameter and
// returns null if there is no simpleType defined or the simpleType
// declaration if one exists. It also throws an error if more than one
// <annotation> or <simpleType> group is present.
private Element findAttributeSimpleType(Element attrDecl) throws Exception {
Element child = checkContent(attrDecl, XUtil.getFirstChildElement(attrDecl), true);
// if there is only a annotatoin, then no simpleType
if (child == null)
return null;
// if the current one is not simpleType, or there are more elements,
// report an error
if (!child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE) ||
XUtil.getNextSiblingElement(child) != null)
//REVISIT: localize
reportGenericSchemaError("src-attribute.0: the content must match (annotation?, (simpleType?)) -- attribute declaration '"+
attrDecl.getAttribute(SchemaSymbols.ATT_NAME)+"'");
if (child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE))
return child;
return null;
} // end findAttributeSimpleType
/**
* Traverse element declaration:
* <element
* abstract = boolean
* block = #all or (possibly empty) subset of {substitutionGroup, extension, restriction}
* default = string
* substitutionGroup = QName
* final = #all or (possibly empty) subset of {extension, restriction}
* fixed = string
* form = qualified | unqualified
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* nillable = boolean
* ref = QName
* type = QName>
* Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*)
* </element>
*
*
* The following are identity-constraint definitions
* <unique
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </unique>
*
* <key
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </key>
*
* <keyref
* id = ID
* name = NCName
* refer = QName>
* Content: (annotation? , (selector , field+))
* </keyref>
*
* <selector>
* Content: XPathExprApprox : An XPath expression
* </selector>
*
* <field>
* Content: XPathExprApprox : An XPath expression
* </field>
*
*
* @param elementDecl
* @return
* @exception Exception
*/
private QName traverseElementDecl(Element elementDecl) throws Exception {
// General Attribute Checking
int scope = isTopLevel(elementDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(elementDecl, scope);
int contentSpecType = -1;
int contentSpecNodeIndex = -1;
int typeNameIndex = -1;
int scopeDefined = -2; //signal a error if -2 gets gets through
//cause scope can never be -2.
DatatypeValidator dv = null;
String abstractStr = elementDecl.getAttribute(SchemaSymbols.ATT_ABSTRACT);
String blockStr = elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK);
String defaultStr = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT);
String finalStr = elementDecl.getAttribute(SchemaSymbols.ATT_FINAL);
String fixedStr = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED);
String formStr = elementDecl.getAttribute(SchemaSymbols.ATT_FORM);
String maxOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS);
String minOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS);
String nameStr = elementDecl.getAttribute(SchemaSymbols.ATT_NAME);
String nillableStr = elementDecl.getAttribute(SchemaSymbols.ATT_NILLABLE);
String refStr = elementDecl.getAttribute(SchemaSymbols.ATT_REF);
String substitutionGroupStr = elementDecl.getAttribute(SchemaSymbols.ATT_SUBSTITUTIONGROUP);
String typeStr = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE);
checkEnumerationRequiredNotation(nameStr, typeStr);
if ( DEBUGGING )
System.out.println("traversing element decl : " + nameStr );
Attr abstractAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_ABSTRACT);
Attr blockAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_BLOCK);
Attr defaultAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT);
Attr finalAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FINAL);
Attr fixedAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FIXED);
Attr formAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FORM);
Attr maxOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MAXOCCURS);
Attr minOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS);
Attr nameAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NAME);
Attr nillableAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NILLABLE);
Attr refAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_REF);
Attr substitutionGroupAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_SUBSTITUTIONGROUP);
Attr typeAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_TYPE);
if(defaultAtt != null && fixedAtt != null)
// REVISIT: localize
reportGenericSchemaError("src-element.1: an element cannot have both \"fixed\" and \"default\" present at the same time");
String fromAnotherSchema = null;
if (isTopLevel(elementDecl)) {
if(nameAtt == null)
// REVISIT: localize
reportGenericSchemaError("globally-declared element must have a name");
else if (refAtt != null)
// REVISIT: localize
reportGenericSchemaError("globally-declared element " + nameStr + " cannot have a ref attribute");
int nameIndex = fStringPool.addSymbol(nameStr);
int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE);
if (eltKey > -1 ) {
return new QName(-1,nameIndex,nameIndex,fTargetNSURI);
}
}
// parse out 'block', 'final', 'nillable', 'abstract'
if (blockAtt == null)
blockStr = null;
int blockSet = parseBlockSet(blockStr);
if( (blockStr != null) && !blockStr.equals("") &&
(!blockStr.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((blockSet & SchemaSymbols.RESTRICTION) == 0) &&
(((blockSet & SchemaSymbols.EXTENSION) == 0) &&
((blockSet & SchemaSymbols.SUBSTITUTION) == 0)))))
reportGenericSchemaError("The values of the 'block' attribute of an element must be either #all or a list of 'substitution', 'restriction' and 'extension'; " + blockStr + " was found");
if (finalAtt == null)
finalStr = null;
int finalSet = parseFinalSet(finalStr);
if( (finalStr != null) && !finalStr.equals("") &&
(!finalStr.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((finalSet & SchemaSymbols.RESTRICTION) == 0) &&
((finalSet & SchemaSymbols.EXTENSION) == 0))))
reportGenericSchemaError("The values of the 'final' attribute of an element must be either #all or a list of 'restriction' and 'extension'; " + finalStr + " was found");
boolean isNillable = nillableStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
boolean isAbstract = abstractStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
int elementMiscFlags = 0;
if (isNillable) {
elementMiscFlags += SchemaSymbols.NILLABLE;
}
if (isAbstract) {
elementMiscFlags += SchemaSymbols.ABSTRACT;
}
// make the property of the element's value being fixed also appear in elementMiscFlags
if(fixedAtt != null)
elementMiscFlags += SchemaSymbols.FIXED;
//if this is a reference to a global element
if (refAtt != null) {
//REVISIT top level check for ref
if (abstractAtt != null || blockAtt != null || defaultAtt != null ||
finalAtt != null || fixedAtt != null || formAtt != null ||
nillableAtt != null || substitutionGroupAtt != null || typeAtt != null)
reportSchemaError(SchemaMessageProvider.BadAttWithRef, null); //src-element.2.2
if (nameAtt != null)
// REVISIT: Localize
reportGenericSchemaError("src-element.2.1: element " + nameStr + " cannot also have a ref attribute");
Element child = XUtil.getFirstChildElement(elementDecl);
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
if (XUtil.getNextSiblingElement(child) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
else
traverseAnnotationDecl(child);
}
else if (child != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
String prefix = "";
String localpart = refStr;
int colonptr = refStr.indexOf(":");
if ( colonptr > 0) {
prefix = refStr.substring(0,colonptr);
localpart = refStr.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriString = resolvePrefixToURI(prefix);
QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1,
localpartIndex,
fStringPool.addSymbol(refStr),
uriString != null ? fStringPool.addSymbol(uriString) : StringPool.EMPTY_STRING);
//if from another schema, just return the element QName
if (! uriString.equals(fTargetNSURIString) ) {
return eltName;
}
int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE);
//if not found, traverse the top level element that if referenced
if (elementIndex == -1 ) {
Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart);
if (targetElement == null ) {
// REVISIT: Localize
reportGenericSchemaError("Element " + localpart + " not found in the Schema");
//REVISIT, for now, the QName anyway
return eltName;
//return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString));
}
else {
// do nothing here, other wise would cause infinite loop for
// <element name="recur"><complexType><element ref="recur"> ...
//eltName= traverseElementDecl(targetElement);
}
}
return eltName;
} else if (nameAtt == null)
// REVISIT: Localize
reportGenericSchemaError("src-element.2.1: a local element must have a name or a ref attribute present");
// Handle the substitutionGroup
Element substitutionGroupElementDecl = null;
int substitutionGroupElementDeclIndex = -1;
boolean noErrorSoFar = true;
String substitutionGroupUri = null;
String substitutionGroupLocalpart = null;
String substitutionGroupFullName = null;
ComplexTypeInfo substitutionGroupEltTypeInfo = null;
DatatypeValidator substitutionGroupEltDV = null;
if ( substitutionGroupStr.length() > 0 ) {
if(refAtt != null)
// REVISIT: Localize
reportGenericSchemaError("a local element cannot have a substitutionGroup");
substitutionGroupUri = resolvePrefixToURI(getPrefix(substitutionGroupStr));
substitutionGroupLocalpart = getLocalPart(substitutionGroupStr);
substitutionGroupFullName = substitutionGroupUri+","+substitutionGroupLocalpart;
if ( !substitutionGroupUri.equals(fTargetNSURIString) ) {
substitutionGroupEltTypeInfo = getElementDeclTypeInfoFromNS(substitutionGroupUri, substitutionGroupLocalpart);
if (substitutionGroupEltTypeInfo == null) {
substitutionGroupEltDV = getElementDeclTypeValidatorFromNS(substitutionGroupUri, substitutionGroupLocalpart);
if (substitutionGroupEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart
+ "' in schema '" + substitutionGroupUri+"'");
}
}
}
else {
substitutionGroupElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, substitutionGroupLocalpart);
if (substitutionGroupElementDecl == null) {
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
if ( substitutionGroupElementDeclIndex == -1) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("unable to locate substitutionGroup affiliation element "
+substitutionGroupStr
+" in element declaration "
+nameStr);
}
}
else {
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
if ( substitutionGroupElementDeclIndex == -1) {
traverseElementDecl(substitutionGroupElementDecl);
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
}
}
if (substitutionGroupElementDeclIndex != -1) {
substitutionGroupEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( substitutionGroupElementDeclIndex );
if (substitutionGroupEltTypeInfo == null) {
fSchemaGrammar.getElementDecl(substitutionGroupElementDeclIndex, fTempElementDecl);
substitutionGroupEltDV = fTempElementDecl.datatypeValidator;
if (substitutionGroupEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart
+ "' in schema '" + substitutionGroupUri+"'");
}
}
}
}
}
// resolving the type for this element right here
ComplexTypeInfo typeInfo = null;
// element has a single child element, either a datatype or a type, null if primitive
Element child = XUtil.getFirstChildElement(elementDecl);
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
traverseAnnotationDecl(child);
child = XUtil.getNextSiblingElement(child);
}
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION))
// REVISIT: Localize
reportGenericSchemaError("element declarations can contain at most one annotation Element Information Item");
boolean haveAnonType = false;
// Handle Anonymous type if there is one
if (child != null) {
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous complexType in element '" + nameStr +"' has a name attribute");
}
else {
// Determine what the type name will be
String anonTypeName = genAnonTypeName(child);
if (fCurrentTypeNameStack.search((Object)anonTypeName) > - 1) {
// A recursing element using an anonymous type
int uriInd = StringPool.EMPTY_STRING;
if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified) {
uriInd = fTargetNSURI;
}
int nameIndex = fStringPool.addSymbol(nameStr);
QName tempQName = new QName(fCurrentScope, nameIndex, nameIndex, uriInd);
fElementRecurseComplex.put(tempQName, anonTypeName);
return new QName(-1, nameIndex, nameIndex, uriInd);
}
else {
typeNameIndex = traverseComplexTypeDecl(child);
if (typeNameIndex != -1 ) {
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse complexType error in element '" + nameStr +"'");
}
}
}
haveAnonType = true;
child = XUtil.getNextSiblingElement(child);
}
else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous simpleType in element '" + nameStr +"' has a name attribute");
}
else
typeNameIndex = traverseSimpleTypeDecl(child);
if (typeNameIndex != -1) {
dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse simpleType error in element '" + nameStr +"'");
}
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
haveAnonType = true;
child = XUtil.getNextSiblingElement(child);
} else if (typeAtt == null) { // "ur-typed" leaf
contentSpecType = XMLElementDecl.TYPE_ANY;
//REVISIT: is this right?
//contentSpecType = fStringPool.addSymbol("UR_TYPE");
// set occurrence count
contentSpecNodeIndex = -1;
}
// see if there's something here; it had better be key, keyref or unique.
if (child != null)
childName = child.getLocalName();
while ((child != null) && ((childName.equals(SchemaSymbols.ELT_KEY))
|| (childName.equals(SchemaSymbols.ELT_KEYREF))
|| (childName.equals(SchemaSymbols.ELT_UNIQUE)))) {
child = XUtil.getNextSiblingElement(child);
if (child != null) {
childName = child.getLocalName();
}
}
if (child != null) {
// REVISIT: Localize
noErrorSoFar = false;
reportGenericSchemaError("src-element.0: the content of an element information item must match (annotation?, (simpleType | complexType)?, (unique | key | keyref)*)");
}
}
// handle type="" here
if (haveAnonType && (typeAtt != null)) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError( "src-element.3: Element '"+ nameStr +
"' have both a type attribute and a annoymous type child" );
}
// type specified as an attribute and no child is type decl.
else if (typeAtt != null) {
String prefix = "";
String localpart = typeStr;
int colonptr = typeStr.indexOf(":");
if ( colonptr > 0) {
prefix = typeStr.substring(0,colonptr);
localpart = typeStr.substring(colonptr+1);
}
String typeURI = resolvePrefixToURI(prefix);
// check if the type is from the same Schema
if ( !typeURI.equals(fTargetNSURIString)
&& !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI.
fromAnotherSchema = typeURI;
typeInfo = getTypeInfoFromNS(typeURI, localpart);
if (typeInfo == null) {
dv = getTypeValidatorFromNS(typeURI, localpart);
if (dv == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type " +localpart
+ " in schema " + typeURI);
}
}
}
else {
typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart);
if (typeInfo == null) {
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null )
if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA))
{
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
else {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (topleveltype != null) {
if (fCurrentTypeNameStack.search((Object)localpart) > - 1) {
//then we found a recursive element using complexType.
// REVISIT: this will be broken when recursing happens between 2 schemas
int uriInd = StringPool.EMPTY_STRING;
if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified) {
uriInd = fTargetNSURI;
}
int nameIndex = fStringPool.addSymbol(nameStr);
QName tempQName = new QName(fCurrentScope, nameIndex, nameIndex, uriInd);
fElementRecurseComplex.put(tempQName, localpart);
return new QName(-1, nameIndex, nameIndex, uriInd);
}
else {
typeNameIndex = traverseComplexTypeDecl( topleveltype, true );
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
}
else {
topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
typeNameIndex = traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
}
}
}
}
}
// now we need to make sure that our substitution (if any)
// is valid, now that we have all the requisite type-related info.
if(substitutionGroupStr.length() > 0) {
checkSubstitutionGroupOK(elementDecl, substitutionGroupElementDecl, noErrorSoFar, substitutionGroupElementDeclIndex, typeInfo, substitutionGroupEltTypeInfo, dv, substitutionGroupEltDV);
}
// this element is ur-type, check its substitutionGroup affiliation.
// if there is substitutionGroup affiliation and not type definition found for this element,
// then grab substitutionGroup affiliation's type and give it to this element
if ( noErrorSoFar && typeInfo == null && dv == null ) {
typeInfo = substitutionGroupEltTypeInfo;
dv = substitutionGroupEltDV;
}
if (typeInfo == null && dv==null) {
if (noErrorSoFar) {
// Actually this Element's type definition is ur-type;
contentSpecType = XMLElementDecl.TYPE_ANY;
// REVISIT, need to wait till we have wildcards implementation.
// ADD attribute wildcards here
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError ("untyped element : " + nameStr );
}
}
// if element belongs to a compelx type
if (typeInfo!=null) {
contentSpecNodeIndex = typeInfo.contentSpecHandle;
contentSpecType = typeInfo.contentType;
scopeDefined = typeInfo.scopeDefined;
dv = typeInfo.datatypeValidator;
}
// if element belongs to a simple type
if (dv!=null) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
if (typeInfo == null) {
fromAnotherSchema = null; // not to switch schema in this case
}
}
// Now we can handle validation etc. of default and fixed attributes,
// since we finally have all the type information.
if(fixedAtt != null) defaultStr = fixedStr;
if(!defaultStr.equals("")) {
if(typeInfo != null &&
(typeInfo.contentType != XMLElementDecl.TYPE_MIXED_SIMPLE &&
typeInfo.contentType != XMLElementDecl.TYPE_MIXED_COMPLEX &&
typeInfo.contentType != XMLElementDecl.TYPE_SIMPLE)) {
// REVISIT: Localize
reportGenericSchemaError ("e-props-correct.2.1: element " + nameStr + " has a fixed or default value and must have a mixed or simple content model");
}
if(typeInfo != null &&
(typeInfo.contentType == XMLElementDecl.TYPE_MIXED_SIMPLE ||
typeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX)) {
if (!particleEmptiable(typeInfo.contentSpecHandle))
reportGenericSchemaError ("e-props-correct.2.2.2: for element " + nameStr + ", the {content type} is mixed, then the {content type}'s particle must be emptiable");
}
try {
if(dv == null) { // in this case validate according to xs:string
new StringDatatypeValidator().validate(defaultStr, null);
} else {
dv.validate(defaultStr, null);
}
} catch (InvalidDatatypeValueException ide) {
reportGenericSchemaError ("e-props-correct.2: invalid fixed or default value '" + defaultStr + "' in element " + nameStr);
}
}
if (!defaultStr.equals("") &&
dv != null && dv instanceof IDDatatypeValidator) {
reportGenericSchemaError ("e-props-correct.4: If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint} -- element " + nameStr);
}
// Create element decl
int elementNameIndex = fStringPool.addSymbol(nameStr);
int localpartIndex = elementNameIndex;
int uriIndex = StringPool.EMPTY_STRING;
int enclosingScope = fCurrentScope;
//refer to 4.3.2 in "XML Schema Part 1: Structures"
if ( isTopLevel(elementDecl)) {
uriIndex = fTargetNSURI;
enclosingScope = TOP_LEVEL_SCOPE;
}
else if ( !formStr.equals(SchemaSymbols.ATTVAL_UNQUALIFIED) &&
(( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified ))) {
uriIndex = fTargetNSURI;
}
//There can never be two elements with the same name and different type in the same scope.
int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope);
if ( existSuchElementIndex > -1) {
fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl);
DatatypeValidator edv = fTempElementDecl.datatypeValidator;
ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex);
if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo))
|| ((edv != null)&&(edv != dv)) ) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("duplicate element decl in the same scope : " +
fStringPool.toString(localpartIndex));
}
}
QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex);
// add element decl to pool
int attrListHead = -1 ;
// copy up attribute decls from type object
if (typeInfo != null) {
attrListHead = typeInfo.attlistHead;
}
int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined,
contentSpecType, contentSpecNodeIndex,
attrListHead, dv);
if ( DEBUGGING ) {
System.out.println("
+ fStringPool.toString(eltQName.localpart) + ")"+
" eltType:"+typeStr+" contentSpecType:"+contentSpecType+
" SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope +
" scopeDefined: " +scopeDefined+"\n");
}
fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo);
// REVISIT: should we report error if typeInfo was null?
// mark element if its type belongs to different Schema.
fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema);
// set BlockSet, FinalSet, Nillable and Abstract for this element decl
fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet);
fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet);
fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags);
fSchemaGrammar.setElementDefault(elementIndex, defaultStr);
// setSubstitutionGroupElementFullName
fSchemaGrammar.setElementDeclSubstitutionGroupElementFullName(elementIndex, substitutionGroupFullName);
// key/keyref/unique processing
Element ic = XUtil.getFirstChildElementNS(elementDecl, IDENTITY_CONSTRAINTS);
if (ic != null) {
Integer elementIndexObj = new Integer(elementIndex);
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints == null) {
identityConstraints = new Vector();
fIdentityConstraints.put(elementIndexObj, identityConstraints);
}
while (ic != null) {
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: adding ic for later traversal: "+ic);
}
identityConstraints.addElement(ic);
ic = XUtil.getNextSiblingElementNS(ic, IDENTITY_CONSTRAINTS);
}
}
return eltQName;
}// end of method traverseElementDecl(Element)
private void traverseIdentityNameConstraintsFor(int elementIndex,
Vector identityConstraints)
throws Exception {
// iterate over identity constraints for this element
int size = identityConstraints != null ? identityConstraints.size() : 0;
if (size > 0) {
// REVISIT: Use cached copy. -Ac
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(elementIndex, edecl);
for (int i = 0; i < size; i++) {
Element ic = (Element)identityConstraints.elementAt(i);
String icName = ic.getLocalName();
if ( icName.equals(SchemaSymbols.ELT_KEY) ) {
traverseKey(ic, edecl);
}
else if ( icName.equals(SchemaSymbols.ELT_UNIQUE) ) {
traverseUnique(ic, edecl);
}
fSchemaGrammar.setElementDecl(elementIndex, edecl);
} // loop over vector elements
} // if size > 0
} // traverseIdentityNameConstraints(Vector)
private void traverseIdentityRefConstraintsFor(int elementIndex,
Vector identityConstraints)
throws Exception {
// iterate over identity constraints for this element
int size = identityConstraints != null ? identityConstraints.size() : 0;
if (size > 0) {
// REVISIT: Use cached copy. -Ac
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(elementIndex, edecl);
for (int i = 0; i < size; i++) {
Element ic = (Element)identityConstraints.elementAt(i);
String icName = ic.getLocalName();
if ( icName.equals(SchemaSymbols.ELT_KEYREF) ) {
traverseKeyRef(ic, edecl);
}
fSchemaGrammar.setElementDecl(elementIndex, edecl);
} // loop over vector elements
} // if size > 0
} // traverseIdentityRefConstraints(Vector)
private void traverseUnique(Element uElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(uElem, scope);
// create identity constraint
String uName = uElem.getAttribute(SchemaSymbols.ATT_NAME);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseUnique(\""+uElem.getNodeName()+"\") ["+uName+']');
}
String eName = getElementNameFor(uElem);
Unique unique = new Unique(uName, eName);
fIdentityConstraintNames.put(fTargetNSURIString+","+uName, unique);
// get selector and fields
traverseIdentityConstraint(unique, uElem);
// add to element decl
eDecl.unique.addElement(unique);
} // traverseUnique(Element,XMLElementDecl)
private void traverseKey(Element kElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(kElem, scope);
// create identity constraint
String kName = kElem.getAttribute(SchemaSymbols.ATT_NAME);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseKey(\""+kElem.getNodeName()+"\") ["+kName+']');
}
String eName = getElementNameFor(kElem);
Key key = new Key(kName, eName);
fIdentityConstraintNames.put(fTargetNSURIString+","+kName, key);
// get selector and fields
traverseIdentityConstraint(key, kElem);
// add to element decl
eDecl.key.addElement(key);
} // traverseKey(Element,XMLElementDecl)
private void traverseKeyRef(Element krElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(krElem, scope);
// create identity constraint
String krName = krElem.getAttribute(SchemaSymbols.ATT_NAME);
String kName = krElem.getAttribute(SchemaSymbols.ATT_REFER);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseKeyRef(\""+krElem.getNodeName()+"\") ["+krName+','+kName+']');
}
// verify that key reference "refer" attribute is valid
String prefix = "";
String localpart = kName;
int colonptr = kName.indexOf(":");
if ( colonptr > 0) {
prefix = kName.substring(0,colonptr);
localpart = kName.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
IdentityConstraint kId = (IdentityConstraint)fIdentityConstraintNames.get(uriStr+","+localpart);
if (kId== null) {
reportSchemaError(SchemaMessageProvider.KeyRefReferNotFound,
new Object[]{krName,kName});
return;
}
String eName = getElementNameFor(krElem);
KeyRef keyRef = new KeyRef(krName, kId, eName);
// add to element decl
traverseIdentityConstraint(keyRef, krElem);
// add key reference to element decl
eDecl.keyRef.addElement(keyRef);
} // traverseKeyRef(Element,XMLElementDecl)
private void traverseIdentityConstraint(IdentityConstraint ic,
Element icElem) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(icElem, scope);
// check for <annotation> and get selector
Element sElem = XUtil.getFirstChildElement(icElem);
sElem = checkContent( icElem, sElem, false);
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(sElem, scope);
if(!sElem.getLocalName().equals(SchemaSymbols.ELT_SELECTOR)) {
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
}
// and make sure <selector>'s content is fine:
checkContent(icElem, XUtil.getFirstChildElement(sElem), true);
String sText = sElem.getAttribute(SchemaSymbols.ATT_XPATH);
sText = sText.trim();
Selector.XPath sXpath = null;
try {
// REVISIT: Must get ruling from XML Schema working group
// regarding whether steps in the XPath must be
// fully qualified if the grammar has a target
// namespace. -Ac
// RESOLUTION: Yes.
sXpath = new Selector.XPath(sText, fStringPool,
fNamespacesScope);
Selector selector = new Selector(sXpath, ic);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: selector: "+selector);
}
ic.setSelector(selector);
}
catch (XPathException e) {
// REVISIT: Add error message.
reportGenericSchemaError(e.getMessage());
return;
}
// get fields
Element fElem = XUtil.getNextSiblingElement(sElem);
while (fElem != null) {
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(fElem, scope);
if(!fElem.getLocalName().equals(SchemaSymbols.ELT_FIELD))
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
// and make sure <field>'s content is fine:
checkContent(icElem, XUtil.getFirstChildElement(fElem), true);
String fText = fElem.getAttribute(SchemaSymbols.ATT_XPATH);
fText = fText.trim();
try {
// REVISIT: Must get ruling from XML Schema working group
// regarding whether steps in the XPath must be
// fully qualified if the grammar has a target
// namespace. -Ac
// RESOLUTION: Yes.
Field.XPath fXpath = new Field.XPath(fText, fStringPool,
fNamespacesScope);
// REVISIT: Get datatype validator. -Ac
// cannot statically determine type of field; not just because of descendant/union
// but because of <any> and <anyAttribute>. - NG
// DatatypeValidator validator = getDatatypeValidatorFor(parent, sXpath, fXpath);
// if (DEBUG_IC_DATATYPES) {
// System.out.println("<ICD>: datatype validator: "+validator);
// must find DatatypeValidator in the Validator...
Field field = new Field(fXpath, ic);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: field: "+field);
}
ic.addField(field);
}
catch (XPathException e) {
// REVISIT: Add error message.
reportGenericSchemaError(e.getMessage());
return;
}
fElem = XUtil.getNextSiblingElement(fElem);
}
} // traverseIdentityConstraint(IdentityConstraint,Element)
/* This code is no longer used because datatypes can't be found statically for ID constraints.
private DatatypeValidator getDatatypeValidatorFor(Element element,
Selector.XPath sxpath,
Field.XPath fxpath)
throws Exception {
// variables
String ename = element.getAttribute("name");
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: XMLValidator#getDatatypeValidatorFor("+
ename+','+sxpath+','+fxpath+')');
}
int localpart = fStringPool.addSymbol(ename);
String targetNamespace = fSchemaRootElement.getAttribute("targetNamespace");
int uri = fStringPool.addSymbol(targetNamespace);
int edeclIndex = fSchemaGrammar.getElementDeclIndex(uri, localpart,
Grammar.TOP_LEVEL_SCOPE);
// walk selector
XPath.LocationPath spath = sxpath.getLocationPath();
XPath.Step[] ssteps = spath.steps;
for (int i = 0; i < ssteps.length; i++) {
XPath.Step step = ssteps[i];
XPath.Axis axis = step.axis;
XPath.NodeTest nodeTest = step.nodeTest;
switch (axis.type) {
case XPath.Axis.ATTRIBUTE: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("not allowed to select attribute");
return null;
}
case XPath.Axis.CHILD: {
int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex);
if (index == -1) {
index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE);
}
if (index == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"');
return null;
}
edeclIndex = index;
break;
}
case XPath.Axis.SELF: {
// no-op
break;
}
default: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("invalid selector axis");
return null;
}
}
}
// walk field
XPath.LocationPath fpath = fxpath.getLocationPath();
XPath.Step[] fsteps = fpath.steps;
for (int i = 0; i < fsteps.length; i++) {
XPath.Step step = fsteps[i];
XPath.Axis axis = step.axis;
XPath.NodeTest nodeTest = step.nodeTest;
switch (axis.type) {
case XPath.Axis.ATTRIBUTE: {
if (i != fsteps.length - 1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("attribute must be last step");
return null;
}
// look up validator
int adeclIndex = fSchemaGrammar.getAttributeDeclIndex(edeclIndex, nodeTest.name);
if (adeclIndex == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such attribute \""+fStringPool.toString(nodeTest.name.rawname)+'"');
}
XMLAttributeDecl adecl = new XMLAttributeDecl();
fSchemaGrammar.getAttributeDecl(adeclIndex, adecl);
DatatypeValidator validator = adecl.datatypeValidator;
return validator;
}
case XPath.Axis.CHILD: {
int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex);
if (index == -1) {
index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE);
}
if (index == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"');
return null;
}
edeclIndex = index;
if (i < fsteps.length - 1) {
break;
}
// NOTE: Let fall through to self case so that we
// avoid duplicating code. -Ac
}
case XPath.Axis.SELF: {
// look up validator, if needed
if (i == fsteps.length - 1) {
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(edeclIndex, edecl);
if (edecl.type != XMLElementDecl.TYPE_SIMPLE) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("selected element is not of simple type");
return null;
}
DatatypeValidator validator = edecl.datatypeValidator;
if (validator == null) validator = new StringDatatypeValidator();
return validator;
}
break;
}
default: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("invalid selector axis");
return null;
}
}
}
// no validator!
// REVISIT: Add message. -Ac
reportGenericSchemaError("No datatype validator for field "+fxpath+
" of element "+ename);
return null;
} // getDatatypeValidatorFor(XPath):DatatypeValidator
*/ // back in to live code...
private String getElementNameFor(Element icnode) {
Element enode = (Element)icnode.getParentNode();
String ename = enode.getAttribute("name");
if (ename.length() == 0) {
ename = enode.getAttribute("ref");
}
return ename;
} // getElementNameFor(Element):String
int getLocalPartIndex(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return fStringPool.addSymbol(localpart);
}
String getLocalPart(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return localpart;
}
int getPrefixIndex(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return fStringPool.addSymbol(prefix);
}
String getPrefix(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return prefix;
}
private void checkSubstitutionGroupOK(Element elementDecl, Element substitutionGroupElementDecl,
boolean noErrorSoFar, int substitutionGroupElementDeclIndex, ComplexTypeInfo typeInfo,
ComplexTypeInfo substitutionGroupEltTypeInfo, DatatypeValidator dv,
DatatypeValidator substitutionGroupEltDV) throws Exception {
// here we must do two things:
// 1. Make sure there actually *is* a relation between the types of
// the element being nominated and the element doing the nominating;
// (see PR 3.3.6 point #3 in the first tableau, for instance; this
// and the corresponding tableaux from 3.4.6 and 3.14.6 rule out the nominated
// element having an anonymous type declaration.
// 2. Make sure the nominated element allows itself to be nominated by
// an element with the given type-relation.
// Note: we assume that (complex|simple)Type processing checks
// whether the type in question allows itself to
// be modified as this element desires.
// Check for type relationship;
// that is, make sure that the type we're deriving has some relatoinship
// to substitutionGroupElt's type.
if (typeInfo != null) {
int derivationMethod = typeInfo.derivedBy;
if(typeInfo.baseComplexTypeInfo == null) {
if (typeInfo.baseDataTypeValidator != null) { // take care of complexType based on simpleType case...
DatatypeValidator dTemp = typeInfo.baseDataTypeValidator;
for(; dTemp != null; dTemp = dTemp.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTemp == substitutionGroupEltDV) break;
}
if (dTemp == null) {
if(substitutionGroupEltDV instanceof UnionDatatypeValidator) {
// dv must derive from one of its members...
Vector subUnionMemberDV = ((UnionDatatypeValidator)substitutionGroupEltDV).getBaseValidators();
int subUnionSize = subUnionMemberDV.size();
boolean found = false;
for (int i=0; i<subUnionSize && !found; i++) {
DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i);
DatatypeValidator dTempOrig = typeInfo.baseDataTypeValidator;
for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTempSub == dTempOrig) {
found = true;
break;
}
}
}
if(!found) {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else { // now let's see if substitutionGroup element allows this:
if((derivationMethod & fSchemaGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
} else {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " which is part of a substitution must have a type which derives from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else {
String eltBaseName = typeInfo.baseComplexTypeInfo.typeName;
ComplexTypeInfo subTypeInfo = substitutionGroupEltTypeInfo;
for (; subTypeInfo != null && !subTypeInfo.typeName.equals(eltBaseName); subTypeInfo = subTypeInfo.baseComplexTypeInfo);
if (subTypeInfo == null) { // then this type isn't in the chain...
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type whose base is " + eltBaseName + "; this basetype does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
} else { // type is fine; does substitutionElement allow this?
if((derivationMethod & fSchemaGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
}
} else if (dv != null) { // do simpleType case...
// first, check for type relation.
if (!(checkSimpleTypeDerivationOK(dv,substitutionGroupEltDV))) {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
else { // now let's see if substitutionGroup element allows this:
if((SchemaSymbols.RESTRICTION & fSchemaGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
}
}
// A utility method to check whether a particular datatypevalidator d, was validly
// derived from another datatypevalidator, b
private boolean checkSimpleTypeDerivationOK(DatatypeValidator d, DatatypeValidator b) {
DatatypeValidator dTemp = d;
for(; dTemp != null; dTemp = dTemp.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTemp == b) break;
}
if (dTemp == null) {
// now if b is a union, then we can
// derive from it if we derive from any of its members' types.
if(b instanceof UnionDatatypeValidator) {
// d must derive from one of its members...
Vector subUnionMemberDV = ((UnionDatatypeValidator)b).getBaseValidators();
int subUnionSize = subUnionMemberDV.size();
boolean found = false;
for (int i=0; i<subUnionSize && !found; i++) {
DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i);
DatatypeValidator dTempOrig = d;
for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTempSub == dTempOrig) {
found = true;
break;
}
}
}
if(!found) {
return false;
}
} else {
return false;
}
}
return true;
}
// this originally-simple method is much -complicated by the fact that, when we're
// redefining something, we've not only got to look at the space of the thing
// we're redefining but at the original schema too.
// The idea is to start from the top, then go down through
// our list of schemas until we find what we aant.
// This should not often be necessary, because we've processed
// all redefined schemas, but three are conditions in which
// not all elements so redefined may have been promoted to
// the topmost level.
private Element getTopLevelComponentByName(String componentCategory, String name) throws Exception {
Element child = null;
SchemaInfo curr = fSchemaInfoListRoot;
for (; curr != null || curr == fSchemaInfoListRoot; curr = curr.getNext()) {
if (curr != null) curr.restore();
if ( componentCategory.equals(SchemaSymbols.ELT_GROUP) ) {
child = (Element) fSchemaGrammar.topLevelGroupDecls.get(name);
}
else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP ) ) {
child = (Element) fSchemaGrammar.topLevelAttrGrpDecls.get(name);
}
else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTE ) ) {
child = (Element) fSchemaGrammar.topLevelAttrDecls.get(name);
}
if (child != null ) {
break;
}
child = XUtil.getFirstChildElement(fSchemaRootElement);
if (child == null) {
continue;
}
while (child != null ){
if ( child.getLocalName().equals(componentCategory)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) {
break;
}
} else if (fRedefineSucceeded && child.getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) {
Element gChild = XUtil.getFirstChildElement(child);
while (gChild != null ){
if (gChild.getLocalName().equals(componentCategory)) {
if (gChild.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) {
break;
}
}
gChild = XUtil.getNextSiblingElement(gChild);
}
if (gChild != null) {
child = gChild;
break;
}
}
child = XUtil.getNextSiblingElement(child);
}
if (child != null || fSchemaInfoListRoot == null) break;
}
// have to reset fSchemaInfoList
if(curr != null)
curr.restore();
else
if (fSchemaInfoListRoot != null)
fSchemaInfoListRoot.restore();
return child;
}
private boolean isTopLevel(Element component) {
String parentName = component.getParentNode().getLocalName();
return (parentName.endsWith(SchemaSymbols.ELT_SCHEMA))
|| (parentName.endsWith(SchemaSymbols.ELT_REDEFINE)) ;
}
DatatypeValidator getTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception {
// The following impl is for the case where every Schema Grammar has its own instance of DatatypeRegistry.
// Now that we have only one DataTypeRegistry used by all schemas. this is not needed.
/**
* Traverses notation declaration
* and saves it in a registry.
* Notations are stored in registry with the following
* key: "uri:localname"
*
* @param notation child <notation>
* @return local name of notation
* @exception Exception
*/
private String traverseNotationDecl( Element notation ) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(notation, scope);
String name = notation.getAttribute(SchemaSymbols.ATT_NAME);
String qualifiedName =name;
if (fTargetNSURIString.length () != 0) {
qualifiedName = fTargetNSURIString+":"+name;
}
if (fNotationRegistry.get(qualifiedName)!=null) {
return name;
}
String publicId = notation.getAttribute(SchemaSymbols.ATT_PUBLIC);
String systemId = notation.getAttribute(SchemaSymbols.ATT_SYSTEM);
if (publicId.length() == 0 && systemId.length() == 0) {
//REVISIT: update error messages
reportGenericSchemaError("<notation> declaration is invalid");
}
if (name.equals("")) {
//REVISIT: update error messages
reportGenericSchemaError("<notation> declaration does not have a name");
}
fNotationRegistry.put(qualifiedName, name);
//we don't really care if something inside <notation> is wrong..
checkContent( notation, XUtil.getFirstChildElement(notation), true );
//REVISIT: wait for DOM L3 APIs to pass info to application
//REVISIT: SAX2 does not support notations. API should be changed.
return name;
}
/**
* This methods will traverse notation from current schema,
* as well as from included or imported schemas
*
* @param notationName
* localName of notation
* @param uriStr uriStr for schema grammar
* @return return local name for Notation (if found), otherwise
* return empty string;
* @exception Exception
*/
private String traverseNotationFromAnotherSchema( String notationName , String uriStr ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseNotationDeclFromAnotherSchema, "+
"schema uri: " + uriStr
+", groupName: " + notationName);
return "";
}
String savedNSURIString = fTargetNSURIString;
fTargetNSURIString = fStringPool.toString(fStringPool.addSymbol(aGrammar.getTargetNamespaceURI()));
if (DEBUGGING) {
System.out.println("[traverseFromAnotherSchema]: " + fTargetNSURIString);
}
String qualifiedName = fTargetNSURIString + ":" + notationName;
String localName = (String)fNotationRegistry.get(qualifiedName);
if(localName != null ) // we've already traversed this notation
return localName;
//notation decl has not been traversed yet
Element notationDecl = (Element) aGrammar.topLevelNotationDecls.get((Object)notationName);
if (notationDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no notation named \"" + notationName
+ "\" was defined in schema : " + uriStr);
return "";
}
localName = traverseNotationDecl(notationDecl);
fTargetNSURIString = savedNSURIString;
return localName;
} // end of method traverseNotationFromAnotherSchema
/**
* Traverse Group Declaration.
*
* <group
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* ref = QName>
* Content: (annotation? , (all | choice | sequence)?)
* <group/>
*
* @param elementDecl
* @return
* @exception Exception
*/
private int traverseGroupDecl( Element groupDecl ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(groupDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(groupDecl, scope);
String groupName = groupDecl.getAttribute(SchemaSymbols.ATT_NAME);
String ref = groupDecl.getAttribute(SchemaSymbols.ATT_REF);
Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true );
if (!ref.equals("")) {
if (isTopLevel(groupDecl))
// REVISIT: localize
reportGenericSchemaError ( "A group with \"ref\" present must not have <schema> or <redefine> as its parent");
if (!groupName.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "group " + groupName + " cannot refer to another group, but it refers to " + ref);
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
return traverseGroupDeclFromAnotherSchema(localpart, uriStr);
}
Object contentSpecHolder = fGroupNameRegistry.get(uriStr + "," + localpart);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// Check if we are in the middle of traversing this group (i.e. circular references)
if (fCurrentGroupNameStack.search((Object)localpart) > - 1) {
reportGenericSchemaError("mg-props-correct: Circular definition for group " + localpart);
return -2;
}
int contentSpecIndex = -1;
Element referredGroup = getTopLevelComponentByName(SchemaSymbols.ELT_GROUP,localpart);
if (referredGroup == null) {
// REVISIT: Localize
reportGenericSchemaError("Group " + localpart + " not found in the Schema");
//REVISIT, this should be some custom Exception
//throw new RuntimeException("Group " + localpart + " not found in the Schema");
}
else {
contentSpecIndex = traverseGroupDecl(referredGroup);
}
return contentSpecIndex;
} else if (groupName.equals(""))
// REVISIT: Localize
reportGenericSchemaError("a <group> must have a name or a ref present");
String qualifiedGroupName = fTargetNSURIString + "," + groupName;
Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// if we're here then we're traversing a top-level group that we've never seen before.
// Push the group name onto a stack, so that we can check for circular groups
fCurrentGroupNameStack.push(groupName);
int index = -2;
boolean illegalChild = false;
String childName =
(child != null) ? child.getLocalName() : "";
if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
}
else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if (child != null && XUtil.getNextSiblingElement(child) != null) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if ( ! illegalChild && child != null) {
index = handleOccurrences(index, child, CHILD_OF_GROUP);
}
contentSpecHolder = new Integer(index);
fCurrentGroupNameStack.pop();
fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder);
return index;
}
private int traverseGroupDeclFromAnotherSchema( String groupName , String uriStr ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseGroupDeclFromAnotherSchema, "+
"schema uri: " + uriStr
+", groupName: " + groupName);
return -1;
}
Element groupDecl = (Element) aGrammar.topLevelGroupDecls.get((Object)groupName);
if (groupDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no group named \"" + groupName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true );
String qualifiedGroupName = fTargetNSURIString + "," + groupName;
Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// if we're here then we're traversing a top-level group that we've never seen before.
int index = -2;
boolean illegalChild = false;
String childName = (child != null) ? child.getLocalName() : "";
if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
}
else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if ( ! illegalChild && child != null) {
index = handleOccurrences( index, child);
}
contentSpecHolder = new Integer(index);
fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder);
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
return index;
} // end of method traverseGroupDeclFromAnotherSchema
/**
*
* Traverse the Sequence declaration
*
* <sequence
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </sequence>
*
**/
int traverseSequence (Element sequenceDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(sequenceDecl, scope);
Element child = checkContent(sequenceDecl, XUtil.getFirstChildElement(sequenceDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
boolean seeParticle = false;
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
// A content type of all can only appear
// as the content type of a complex type definition.
if (hasAllContent(index)) {
reportSchemaError(SchemaMessageProvider.AllContentLimited,
new Object [] { "sequence" });
continue;
}
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(
SchemaMessageProvider.SeqChoiceContentRestricted,
new Object [] { "sequence", childName });
continue;
}
if (index != -2)
hadContent = true;
if (seeParticle) {
index = handleOccurrences( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
/**
*
* Traverse the Choice declaration
*
* <choice
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </choice>
*
**/
int traverseChoice (Element choiceDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(choiceDecl, scope);
// REVISIT: traverseChoice, traverseSequence can be combined
Element child = checkContent(choiceDecl, XUtil.getFirstChildElement(choiceDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
boolean seeParticle = false;
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
// A model group whose {compositor} is "all" can only appear
// as the {content type} of a complex type definition.
if (hasAllContent(index)) {
reportSchemaError(SchemaMessageProvider.AllContentLimited,
new Object [] { "choice" });
continue;
}
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(
SchemaMessageProvider.SeqChoiceContentRestricted,
new Object [] { "choice", childName });
continue;
}
if (index != -2)
hadContent = true;
if (seeParticle) {
index = handleOccurrences( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
/**
*
* Traverse the "All" declaration
*
* <all
* id = ID
* maxOccurs = 1 : 1
* minOccurs = (0 | 1) : 1>
* Content: (annotation? , element*)
* </all>
**/
int traverseAll(Element allDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(allDecl, scope);
Element child = checkContent(allDecl,
XUtil.getFirstChildElement(allDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_ALL;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
String childName = child.getLocalName();
// Only elements are allowed in <all>
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode(
XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
index = handleOccurrences(index, child, PROCESSING_ALL);
}
else {
reportSchemaError(SchemaMessageProvider.AllContentRestricted,
new Object [] { childName });
continue;
}
hadContent = true;
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
// Determines whether a content spec tree represents an "all" content model
private boolean hasAllContent(int contentSpecIndex) {
// If the content is not empty, is the top node ALL?
if (contentSpecIndex > -1) {
XMLContentSpec content = new XMLContentSpec();
fSchemaGrammar.getContentSpec(contentSpecIndex, content);
// An ALL node could be optional, so we have to be prepared
// to look one level below a ZERO_OR_ONE node for an ALL.
if (content.type == XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE) {
fSchemaGrammar.getContentSpec(content.value, content);
}
return (content.type == XMLContentSpec.CONTENTSPECNODE_ALL);
}
return false;
}
// utilities from Tom Watson's SchemaParser class
// TO DO: Need to make this more conformant with Schema int type parsing
private int parseInt (String intString) throws Exception
{
if ( intString.equals("*") ) {
return SchemaSymbols.INFINITY;
} else {
return Integer.parseInt (intString);
}
}
private int parseSimpleFinal (String finalString) throws Exception
{
if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.ENUMERATION+SchemaSymbols.RESTRICTION+SchemaSymbols.LIST;
} else {
int enumerate = 0;
int restrict = 0;
int list = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ("restriction in set twice");
}
} else if ( token.equals (SchemaSymbols.ELT_LIST) ) {
if ( list == 0 ) {
list = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ("list in set twice");
}
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid value (" +
finalString +
")" );
}
}
return enumerate+list;
}
}
private int parseDerivationSet (String finalString) throws Exception
{
if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION;
} else {
int extend = 0;
int restrict = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "extension already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "restriction already in set" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
return extend+restrict;
}
}
private int parseBlockSet (String blockString) throws Exception
{
if( blockString == null)
return fBlockDefault;
else if ( blockString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.SUBSTITUTION+SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION;
} else {
int extend = 0;
int restrict = 0;
int substitute = 0;
StringTokenizer t = new StringTokenizer (blockString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_SUBSTITUTION) ) {
if ( substitute == 0 ) {
substitute = SchemaSymbols.SUBSTITUTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'substitution' already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'extension' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'restriction' is already in the list" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid block value (" + blockString + ")" );
}
}
int defaultVal = extend+restrict+substitute;
return (defaultVal == 0 ? fBlockDefault : defaultVal);
}
}
private int parseFinalSet (String finalString) throws Exception
{
if( finalString == null) {
return fFinalDefault;
}
else if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.UNION;
} else {
int extend = 0;
int restrict = 0;
int list = 0;
int union = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ELT_UNION) ) {
if ( union == 0 ) {
union = SchemaSymbols.UNION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'union' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'extension' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ELT_LIST) ) {
if ( list == 0 ) {
list = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'list' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'restriction' is already in the list" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
int defaultVal = extend+restrict+list+union;
return (defaultVal == 0 ? fFinalDefault : defaultVal);
}
}
private void reportGenericSchemaError (String error) throws Exception {
if (fErrorReporter == null) {
System.err.println("__TraverseSchemaError__ : " + error);
}
else {
reportSchemaError (SchemaMessageProvider.GenericError, new Object[] { error });
}
}
private void reportSchemaError(int major, Object args[]) throws Exception {
if (fErrorReporter == null) {
System.out.println("__TraverseSchemaError__ : " + SchemaMessageProvider.fgMessageKeys[major]);
for (int i=0; i< args.length ; i++) {
System.out.println((String)args[i]);
}
}
else {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
major,
SchemaMessageProvider.MSG_NONE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
static class Resolver implements EntityResolver {
private static final String SYSTEM[] = {
"http:
"http:
"http:
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
"versionInfo.ent",
};
public InputSource resolveEntity(String publicId, String systemId)
throws IOException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// use default resolution
return null;
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) throws SAXException {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
throw ex;
}
// Private methods
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
static class IgnoreWhitespaceParser
extends DOMParser {
public void ignorableWhitespace(char ch[], int start, int length) {}
public void ignorableWhitespace(int dataIdx) {}
} // class IgnoreWhitespaceParser
// When in a <redefine>, type definitions being used (and indeed
// refs to <group>'s and <attributeGroup>'s) may refer to info
// items either in the schema being redefined, in the <redefine>,
// or else in the schema doing the redefining. Because of this
// latter we have to be prepared sometimes to look for our type
// definitions outside the schema stored in fSchemaRootElement.
// This simple class does this; it's just a linked list that
// lets us look at the <schema>'s on the queue; note also that this
// should provide us with a mechanism to handle nested <redefine>'s.
// It's also a handy way of saving schema info when importing/including; saves some code.
public class SchemaInfo {
private Element saveRoot;
private SchemaInfo nextRoot;
private SchemaInfo prevRoot;
private String savedSchemaURL = fCurrentSchemaURL;
private boolean saveElementDefaultQualified = fElementDefaultQualified;
private boolean saveAttributeDefaultQualified = fAttributeDefaultQualified;
private int saveScope = fCurrentScope;
private int saveBlockDefault = fBlockDefault;
private int saveFinalDefault = fFinalDefault;
public SchemaInfo ( boolean saveElementDefaultQualified, boolean saveAttributeDefaultQualified,
int saveBlockDefault, int saveFinalDefault,
int saveScope, String savedSchemaURL, Element saveRoot, SchemaInfo nextRoot, SchemaInfo prevRoot) {
this.saveElementDefaultQualified = saveElementDefaultQualified;
this.saveAttributeDefaultQualified = saveAttributeDefaultQualified;
this.saveBlockDefault = saveBlockDefault;
this.saveFinalDefault = saveFinalDefault;
this.saveScope = saveScope ;
this.savedSchemaURL = savedSchemaURL;
this.saveRoot = saveRoot ;
this.nextRoot = nextRoot;
this.prevRoot = prevRoot;
}
public void setNext (SchemaInfo next) {
nextRoot = next;
}
public SchemaInfo getNext () {
return nextRoot;
}
public void setPrev (SchemaInfo prev) {
prevRoot = prev;
}
public String getCurrentSchemaURL() { return savedSchemaURL; }
public SchemaInfo getPrev () {
return prevRoot;
}
public Element getRoot() { return saveRoot; }
// NOTE: this has side-effects!!!
public void restore() {
fCurrentSchemaURL = savedSchemaURL;
fCurrentScope = saveScope;
fElementDefaultQualified = saveElementDefaultQualified;
fAttributeDefaultQualified = saveAttributeDefaultQualified;
fBlockDefault = saveBlockDefault;
fFinalDefault = saveFinalDefault;
fSchemaRootElement = saveRoot;
}
} // class SchemaInfo
} // class TraverseSchema |
package org.blitzortung.android.map.overlay;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.blitzortung.android.data.beans.Stroke;
import org.blitzortung.android.map.OwnMapActivity;
import org.blitzortung.android.map.overlay.color.StrokeColorHandler;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;
import android.text.format.DateFormat;
public class StrokesOverlay extends PopupOverlay<StrokeOverlayItem> {
@SuppressWarnings("unused")
private static final String TAG = "overlay.StrokesOverlay";
ArrayList<StrokeOverlayItem> items;
StrokeColorHandler colorHandler;
static private Drawable DefaultDrawable;
static {
Shape shape = new StrokeShape(1, 0);
DefaultDrawable = new ShapeDrawable(shape);
}
public StrokesOverlay(OwnMapActivity activity, StrokeColorHandler colorHandler) {
super(activity, boundCenter(DefaultDrawable));
this.colorHandler = colorHandler;
items = new ArrayList<StrokeOverlayItem>();
populate();
}
@Override
protected StrokeOverlayItem createItem(int index) {
return items.get(index);
}
@Override
public int size() {
return items.size();
}
@Override
public void draw(Canvas canvas, com.google.android.maps.MapView mapView, boolean shadow) {
if (!shadow) {
super.draw(canvas, mapView, false);
}
}
public void addStrokes(List<Stroke> strokes) {
for (Stroke stroke : strokes) {
items.add(new StrokeOverlayItem(stroke));
}
populate();
}
public void clear() {
items.clear();
}
int shapeSize;
public void updateShapeSize(int zoomLevel) {
this.shapeSize = zoomLevel + 1;
refresh();
}
public void refresh() {
Date now = new GregorianCalendar().getTime();
int current_section = -1;
Drawable drawable = null;
int colors[] = colorHandler.getColors();
for (StrokeOverlayItem item : items) {
int section = (int) (now.getTime() - item.getTimestamp().getTime()) / 1000 / 60 / 10;
if (section >= colors.length)
section = colors.length - 1;
if (current_section != section) {
drawable = getDrawable(section, colors[section]);
}
item.setMarker(drawable);
}
}
private Drawable getDrawable(int section, int color) {
Shape shape = new StrokeShape(shapeSize, color);
return new ShapeDrawable(shape);
}
@Override
protected boolean onTap(int index) {
if (index < items.size()) {
StrokeOverlayItem item = items.get(index);
if (item != null && item.getPoint() != null && item.getTimestamp() != null) {
showPopup(item.getPoint(), (String) DateFormat.format("kk:mm:ss", item.getTimestamp()));
return true;
}
}
clearPopup();
return false;
}
public void expireStrokes(Date expireTime) {
List<StrokeOverlayItem> toRemove = new ArrayList<StrokeOverlayItem>();
for (StrokeOverlayItem item : items) {
if (item.getTimestamp().before(expireTime)) {
toRemove.add(item);
} else {
break;
}
}
if (toRemove.size() > 0) {
items.removeAll(toRemove);
}
}
} |
package SW9.controllers;
import SW9.NewMain;
import SW9.abstractions.Component;
import SW9.abstractions.Edge;
import SW9.abstractions.Location;
import SW9.backend.UPPAALDriver;
import SW9.presentations.CanvasPresentation;
import SW9.presentations.LocationPresentation;
import SW9.utility.UndoRedoStack;
import SW9.utility.colors.Color;
import SW9.utility.helpers.BindingHelper;
import SW9.utility.helpers.SelectHelperNew;
import SW9.utility.keyboard.Keybind;
import SW9.utility.keyboard.KeyboardTracker;
import com.jfoenix.controls.JFXTextField;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Path;
import javafx.scene.shape.Rectangle;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
public class LocationController implements Initializable, SelectHelperNew.ColorSelectable {
private static final AtomicInteger hiddenLocationID = new AtomicInteger(0);
private static final long DOUBLE_PRESS_SHOW_PROPERTIES_DELAY = 500;
private final ObjectProperty<Location> location = new SimpleObjectProperty<>();
private final ObjectProperty<Component> component = new SimpleObjectProperty<>();
public Group root;
public Circle initialIndicator;
public StackPane finalIndicator;
public Group shakeContent;
public Label nameLabel;
public Rectangle rectangle;
public Rectangle rectangleShakeIndicator;
public Circle circle;
public Circle circleShakeIndicator;
public Path octagon;
public Path octagonShakeIndicator;
public StackPane propertiesPane;
public JFXTextField nameField;
public TextArea invariantField;
private boolean isPlaced;
private long lastPress = 0;
private TimerTask reachabilityCheckTask;
@Override
public void initialize(final URL location, final ResourceBundle resources) {
this.location.addListener((obsLocation, oldLocation, newLocation) -> {
// The radius property on the abstraction must reflect the radius in the view
newLocation.radiusProperty().bind(circle.radiusProperty());
// The scale property on the abstraction must reflect the radius in the view
newLocation.scaleProperty().bind(root.scaleXProperty());
// initialize the name field and its bindings
nameField.setText(newLocation.getName());
newLocation.nameProperty().bind(nameField.textProperty());
// initialize the invariant field and its bindings
invariantField.setText(newLocation.getInvariant());
newLocation.invariantProperty().bind(invariantField.textProperty());
});
// Scale x and y 1:1 (based on the x-scale)
root.scaleYProperty().bind(root.scaleXProperty());
// Register click listener on canvas to hide the property pane when the canvas is clicked
CanvasPresentation.mouseTracker.registerOnMouseClickedEventHandler(event -> propertiesPane.setVisible(false));
// Register a key-bind for hiding the property pane (using a hidden locationID)
KeyboardTracker.registerKeybind(KeyboardTracker.HIDE_LOCATION_PROPERTY_PANE + hiddenLocationID.getAndIncrement(), new Keybind(new KeyCodeCombination(KeyCode.ESCAPE), () -> {
propertiesPane.setVisible(false);
}));
initializeReachabilityCheck();
}
public void initializeReachabilityCheck() {
final int interval = 5000;
// Could not run query
reachabilityCheckTask = new TimerTask() {
@Override
public void run() {
if (getComponent() == null || getLocation() == null) return;
// The location might have been remove from the component (through ctrl + z)
if (!getComponent().getLocations().contains(getLocation())) return;
UPPAALDriver.verify(
"E<> " + getComponent().getName() + "." + getLocation().getName(),
result -> {
final LocationPresentation locationPresentation = (LocationPresentation) LocationController.this.root;
locationPresentation.animateShakeWarning(!result);
},
e -> {
System.out.println("hsj");
System.out.println(e);
// Could not run query
},
NewMain.getProject().getComponents()
);
}
};
new Timer().schedule(reachabilityCheckTask, 0, interval);
}
public Location getLocation() {
return location.get();
}
public void setLocation(final Location location) {
this.location.set(location);
if (location.getType().equals(Location.Type.NORMAL)) {
root.layoutXProperty().bind(location.xProperty());
root.layoutYProperty().bind(location.yProperty());
} else {
location.xProperty().bind(root.layoutXProperty());
location.yProperty().bind(root.layoutYProperty());
isPlaced = true;
}
}
public ObjectProperty<Location> locationProperty() {
return location;
}
public Component getComponent() {
return component.get();
}
public void setComponent(final Component component) {
this.component.set(component);
}
public ObjectProperty<Component> componentProperty() {
return component;
}
@FXML
private void mouseEntered() {
circle.setCursor(Cursor.HAND);
((LocationPresentation) root).animateHoverEntered();
// Keybind for making location urgent
KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_URGENT, new Keybind(new KeyCodeCombination(KeyCode.U), () -> {
final Location.Urgency previousUrgency = location.get().getUrgency();
if (previousUrgency.equals(Location.Urgency.URGENT)) {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.NORMAL);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
});
} else {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.URGENT);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
});
}
}));
// Keybind for making location committed
KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED, new Keybind(new KeyCodeCombination(KeyCode.C), () -> {
final Location.Urgency previousUrgency = location.get().getUrgency();
if (previousUrgency.equals(Location.Urgency.COMMITTED)) {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.NORMAL);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
});
} else {
UndoRedoStack.push(() -> { // Perform
getLocation().setUrgency(Location.Urgency.COMMITTED);
}, () -> { // Undo
getLocation().setUrgency(previousUrgency);
});
}
}));
}
@FXML
private void mouseExited() {
circle.setCursor(Cursor.DEFAULT);
((LocationPresentation) root).animateHoverExited();
KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_URGENT);
KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED);
}
@FXML
private void mouseClicked(final MouseEvent event) {
event.consume();
// Double clicking the location opens the properties pane
if(lastPress + DOUBLE_PRESS_SHOW_PROPERTIES_DELAY >= System.currentTimeMillis()) {
propertiesPane.setVisible(true);
// Place the location in front (so that the properties pane is above edges etc)
root.toFront();
} else {
lastPress = System.currentTimeMillis();
}
}
@FXML
private void mousePressed(final MouseEvent event) {
final Component component = getComponent();
event.consume();
if (isPlaced) {
final Edge unfinishedEdge = component.getUnfinishedEdge();
if (unfinishedEdge != null) {
unfinishedEdge.setTargetLocation(getLocation());
} else {
// If shift is being held down, start drawing a new edge
if (event.isShiftDown()) {
final Edge newEdge = new Edge(getLocation());
UndoRedoStack.push(() -> { // Perform
component.addEdge(newEdge);
}, () -> { // Undo
component.removeEdge(newEdge);
});
}
// Otherwise, select the location
else {
SelectHelperNew.select(this);
}
}
} else {
BindingHelper.place(getLocation(), getComponent().xProperty(), getComponent().yProperty());
isPlaced = true;
}
}
@Override
public void color(final Color color, final Color.Intensity intensity) {
final Location location = getLocation();
// Set the color of the location
location.setColorIntensity(intensity);
location.setColor(color);
}
@Override
public Color getColor() {
return getLocation().getColor();
}
@Override
public Color.Intensity getColorIntensity() {
return getLocation().getColorIntensity();
}
@Override
public void select() {
((SelectHelperNew.Selectable) root).select();
}
@Override
public void deselect() {
((SelectHelperNew.Selectable) root).deselect();
}
} |
package org.bostonandroid.umbrellatoday;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
public class AboutUmbrellaToday extends Activity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
TextView tv = (TextView) findViewById(R.id.about);
tv.setText(Html.fromHtml(getString(R.string.about_text)));
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
} |
package SW9.presentations;
import SW9.abstractions.Component;
import SW9.abstractions.Edge;
import SW9.controllers.EdgeController;
import SW9.utility.colors.Color;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Circle;
import java.io.IOException;
import java.net.URL;
import static SW9.presentations.CanvasPresentation.GRID_SIZE;
public class EdgePresentation extends Group {
private final EdgeController controller;
private final ObjectProperty<Edge> edge = new SimpleObjectProperty<>();
private final ObjectProperty<Component> component = new SimpleObjectProperty<>();
public EdgePresentation(final Edge edge, final Component component) {
final URL url = this.getClass().getResource("EdgePresentation.fxml");
final FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(url);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try {
fxmlLoader.setRoot(this);
fxmlLoader.load(url.openStream());
controller = fxmlLoader.getController();
controller.setEdge(edge);
this.edge.bind(controller.edgeProperty());
controller.setComponent(component);
this.component.bind(controller.componentProperty());
initializeEdgeProperties();
} catch (final IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void initializeEdgeProperties() {
initializeProperty(controller.selectContainer, controller.selectCircle, controller.selectLabel, 1);
initializeProperty(controller.guardContainer, controller.guardCircle, controller.guardLabel, 2);
initializeProperty(controller.syncContainer, controller.syncCircle, controller.syncLabel, 3);
initializeProperty(controller.updateContainer, controller.updateCircle, controller.updateLabel, 4);
}
private void initializeProperty(final StackPane container, final Circle circle, final Label label, final int index) {
final Edge edge = controller.getEdge();
circle.setFill(javafx.scene.paint.Color.WHITE);
circle.setStroke(Color.GREY.getColor(Color.Intensity.I500));
label.setTextFill(Color.GREY.getTextColor(Color.Intensity.I50));
final Runnable updatePlacement = () -> {
// todo: calculate the placement differently if source = target
if (edge.getSourceLocation().equals(edge.getTargetLocation())) return;
if (edge.getTargetLocation() == null) return;
final double x1 = edge.getSourceLocation().getX();
final double x2 = edge.getTargetLocation().getX();
final double y1 = edge.getSourceLocation().getY();
final double y2 = edge.getTargetLocation().getY();
final double m = (y2 - y1) / (x2 - x1);
final double angle = Math.atan(m);
final double hype = GRID_SIZE + index * GRID_SIZE * 2;
final double w = Math.cos(angle) * hype;
final double h = Math.sqrt(Math.pow(hype, 2) - Math.pow(w, 2));
if (x1 > x2) {
container.setLayoutX(x1 + w * -1);
} else {
container.setLayoutX(x1 + w);
}
if (y1 > y2) {
container.setLayoutY(y1 + h * -1);
} else {
container.setLayoutY(y1 + h);
}
};
edge.sourceLocationProperty().addListener(observable -> {
edge.getSourceLocation().xProperty().addListener(observable1 -> updatePlacement.run());
edge.getSourceLocation().yProperty().addListener(observable1 -> updatePlacement.run());
});
edge.targetLocationProperty().addListener(observable -> {
edge.getTargetLocation().xProperty().addListener(observable1 -> updatePlacement.run());
edge.getTargetLocation().yProperty().addListener(observable1 -> updatePlacement.run());
});
edge.getSourceLocation().xProperty().addListener(obs -> updatePlacement.run());
edge.getSourceLocation().yProperty().addListener(obs -> updatePlacement.run());
if (edge.getTargetLocation() == null) return;
edge.getTargetLocation().xProperty().addListener(obs -> updatePlacement.run());
edge.getTargetLocation().yProperty().addListener(obs -> updatePlacement.run());
updatePlacement.run();
}
} |
package org.caleydo.view.bicluster.elem;
import gleem.linalg.Vec2f;
import gleem.linalg.Vec4f;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.view.opengl.layout2.GLElement;
import org.caleydo.core.view.opengl.layout2.GLElementContainer;
import org.caleydo.core.view.opengl.layout2.IGLElementContext;
import org.caleydo.core.view.opengl.layout2.layout.IGLLayout;
import org.caleydo.core.view.opengl.layout2.layout.IGLLayoutElement;
import org.caleydo.view.bicluster.util.Vec2d;
import com.google.common.base.Stopwatch;
/**
* @author Samuel Gratzl
* @author Michael Gillhofer
*/
public class AllClustersElement extends GLElementContainer implements IGLLayout {
float layoutStabilisationTime = 3000; // After X Milliseconds the layout is
// fixed until a cluster is moved
// resetDamping(); is called)
float repulsion = 200000f;
float attractionFactor = 400f;
float borderForceFactor = 300f;
// double aD = 0.3;
public Integer fixedElementsCount = 15;
private GLRootElement glRootElement;
/**
* @return the fixedElementsCount, see {@link #fixedElementsCount}
*/
public Integer getFixedElementsCount() {
return fixedElementsCount;
}
/**
* @param fixedElementsCount
* setter, see {@link fixedElementsCount}
*/
public void setFixedElementsCount(Integer fixedElementsCount) {
this.fixedElementsCount = fixedElementsCount;
}
public AllClustersElement(GLRootElement glRootElement) {
setLayout(this);
this.glRootElement = glRootElement;
}
@Override
protected void init(IGLElementContext context) {
super.init(context);
}
public void setData(List<TablePerspective> list, TablePerspective x) {
this.clear();
if (list != null) {
System.out.println("List size: " + list.size());
for (TablePerspective p : list) {
final ClusterElement el = new ClusterElement(p, x, this);
this.add(el);
}
}
}
private boolean isInitLayoutDone = false;
private GLElement dragedElement = null;
Stopwatch stopwatch = new Stopwatch();
float lastW, lastH;
@Override
public void doLayout(List<? extends IGLLayoutElement> children, float w,
float h) {
if (!isInitLayoutDone && !children.isEmpty()) {
initialLayout(children, w, h);
isInitLayoutDone = true;
} else {
if (lastW > w || lastH > h)
scaleView(children, w, h);
lastW = w;
lastH = h;
bringClustersBackToFrame(children, w, h);
clearClusterCollisions(children, w, h);
forceDirectedLayout(children, w, h);
}
for (IGLLayoutElement child : children) {
child.setSize(child.getSetWidth(), child.getSetHeight());
}
relayout();
}
private void bringClustersBackToFrame(
List<? extends IGLLayoutElement> children, float w, float h) {
for (IGLLayoutElement i : children) {
i.setLocation(i.getLocation().x() %w, i.getLocation().y()%h);
}
}
private void clearClusterCollisions(
List<? extends IGLLayoutElement> children, float w, float h) {
int k = 1;
for (IGLLayoutElement i : children) {
for (IGLLayoutElement j : children.subList(k, children.size())) {
Vec2d iCenter = getCenter((ClusterElement) i.asElement());
Vec2d jCenter = getCenter((ClusterElement) j.asElement());
if (iCenter.minus(jCenter).length() < 5) {
// move i
i.setLocation((i.getLocation().x() + 100) % w, (i
.getLocation().y() + 100) % h);
}
}
k++;
}
}
private void scaleView(List<? extends IGLLayoutElement> children, float w,
float h) {
for (IGLLayoutElement igllChild : children) {
GLElement child = igllChild.asElement();
Vec2f loc = child.getLocation();
child.setLocation(loc.x() * w / lastW, loc.y() * h / lastH);
}
}
double damping = 1f;
double timerInterval = 100;
Timer dampingTimer = new Timer();
public void resetDamping() {
damping = 1.f;
}
TimerTask timerTask = new TimerTask() { // periodic tasks for stabilizing
// layout after
// layoutStabilisationTime
// seconds.
@Override
public void run() {
// setDamping();
}
protected void setDamping() {
double amount = (1. / (layoutStabilisationTime / timerInterval));
if (damping >= amount)
damping -= amount;
else
damping = 0;
}
};
private ClusterElement hoveredElement;
// contains positions of the childs in [0,1] x [0,1] space
// Map<ClusterElement, Vec2d> virtualPositions = new HashMap<>();
/**
* @param children2
* @param w
* @param h
*/
private void forceDirectedLayout(List<? extends IGLLayoutElement> children,
float w, float h) {
// calculate the attraction based on the size of all overlaps
double xOverlapSize = 0, yOverlapSize = 0;
for (IGLLayoutElement iGLE : children) {
GLElement vGL = iGLE.asElement();
ClusterElement v = (ClusterElement) vGL;
xOverlapSize += v.getDimensionOverlapSize();
yOverlapSize += v.getRecordOverlapSize();
}
double attractionX = 1;
double attractionY = 1;
attractionX = attractionFactor / (xOverlapSize + yOverlapSize);
attractionY = attractionFactor / (yOverlapSize + xOverlapSize);
xOverlapSize /= 3;
yOverlapSize /= 3;
// layout begin
for (IGLLayoutElement iGLE : children) { // Loop through Vertices
GLElement vGL = iGLE.asElement();
ClusterElement i = (ClusterElement) vGL;
i.setRepForce(new Vec2d(0, 0));
i.setAttForce(new Vec2d(0, 0));
// repulsion
for (IGLLayoutElement jGLL : children) { // loop through other
// vertices
GLElement jElement = jGLL.asElement();
ClusterElement j = (ClusterElement) jElement;
if (j == i)
continue;
// squared distance between "u" and "v" in 2D space
// calculate the repulsion between two vertices
Vec2d distVec = getDistance(i, j);
double rsq = distVec.lengthSquared();
rsq *= distVec.length();
double forcex = repulsion * distVec.x() / rsq;
double forcey = repulsion * distVec.y() / rsq;
forcex += i.getRepForce().x();
forcey += i.getRepForce().y();
i.setRepForce(new Vec2d(forcex, forcey));
}
// attraction force calculation
for (IGLLayoutElement jGLL : children) {
GLElement jElement = jGLL.asElement();
ClusterElement j = (ClusterElement) jElement;
if (i == j)
continue;
List<Integer> xOverlap = i.getDimOverlap(j);
List<Integer> yOverlap = i.getRecOverlap(j);
if (xOverlap.size() == 0 && yOverlap.size() == 0)
continue;
int overlapSizeX = xOverlap.size();
int overlapSizeY = yOverlap.size();
Vec2d distVec = getDistance(j, i);
double dist = distVec.length/* Squared */();
double forcex = attractionX * distVec.x()
* (overlapSizeX + overlapSizeY) / dist; // * isXNeg;
double forcey = attractionY * distVec.y()
* (overlapSizeY + overlapSizeX) / dist; // * isYNeg;
// counting the attraction
forcex = i.getAttForce().x() + forcex;
forcey = i.getAttForce().y() + forcey;
i.setAttForce(new Vec2d(forcex, forcey));
}
// Border Force
Vec2d distFromTopLeft = getDistanceFromTopLeft(i, w, h);
Vec2d distFromBottomRight = getDistanceFromBottomRight(i, w, h);
double forceX = Math.exp(borderForceFactor
/ Math.abs(distFromTopLeft.x()));
forceX -= Math.exp(borderForceFactor
/ Math.abs(distFromBottomRight.x()));
double forceY = Math.exp(borderForceFactor
/ Math.abs(distFromTopLeft.y()));
forceY -= Math.exp(borderForceFactor
/ Math.abs(distFromBottomRight.y()));
i.setFrameForce(new Vec2d(forceX, forceY));
// Toolbar force
Vec2d distVec = getDistance(i, toolbar);
double rsq = distVec.lengthSquared();
rsq *= distVec.length();
double forcex = repulsion * distVec.x() / rsq;
double forcey = repulsion * distVec.y() / rsq;
forcex += i.getRepForce().x();
forcey += i.getRepForce().y();
i.setRepForce(new Vec2d(forcex, forcey));
}
for (IGLLayoutElement iGLL : children) {
ClusterElement i = (ClusterElement) iGLL.asElement();
Vec2d force = i.getAttForce().plus(i.getRepForce())
.plus(i.getFrameForce());
while (force.length() > 10)
force.scale(0.1);
Vec2d pos = getCenter(i);
pos = force.times(damping).plus(pos);
// System.out.println(i.getId() + ": ");
// System.out.println(" Att: " + i.getAttForce());
// System.out.println(" Rep: " + i.getRepForce());
// System.out.println(" Fra: " + i.getCenterForce());
// System.out.println(" Sum: " + force);
if (i != dragedElement && i != hoveredElement)
setLocation(i, (float) pos.x(), (float) pos.y(), w, h);
}
}
private Vec2d getDistance(ClusterElement i, GlobalToolBarElement tools) {
Vec2f toolsPos = tools.getAbsoluteLocation();
Vec2f toolsSize = tools.getSize();
Vec2d toolsCenter = new Vec2d(toolsPos.x() + toolsSize.x(),
toolsPos.y() + toolsSize.y());
Vec2d distVec = getCenter(i).minus(toolsCenter);
double distance = distVec.length();
Vec2f iSize = i.getSize();
Vec2f jSize = toolsSize;
double r1 = iSize.x() > iSize.y() ? iSize.x() / 2 : iSize.y() / 2;
double r2 = jSize.x() > jSize.y() ? jSize.x() / 2 : jSize.y() / 2;
distance -= Math.abs(r1) + Math.abs(r2);
distVec.normalize();
distVec.scale(distance);
return distVec;
}
private Vec2d getDistanceFromTopLeft(ClusterElement i, float w, float h) {
Vec2d pos = getCenter(i);
return pos;
}
private Vec2d getDistanceFromBottomRight(ClusterElement i, float w, float h) {
Vec2d dist = getDistanceFromTopLeft(i, w, h);
dist.setX(-(w - dist.x()));
dist.setY(-(h - dist.y()));
return dist;
}
private Vec2d getCenter(ClusterElement i) {
Vec2f vec = i.getLocation().addScaled(0.5f, i.getSize());
return new Vec2d(vec.x(), vec.y());
}
private Vec2d getDistance(ClusterElement i, ClusterElement j) {
Vec2d distVec = getCenter(i).minus(getCenter(j));
double distance = distVec.length();
Vec2f iSize = i.getSize();
Vec2f jSize = j.getSize();
double r1 = iSize.x() > iSize.y() ? iSize.x() / 2 : iSize.y() / 2;
double r2 = jSize.x() > jSize.y() ? jSize.x() / 2 : jSize.y() / 2;
distance -= Math.abs(r1) + Math.abs(r2);
distVec.normalize();
distVec.scale(distance);
return distVec;
}
private void setLocation(ClusterElement v, double xPos, double yPos,
float w, float h) {
if (xPos > w || xPos < 0 || yPos > h || yPos < 0)
System.out.println(v.getID() + ": " + xPos + "/" + yPos);
v.setLocation((float) (xPos - v.getSize().x() / 2), (float) (yPos - v
.getSize().y() / 2));
v.repaintPick();
}
private void initialLayout(List<? extends IGLLayoutElement> children,
float w, float h) {
int rowCount = ((int) (Math.sqrt(children.size())) + 1);
int i = 0;
for (GLElement child : asList()) {
Vec2d pos = new Vec2d(i / rowCount * 250 + 200,
(i % rowCount) * 180 + 100);
setLocation((ClusterElement) child, pos.x(), pos.y(), w, h);
i++;
}
}
/**
* @return the fixLayout, see {@link #fixLayout}
*/
public boolean isLayoutFixed() {
return dragedElement == null;
}
/**
* @param fixLayout
* setter, see {@link fixLayout}
*/
public void setDragedLayoutElement(ClusterElement element) {
this.dragedElement = element;
}
public void setHooveredElement(ClusterElement hooveredElement) {
this.hoveredElement = hooveredElement;
}
GlobalToolBarElement toolbar;
public void setToolbar(GlobalToolBarElement globalToolBar) {
this.toolbar = globalToolBar;
}
} |
package cc.nsg.bukkit.syncnbt;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
/**
* Handlers players for ProtocolLib (mode 2)
*/
public class PlayerTicker {
private String name = null;
private int ticker_thread_id = -1;
private SyncNBT plugin = null;
public PlayerTicker(SyncNBT plugin, String name) {
setName(name);
setPlugin(plugin);
}
// We found a new player to track
public void startPlayerTicker() {
getPlugin().getLogger().info("A new player called "+ name +" found, register player tracking.");
String json = plugin.db.getJSONData(name);
if (json != null) {
getPlugin().getLogger().info("Found data in database for player " + name + ", restoring data.");
new JSONSerializer().restorePlayer(json);
}
ticker_thread_id = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
Player p = Bukkit.getServer().getPlayer(name);
if (p == null) {
stopPlayerTicker();
} else {
String json = new JSONSerializer().toJSON(name);
plugin.db.saveJSONData(name, json);
}
}
}, 1200L, 1200L);
}
// The player is gone
public void stopPlayerTicker(Boolean save) {
if (save) {
String json = new JSONSerializer().toJSON(name);
plugin.db.saveJSONData(name, json);
}
getPlugin().getLogger().info("Player "+ name +" not found, unregister player tracking.");
Bukkit.getScheduler().cancelTask(ticker_thread_id);
}
public void stopPlayerTicker() {
stopPlayerTicker(false);
}
public String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
private void setPlugin(SyncNBT plugin) {
this.plugin = plugin;
}
private SyncNBT getPlugin() {
return plugin;
}
} |
package ch.eitchnet.utils.helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import ch.eitchnet.utils.exceptions.XmlException;
/**
* Helper class for performing XML based tasks
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class XmlHelper {
/**
* PROP_LINE_SEPARATOR = "line.separator" : the system property to fetch defined line separator
*/
public static final String PROP_LINE_SEPARATOR = "line.separator";
/**
* UNIX_LINE_SEP = "\n" : mostly we want this line separator, instead of the windows version
*/
public static final String UNIX_LINE_SEP = "\n";
/**
* DEFAULT_ENCODING = "UTF-8" : defines the default UTF-8 encoding expected of XML files
*/
public static final String DEFAULT_ENCODING = "UTF-8";
private static final Logger logger = LoggerFactory.getLogger(XmlHelper.class);
/**
* Parses an XML file on the file system and returns the resulting {@link Document} object
*
* @param xmlFile
* the {@link File} which has the path to the XML file to read
*/
public static void parseDocument(File xmlFile, DefaultHandler xmlHandler) {
try {
XmlHelper.logger.info("Parsing XML document " + xmlFile.getAbsolutePath());
parseDocument(new FileInputStream(xmlFile), xmlHandler);
} catch (FileNotFoundException e) {
throw new XmlException("The XML file could not be read: " + xmlFile.getAbsolutePath(), e);
}
}
/**
* Parses an XML file on the file system and returns the resulting {@link Document} object
*
* @param xmlFileInputStream
* the XML {@link InputStream} which is to be parsed
*/
public static void parseDocument(InputStream xmlFileInputStream, DefaultHandler xmlHandler) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(xmlFileInputStream, xmlHandler);
} catch (ParserConfigurationException e) {
throw new XmlException("Failed to initialize a SAX Parser: " + e.getMessage(), e);
} catch (SAXException e) {
throw new XmlException("The XML stream is not parseable: " + e.getMessage(), e);
} catch (IOException e) {
throw new XmlException("The XML stream not be read: " + e.getMessage(), e);
}
}
/**
* Writes a {@link Document} to an XML file on the file system
*
* @param document
* the {@link Document} to write to the file system
* @param file
* the {@link File} describing the path on the file system where the XML file should be written to
*
* @throws RuntimeException
* if something went wrong while creating the XML configuration, or writing the element
*/
public static void writeDocument(Document document, File file) throws RuntimeException {
XmlHelper.logger.info("Exporting document element " + document.getNodeName() + " to " + file.getAbsolutePath());
String lineSep = System.getProperty(PROP_LINE_SEPARATOR);
try {
String encoding = document.getInputEncoding();
if (encoding == null || encoding.isEmpty()) {
XmlHelper.logger.info("No encoding passed. Using default encoding " + XmlHelper.DEFAULT_ENCODING);
encoding = XmlHelper.DEFAULT_ENCODING;
}
if (!lineSep.equals("\n")) {
XmlHelper.logger.info("Overriding line separator to \\n");
System.setProperty(PROP_LINE_SEPARATOR, UNIX_LINE_SEP);
}
// Set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer transformer = transfac.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
// Transform to file
StreamResult result = new StreamResult(file);
Source xmlSource = new DOMSource(document);
transformer.transform(xmlSource, result);
} catch (Exception e) {
throw new XmlException("Exception while exporting to file: " + e, e);
} finally {
System.setProperty(PROP_LINE_SEPARATOR, lineSep);
}
}
/**
* Writes an {@link Element} to an XML file on the file system
*
* @param rootElement
* the {@link Element} to write to the file system
* @param file
* the {@link File} describing the path on the file system where the XML file should be written to
* @param encoding
* encoding to use to write the file
*
* @throws RuntimeException
* if something went wrong while creating the XML configuration, or writing the element
*/
public static void writeElement(Element rootElement, File file, String encoding) throws RuntimeException {
Document document = createDocument();
document.appendChild(rootElement);
XmlHelper.writeDocument(document, file);
}
/**
* Returns a new document instance
*
* @return a new document instance
*
* @throws RuntimeException
* if something went wrong while creating the XML configuration
*/
public static Document createDocument() throws RuntimeException {
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document document = docBuilder.newDocument();
return document;
} catch (DOMException e) {
throw new XmlException("Failed to create Document: " + e.getLocalizedMessage(), e);
} catch (ParserConfigurationException e) {
throw new XmlException("Failed to create Document: " + e.getLocalizedMessage(), e);
}
}
} |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check if any chromosomes that have different lengths in karyotype &
* seq_region tables.
*/
public class Karyotype extends SingleDatabaseTestCase {
/**
* Create a new Karyotype test case.
*/
public Karyotype() {
addToGroup("post_genebuild");
addToGroup("release");
setDescription("Check that karyotype and seq_region tables agree");
}
/**
* This only applies to core and Vega databases.
*/
public void types() {
removeAppliesToType(DatabaseType.EST);
}
/**
* Run the test.
*
* @param dbre
* The database to use.
* @return true if the test pased.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// This test should fail if the karyotype table is empty
if (!tableHasRows(con, "karyotype")) {
// certain species are allowed to have empty karyotype tables
Species species = dbre.getSpecies();
if (species == Species.CAENORHABDITIS_BRIGGSAE || species == Species.CAENORHABDITIS_ELEGANS || species == Species.DANIO_RERIO || species == Species.FUGU_RUBRIPES || species == Species.XENOPUS_TROPICALIS || species == Species.APIS_MELLIFERA) {
ReportManager.correct(this, con, "Karyotype table is empty, but this is allowed for " + species.toString());
return true;
} else { // if it's not one of those species, it's a problem
ReportManager.problem(this, con, "Karyotype table is empty");
return false;
}
}
// The seq_region.length and karyotype.length should always be the
// same.
// The SQL returns failures
String karsql = "SELECT sr.name, max(kar.seq_region_end), sr.length " + "FROM seq_region sr, karyotype kar "
+ "WHERE sr.seq_region_id=kar.seq_region_id " + "GROUP BY kar.seq_region_id "
+ "HAVING sr.length <> MAX(kar.seq_region_end)";
int count = 0;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(karsql);
if (rs != null) {
while (rs.next() && count < 50) {
count++;
String chrName = rs.getString(1);
int karLen = rs.getInt(2);
int chrLen = rs.getInt(3);
String prob = "";
int bp = 0;
if (karLen > chrLen) {
bp = karLen - chrLen;
prob = "longer";
} else {
bp = chrLen - karLen;
prob = "shorter";
}
result = false;
ReportManager.problem(this, con, "Chromosome " + chrName + " is " + bp + "bp " + prob + " in the karyotype table than " + "in the seq_region table");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
if (count == 0) {
ReportManager.correct(this, con, "Chromosome lengths are the same" + " in karyotype and seq_region tables");
}
return result;
} // run
} // Karyotype |
package ch.sportchef.business;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public enum ImageResizer {
;
public static BufferedImage resizeAndCrop(final BufferedImage inputImage,
final int outputWidth, final int outputHeight) {
final double outputAspectRatio = outputWidth / (double) outputHeight;
final int inputWidth = inputImage.getWidth();
final int inputHeight = inputImage.getHeight();
final BufferedImage outputImage;
if (inputWidth == outputWidth && inputHeight == outputHeight) {
outputImage = inputImage;
} else {
final BufferedImage resizedImage;
if (inputWidth != outputWidth && inputHeight != outputHeight) {
final double inputAspectRatio = inputWidth / (double) inputHeight;
final int scaleWidth;
int scaleHeight;
if (outputAspectRatio < inputAspectRatio) {
scaleWidth = outputWidth;
scaleHeight = inputHeight * outputWidth / inputWidth;
} else {
scaleWidth = inputWidth * outputHeight / inputHeight;
scaleHeight = outputHeight;
}
resizedImage = resize(inputImage, scaleWidth, scaleHeight);
} else {
resizedImage = inputImage;
}
outputImage = crop(resizedImage, outputWidth, outputHeight);
}
return outputImage;
}
public static BufferedImage resize(final BufferedImage inputImage,
final int outputWidth, final int outputHeight) {
final BufferedImage outputImage = new BufferedImage(outputWidth, outputHeight, inputImage.getType());
final Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, outputWidth, outputHeight, null);
g2d.dispose();
return outputImage;
}
public static BufferedImage crop(final BufferedImage inputImage,
final int outputWidth, final int outputHeight) {
final int inputWidth = inputImage.getWidth();
final int inputHeight = inputImage.getHeight();
final int startX = inputWidth > outputWidth ? (inputWidth - outputWidth) / 2 : 0;
final int startY = inputHeight > outputHeight ? (inputHeight - outputHeight) / 2 : 0;
return crop(inputImage, startX, startY, outputWidth, outputHeight);
}
public static BufferedImage crop(final BufferedImage inputImage,
final int startX, final int startY,
final int outputWidth, final int outputHeight) {
return inputImage.getSubimage(startX, startY, outputWidth, outputHeight);
}
} |
package org.exist.validation.internal;
import java.io.IOException;
import java.io.OutputStream;
/**
* <code>BlockingOutputStream</code> is a combination of an output stream and
* an input stream, connected through a (circular) buffer in memory.
* It is intended for coupling producer threads to consumer threads via a
* (byte) stream.
* When the buffer is full producer threads will be blocked until the buffer
* has some free space again. When the buffer is empty the consumer threads will
* be blocked until some bytes are available again.
*
*/
public class BlockingOutputStream extends OutputStream {
private final static int EOS = -1;
private static final int CAPACITY = 8192;
private static final int SIZE = CAPACITY + 1;
private byte[] buffer = new byte[SIZE]; // Circular queue.
private int head; // First full buffer position.
private int tail; // First empty buffer position.
private boolean closed;
/* InputStream methods */
/**
* Reads the next byte of data from the input stream. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @throws IOException if an I/O error occurs.
*/
public synchronized int read() throws IOException {
byte bb[] = new byte[1];
return (read(bb, 0, 1) == EOS) ? EOS : bb[0];
}
/**
* Reads up to <code>len</code> bytes of data from the input stream into
* an array of bytes. An attempt is made to read as many as
* <code>len</code> bytes, but a smaller number may be read.
* The number of bytes actually read is returned as an integer.
*
* <p> This method blocks until input data is available, end of file is
* detected, or an exception is thrown.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @throws IOException if an I/O error occurs.
* @throws NullPointerException if <code>b</code> is <code>null</code>.
*/
public synchronized int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int count = EOS;
try {
while (empty() && !closed) wait();
if (!closed) {
count = Math.min(len, available());
int count1 = Math.min(count, availablePart1());
System.arraycopy(buffer, head, b, off, count1);
int count2 = count - count1;
if (count2 > 0) {
System.arraycopy(buffer, 0, b, off + count1, count2);
}
head = next(head, count);
if (empty()) head = tail = 0; // Reset to optimal situation.
notifyAll();
}
} catch (InterruptedException e) {
//throw new DaMaIOException("Read operation interrupted.", e);
throw new IOException("Read operation interrupted."+ e);
}
return count;
}
/**
* Closes this input stream and releases any system resources associated
* with the stream.
*
* @throws IOException if an I/O error occurs.
*/
public synchronized void close() throws IOException {
closed = true;
notifyAll();
}
/**
* The number of bytes that can be read (or skipped over) from
* this input stream without blocking by the next caller of a method for
* this input stream.
*
* @return the number of bytes that can be read from this input stream
* without blocking.
* @throws IOException if an I/O error occurs.
*/
public synchronized int available() {
return (tail - head + SIZE) % SIZE;
}
private int availablePart1() {
return (tail >= head) ? tail - head : SIZE - head;
}
private int availablePart2() {
return (tail >= head) ? 0 : tail;
}
/* OutputStream methods */
/**
* Writes the specified byte to this output stream. The general
* contract for <code>write</code> is that one byte is written
* to the output stream. The byte to be written is the eight
* low-order bits of the argument <code>b</code>. The 24
* high-order bits of <code>b</code> are ignored.
*
* @param b the <code>byte</code>.
* @throws IOException if an I/O error occurs. In particular,
* an <code>IOException</code> may be thrown if the
* output stream has been closed.
*/
public synchronized void write(int b) throws IOException {
byte bb[] = { (byte) b };
write(bb, 0, 1);
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this output stream.
* The general contract for <code>write(b, off, len)</code> is that
* some of the bytes in the array <code>b</code> are written to the
* output stream in order; element <code>b[off]</code> is the first
* byte written and <code>b[off+len-1]</code> is the last byte written
* by this operation.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @throws IOException if an I/O error occurs. In particular,
* an <code>IOException</code> is thrown if the output
* stream is closed.
*/
public synchronized void write(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
while (len > 0) {
int count;
try {
while (full() && !closed) wait();
if (closed) throw new IOException("Writing to closed stream");
count = Math.min(len, free());
int count1 = Math.min(count, freePart1());
System.arraycopy(b, off, buffer, tail, count1);
int count2 = count - count1;
if (count2 > 0) {
System.arraycopy(b, off + count1, buffer, 0, count2);
}
tail = next(tail, count);
notifyAll();
} catch (InterruptedException e) {
throw new IOException("Write operation interrupted."+ e);
}
off += count;
len -= count;
}
}
/**
* Equivalent of the <code>close()</code> method of an output stream.
* Renamed to solve the name clash with the <code>close()</code> method
* of the input stream also implemented by this class.
* Closes this output stream and releases any system resources
* associated with this stream. A closed stream cannot perform
* output operations and cannot be reopened.
* <p>
* This method blocks its caller until all bytes remaining in the buffer
* are read from the buffer by the receiving threads or an exception occurs.
*
* @throws IOException if an I/O error occurs.
*/
public synchronized void closeOutputStream() throws IOException {
try {
while(!empty() && !closed) wait();
if (!empty()) throw new IOException("Closing non empty stream.");
closed = true;
notifyAll();
} catch (InterruptedException e) {
throw new IOException(
"Close OutputStream operation interrupted."+ e);
}
}
/**
* Flushes this output stream and forces any buffered output bytes
* to be written out.
* <p>
* This methods blocks its caller until all buffered bytes are actually
* read by the consuming threads.
*
* @throws IOException if an I/O error occurs.
*/
public synchronized void flush() throws IOException {
try {
while(!empty() && !closed) wait();
if (!empty()) throw new IOException(
"Flushing non empty closed stream.");
notifyAll();
} catch (InterruptedException e) {
throw new IOException("Flush operation interrupted."+ e);
}
}
/**
* The number of bytes that can be written to
* this output stream without blocking by the next caller of a method for
* this output stream.
*
* @return the number of bytes that can be written to this output stream
* without blocking.
* @throws IOException if an I/O error occurs.
*/
public synchronized int free() {
int prevhead = prev(head);
return (prevhead - tail + SIZE) % SIZE;
}
private int freePart1() {
int prevhead = prev(head);
return (prevhead >= tail) ? prevhead - tail : SIZE - tail;
}
private int freePart2() {
int prevhead = prev(head);
return (prevhead >= tail) ? 0 : prevhead;
}
/* Buffer management methods */
private boolean empty() {
return head == tail;
}
private boolean full() {
return next(tail) == head;
}
private static int next(int pos) {
return next(pos, 1);
}
private static int next(int pos, int incr) {
return (pos + incr) % SIZE;
}
private static int prev(int pos) {
return prev(pos, 1);
}
private static int prev(int pos, int decr) {
return (pos - decr + SIZE) % SIZE;
}
} |
package co.com.codesoftware.beans;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;
import co.com.codesoftware.entity.PuntoMenuEntity;
import co.com.codesoftware.servicio.usuario.UsuarioEntity;
@ManagedBean
@ViewScoped
public class MenuBean implements Serializable {
private static final long serialVersionUID = 1L;
private String listaPermisos = ".InPr13.";
private ArrayList<PuntoMenuEntity> menu;
private MenuModel menuDinamico;
private UsuarioEntity objetoSesion;
@PostConstruct
public void init() {
this.objetoSesion = (UsuarioEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("dataSession");
this.listaPermisos = this.objetoSesion.getPerfil().getPermisos();
this.creaMenu();
}
/**
* Funcion con la cual creo el menu principal de la aplicacion
*/
public void creaMenu() {
if (menuDinamico == null) {
this.menuDinamico = new DefaultMenuModel();
}
DefaultMenuItem tercerPunto = new DefaultMenuItem("Cerrar Sesion");
tercerPunto.setIcon("fa fa-close");
tercerPunto.setCommand("#{loginBean.cerrarSesion}");
// Cuarto punto de menu
// DefaultSubMenu tercerPunto = new DefaultSubMenu();
DefaultMenuItem cuartoPunto = new DefaultMenuItem("SIGEMCO");
cuartoPunto.setCommand("#{loginBean.cambioSigemco}");
this.menuDinamico.addElement(this.generaMenuAdmon());
this.menuDinamico.addElement(this.generaMenuProd());
this.menuDinamico.addElement(this.generaMenuParametros());
this.menuDinamico.addElement(this.generaMenuReportes());
this.menuDinamico.addElement(this.generaMenuFacturacion());
this.menuDinamico.addElement(this.generaMenuImportaciones());
this.menuDinamico.addElement(this.generaMenuContabilidad());
this.menuDinamico.addElement(tercerPunto);
this.menuDinamico.addElement(cuartoPunto);
}
public DefaultSubMenu generaMenuParametros() {
DefaultSubMenu segundoPunto = new DefaultSubMenu();
try {
// REPORTES
if (this.listaPermisos.contains(".Per1.") || this.listaPermisos.contains(".Per2.")) {
segundoPunto.setLabel("PARAMETROS");
segundoPunto.setIcon("fa fa-archive");
if (this.listaPermisos.contains(".Per3.")) {
DefaultSubMenu segPunNivUno = new DefaultSubMenu();
segPunNivUno.setLabel("Categoria");
DefaultMenuItem segPunNvUnoAsoc = new DefaultMenuItem("Asociar Cat y Sub Cat");
segPunNvUnoAsoc.setCommand("/ACTION/SUBCATEGORIA/asocCatSubCat.jsf");
segundoPunto.addElement(segPunNivUno);
segPunNivUno.addElement(segPunNvUnoAsoc);
}
if (this.listaPermisos.contains(".Per4.")) {
DefaultSubMenu segPunNivDos = new DefaultSubMenu();
segPunNivDos.setLabel("Precio Masivo");
DefaultMenuItem segPunNvDosPrecMasiv = new DefaultMenuItem("Consulta Porcentajes");
segPunNvDosPrecMasiv.setCommand("/ACTION/PRECIOS/ConsPorcPrecioMasivo.jsf");
DefaultMenuItem segPunNvDosPrecMasivIns = new DefaultMenuItem("Insercion Parametros");
segPunNvDosPrecMasivIns.setCommand("/ACTION/PRECIOS/InsercionParametrosPrecio.jsf");
DefaultMenuItem segPunNvDosPrecMasivEje = new DefaultMenuItem("Ejecucion");
segPunNvDosPrecMasivEje.setCommand("/ACTION/PRECIOS/EjecuionParaPrecioMasivo.jsf");
segundoPunto.addElement(segPunNivDos);
segPunNivDos.addElement(segPunNvDosPrecMasiv);
segPunNivDos.addElement(segPunNvDosPrecMasivIns);
segPunNivDos.addElement(segPunNvDosPrecMasivEje);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return segundoPunto;
}
/**
* Funcion con la cual genero el menu de reportes
*
* @return
*/
public DefaultSubMenu generaMenuReportes() {
DefaultSubMenu menuPrincipal = new DefaultSubMenu();
try {
// REPORTES
if (this.listaPermisos.contains(".Per3.") || this.listaPermisos.contains(".Per4.")) {
menuPrincipal.setLabel("REPORTES");
menuPrincipal.setIcon("fa fa-file-excel-o");
if (this.listaPermisos.contains(".Per3.")) {
DefaultMenuItem basico = new DefaultMenuItem("Basico");
basico.setCommand("/ACTION/REPORTES/reportes.jsf");
menuPrincipal.addElement(basico);
}
if (this.listaPermisos.contains(".Per4.")) {
DefaultMenuItem comVentas = new DefaultMenuItem("Compras y Ventas");
comVentas.setCommand("/ACTION/REPORTES/comprasVentas.xhtml");
menuPrincipal.addElement(comVentas);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return menuPrincipal;
}
public DefaultSubMenu generaMenuProd() {
DefaultSubMenu menuPrincipal = new DefaultSubMenu();
try {
if (this.listaPermisos.contains(".Inv1.") || this.listaPermisos.contains(".Inv2.")
|| this.listaPermisos.contains(".Inv3.") || this.listaPermisos.contains(".Inv5.")
|| this.listaPermisos.contains(".Inv5.") || this.listaPermisos.contains(".Inv6.")
|| this.listaPermisos.contains(".Inv7.") || this.listaPermisos.contains(".Inv8.")
|| this.listaPermisos.contains(".Inv9.") || this.listaPermisos.contains(".Inv10.")
|| this.listaPermisos.contains(".Inv11")) {
menuPrincipal.setLabel("INVENTARIOS");
menuPrincipal.setIcon("fa fa-bank");
if (this.listaPermisos.contains(".Inv1.") || this.listaPermisos.contains(".Inv3.") || this.listaPermisos.contains(".Inv2.")){
DefaultSubMenu compras = new DefaultSubMenu();
compras.setLabel("Compras");
menuPrincipal.addElement(compras);
if (this.listaPermisos.contains(".Inv1.")) {
DefaultMenuItem tercerNivel = new DefaultMenuItem("Registro Tem");
tercerNivel.setCommand("/ACTION/FACTURACION/facturaCompraTmp.jsf?faces-redirect=false");
compras.addElement(tercerNivel);
}
if (this.listaPermisos.contains(".Inv3.")) {
DefaultMenuItem tercerNivelFacturaCompraTmp = new DefaultMenuItem("Consulta Temporales");
tercerNivelFacturaCompraTmp
.setCommand("/ACTION/FACTURACION/consultaFacCompraTmp.jsf?faces-redirect=false");
compras.addElement(tercerNivelFacturaCompraTmp);
}
if (this.listaPermisos.contains(".Inv2.")) {
DefaultMenuItem tercerNivelFacturaCompra = new DefaultMenuItem("Consulta");
tercerNivelFacturaCompra
.setCommand("/ACTION/PRODUCTOS/consultaFacturaCompras.jsf?faces-redirect=false");
compras.addElement(tercerNivelFacturaCompra);
}
}
if ( this.listaPermisos.contains(".Inv5.")
|| this.listaPermisos.contains(".Adm5.") || this.listaPermisos.contains(".Inv6.")
|| this.listaPermisos.contains(".Inv7.")) {
// Segundo Nivel
DefaultSubMenu productos = new DefaultSubMenu();
productos.setLabel("Productos ");
menuPrincipal.addElement(productos);
if (this.listaPermisos.contains(".Inv4.")) {
DefaultMenuItem tercerNivelPrueba = new DefaultMenuItem("Insertar Productos");
tercerNivelPrueba.setCommand("/ACTION/PRODUCTOS/insertaProductos.jsf?faces-redirect=false");
productos.addElement(tercerNivelPrueba);
}
if (this.listaPermisos.contains(".Inv5.")) {
DefaultMenuItem tercerNivelPrecio = new DefaultMenuItem("Parametrizacion de precio");
tercerNivelPrecio.setCommand("/ACTION/PRODUCTOS/precioProductos.jsf?faces-redirect=false");
productos.addElement(tercerNivelPrecio);
}
if (this.listaPermisos.contains(".Inv6.")) {
DefaultMenuItem tercerNivelConsGeneral = new DefaultMenuItem("Consulta General");
tercerNivelConsGeneral
.setCommand("/ACTION/PRODUCTOS/consGeneralProductos.jsf?faces-redirect=false");
productos.addElement(tercerNivelConsGeneral);
}
if (this.listaPermisos.contains(".Inv11.")) {
DefaultMenuItem tercerNivelConsGeneral2 = new DefaultMenuItem("Consulta Prod X Sede");
tercerNivelConsGeneral2
.setCommand("/ACTION/PRODUCTOS/consultaProductosXsede.jsf?faces-redirect=false");
productos.addElement(tercerNivelConsGeneral2);
}
if (this.listaPermisos.contains(".Inv7.")) {
DefaultMenuItem tercerNivelSolicitudes = new DefaultMenuItem("Solicitudes");
tercerNivelSolicitudes
.setCommand("/ACTION/SOLICITUDES/consultaSolicitudes.jsf?faces-redirect=false");
productos.addElement(tercerNivelSolicitudes);
}
}
if (this.listaPermisos.contains(".Inv8.") || this.listaPermisos.contains(".Inv9.")) {
DefaultSubMenu cargues = new DefaultSubMenu();
cargues.setLabel("Cargues Masivos ");
menuPrincipal.addElement(cargues);
if (this.listaPermisos.contains(".Inv8.")) {
DefaultMenuItem cargueProductos = new DefaultMenuItem("Cargue Productos");
cargueProductos.setCommand("/ACTION/PRODUCTOS/cargueProductos.jsf?faces-redirect=false");
cargues.addElement(cargueProductos);
}
if (this.listaPermisos.contains(".Inv9.")) {
DefaultMenuItem cargueProd = new DefaultMenuItem("Solo Prod");
cargueProd.setCommand("/ACTION/PRODUCTOS/cargueSoloProducto.jsf?faces-redirect=false");
cargues.addElement(cargueProd);
}
}
if (this.listaPermisos.contains(".Inv10.")) {
DefaultSubMenu aportesSoci = new DefaultSubMenu();
aportesSoci.setLabel("Aporte Socio");
menuPrincipal.addElement(aportesSoci);
if (this.listaPermisos.contains(".Inv10.")) {
DefaultMenuItem cargarAparte = new DefaultMenuItem("Aportes");
cargarAparte.setCommand("/ACTION/PRODUCTOS/aporteSocio.jsf?faces-redirect=false");
aportesSoci.addElement(cargarAparte);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return menuPrincipal;
}
/**
* Funcion con la cual genero el menu de administracion, con todos sus hijos
*
* @return
*/
public DefaultSubMenu generaMenuAdmon() {
DefaultSubMenu menuPrincipal = new DefaultSubMenu();
try {
if (this.listaPermisos.contains(".Adm1.") || this.listaPermisos.contains(".Adm2.")
|| this.listaPermisos.contains(".Adm3.") || this.listaPermisos.contains(".Adm4.")
|| this.listaPermisos.contains(".Adm5.") || this.listaPermisos.contains(".Adm6.")
|| this.listaPermisos.contains(".Adm7.") || this.listaPermisos.contains(".Adm8.")
|| this.listaPermisos.contains(".Adm9.") || this.listaPermisos.contains(".Adm10.")) {
menuPrincipal.setLabel("ADMINISTRACION");
menuPrincipal.setIcon("fa fa-users");
// Se generan los submenus de segundo nivel
// Genero el segundo nivel del menu
if (this.listaPermisos.contains(".Adm1.")) {
DefaultMenuItem segundoNivel = new DefaultMenuItem("Resolución Fact.");
segundoNivel.setCommand("/ACTION/ADMIN/resolucionFacturacion.jsf");
menuPrincipal.addElement(segundoNivel);
}
if (this.listaPermisos.contains(".Adm2.")) {
// Genero sedes
DefaultMenuItem segundoNivelUno = new DefaultMenuItem("Sedes.");
segundoNivelUno.setCommand("/ACTION/ADMIN/sedes.jsf");
menuPrincipal.addElement(segundoNivelUno);
}
if (this.listaPermisos.contains(".Adm3.")) {
// Genero conteos
DefaultMenuItem segundoNivelDos = new DefaultMenuItem("Conteo.");
segundoNivelDos.setCommand("/ACTION/ADMIN/conteos.jsf");
menuPrincipal.addElement(segundoNivelDos);
}
if (this.listaPermisos.contains(".Adm4.")) {
// Punto de menu para parametros
DefaultMenuItem segundoNivelTres = new DefaultMenuItem("Parametros.");
segundoNivelTres.setCommand("/ACTION/ADMIN/parametrosGenerales.jsf");
menuPrincipal.addElement(segundoNivelTres);
}
if (this.listaPermisos.contains(".Adm5.")) {
// Punto de menu para usuarios
DefaultMenuItem segundoNivelCuatro = new DefaultMenuItem("Usuarios.");
segundoNivelCuatro.setCommand("/ACTION/ADMIN/usuarios.jsf");
menuPrincipal.addElement(segundoNivelCuatro);
}
if (this.listaPermisos.contains(".Adm6.")) {
DefaultMenuItem segundoNivelCinco = new DefaultMenuItem("Proveedores.");
segundoNivelCinco.setCommand("/ACTION/ADMIN/proveedores.jsf");
menuPrincipal.addElement(segundoNivelCinco);
}
if (this.listaPermisos.contains(".Adm7.")) {
DefaultMenuItem segundoNivelSeis = new DefaultMenuItem("Clientes.");
segundoNivelSeis.setCommand("/ACTION/ADMIN/clientes.jsf");
menuPrincipal.addElement(segundoNivelSeis);
}
if (this.listaPermisos.contains(".Adm8.")) {
DefaultMenuItem segundoNivelSiete = new DefaultMenuItem("Perfiles.");
segundoNivelSiete.setCommand("/ACTION/ADMIN/perfiles.jsf");
menuPrincipal.addElement(segundoNivelSiete);
}
if (this.listaPermisos.contains(".Adm9.")) {
DefaultMenuItem segundoNivelOcho = new DefaultMenuItem("Socios.");
segundoNivelOcho.setCommand("/ACTION/ADMIN/socios.jsf");
menuPrincipal.addElement(segundoNivelOcho);
}
if (this.listaPermisos.contains(".Adm10.")) {
DefaultMenuItem segundoNivelOcho = new DefaultMenuItem("Param Productos.");
segundoNivelOcho.setCommand("/ACTION/ADMIN/productosParam.jsf");
menuPrincipal.addElement(segundoNivelOcho);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return menuPrincipal;
}
/**
* Funcion con la cual genero el menu de facturacion, con todos sus hijos
*
* @return
*/
public DefaultSubMenu generaMenuFacturacion() {
DefaultSubMenu menuPrincipal = new DefaultSubMenu();
try {
if (this.listaPermisos.contains(".Fact1.") || this.listaPermisos.contains(".Fact2.")
|| this.listaPermisos.contains(".Fact3.") || this.listaPermisos.contains(".Fact4.")|| this.listaPermisos.contains(".Fact5.")) {
menuPrincipal.setLabel("FACTURACION");
menuPrincipal.setIcon("fa fa-files-o");
if (this.listaPermisos.contains(".Fact1.") || this.listaPermisos.contains(".Fact2.")) {
DefaultSubMenu item = new DefaultSubMenu("Notas");
if (this.listaPermisos.contains(".Fact1.")) {
DefaultMenuItem subItem = new DefaultMenuItem("Credito");
subItem.setCommand("/ACTION/FACTURACION/notaCredito.jsf");
item.addElement(subItem);
}
if (this.listaPermisos.contains(".Fact2.")) {
DefaultMenuItem subItem = new DefaultMenuItem("Debito");
item.addElement(subItem);
}
menuPrincipal.addElement(item);
}
if (this.listaPermisos.contains(".Fact3.") || this.listaPermisos.contains(".Fact4.")) {
DefaultSubMenu segundoNivelDos = new DefaultSubMenu("Remisiones");
if (this.listaPermisos.contains(".Fact3.")) {
DefaultMenuItem consultaRemi = new DefaultMenuItem("Consulta Remisiones");
consultaRemi.setCommand("/ACTION/FACTURACION/remisionFacturacion.jsf");
segundoNivelDos.addElement(consultaRemi);
}
if (this.listaPermisos.contains(".Fact4.")) {
DefaultMenuItem consultaPagos = new DefaultMenuItem("Registro Pagos");
consultaPagos.setCommand("/ACTION/FACTURACION/pagosRemision.jsf");
segundoNivelDos.addElement(consultaPagos);
}
menuPrincipal.addElement(segundoNivelDos);
}
if (this.listaPermisos.contains(".Fact5.")) {
DefaultMenuItem segundoNivel = new DefaultMenuItem("Consulta Facturas");
segundoNivel.setCommand("/ACTION/FACTURACION/consultaFacturas.jsf");
DefaultSubMenu segundoNivelDos = new DefaultSubMenu("Remisiones");
menuPrincipal.addElement(segundoNivel);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return menuPrincipal;
}
/**
* Menu en el cual se generan las importaciones
*
* @return
*/
public DefaultSubMenu generaMenuImportaciones() {
DefaultSubMenu menuPrincipal = new DefaultSubMenu();
try {
menuPrincipal.setLabel("IMPORTACIONES");
menuPrincipal.setIcon("fa fa-briefcase");
// Se generan los submenus de segundo nivel
// Genero el segundo nivel del menu
DefaultMenuItem segundoNivel = new DefaultMenuItem("Info Principal");
DefaultMenuItem segundoNivelConsulta = new DefaultMenuItem("Consulta Gral");
segundoNivel.setCommand("/ACTION/IMPORTACION/adminImportacion.jsf");
segundoNivelConsulta.setCommand("/ACTION/IMPORTACION/consultaImportacion.jsf");
// Adiciono al punto de menu principal
menuPrincipal.addElement(segundoNivel);
menuPrincipal.addElement(segundoNivelConsulta);
} catch (Exception e) {
e.printStackTrace();
}
return menuPrincipal;
}
/**
* Menu en el cual se generan las importaciones
*
* @return
*/
public DefaultSubMenu generaMenuContabilidad() {
DefaultSubMenu menuPrincipal = new DefaultSubMenu();
try {
menuPrincipal.setLabel("CONTABILIDAD");
menuPrincipal.setIcon("fa fa-calculator");
// Se generan los submenus de segundo nivel
// Genero el segundo nivel del menu
DefaultSubMenu segundoNivel = new DefaultSubMenu("PUC");
DefaultMenuItem tercerNivelConsulta = new DefaultMenuItem("Consulta Gral");
// tercerNivelConsulta.setCommand("/ACTION/IMPORTACION/adminImportacion.jsf");
tercerNivelConsulta.setCommand("/ACTION/CONTABILIDAD/CONSULTAS/consultaClase.jsf");
DefaultSubMenu segundoNivelDos = new DefaultSubMenu("CONSULTA MV.");
DefaultMenuItem tercerNivelConsultaDos = new DefaultMenuItem("POR TIPO DOCUMENTO");
tercerNivelConsultaDos.setCommand("/ACTION/CONTABILIDAD/CONSULTAS/consultaMoviContable.jsf");
DefaultMenuItem tercerNivelConsultaTres= new DefaultMenuItem("POR CUENTA");
tercerNivelConsultaTres.setCommand("/ACTION/CONTABILIDAD/CONSULTAS/consultaCuentaTotal.jsf");
// Adiciono al punto de menu principal
menuPrincipal.addElement(segundoNivel);
segundoNivel.addElement(tercerNivelConsulta);
segundoNivelDos.addElement(tercerNivelConsultaDos);
segundoNivelDos.addElement(tercerNivelConsultaTres);
menuPrincipal.addElement(segundoNivelDos);
} catch (Exception e) {
e.printStackTrace();
}
return menuPrincipal;
}
public String getListaPermisos() {
return listaPermisos;
}
public void setListaPermisos(String listaPermisos) {
this.listaPermisos = listaPermisos;
}
public ArrayList<PuntoMenuEntity> getMenu() {
return menu;
}
public void setMenu(ArrayList<PuntoMenuEntity> menu) {
this.menu = menu;
}
public MenuModel getMenuDinamico() {
return menuDinamico;
}
public void setMenuDinamico(MenuModel menuDinamico) {
this.menuDinamico = menuDinamico;
}
public UsuarioEntity getObjetoSesion() {
return objetoSesion;
}
public void setObjetoSesion(UsuarioEntity objetoSesion) {
this.objetoSesion = objetoSesion;
}
} |
package org.foo_projects.sofar.Sedimentology;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Map;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.scheduler.BukkitScheduler;
import com.massivecraft.factions.entity.BoardColls;
import com.massivecraft.factions.entity.Faction;
import com.massivecraft.mcore.ps.PS;
import com.palmergames.bukkit.towny.Towny;
import com.palmergames.bukkit.towny.object.TownyUniverse;
import com.sk89q.worldguard.bukkit.WGBukkit;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.managers.RegionManager;
/*
* Sedimentology concepts
*
* Erosion & deposition go hand in hand - at higher elevation (>64) erosion dominates, and at
* lower elevations, sedimentation dominates.
*
* Decay cycles affect rocks - stone breaks into gravel, into sand, into clay. Each step takes longer
*
* Transports are wind, water, ice.
*
* Wind can displace sand - create dunes.
* Water displaces sand and clay
* Ice displaces all blocks
*
* Snow compacts into Ice
*
* Blocks do not disappear, the volume of blocks remains equal througout the process
*
* slope affects erosion - a higher slope means more erosion
*
* deposition happens where the slope reduces - a lower slope means more deposition
*
*/
public final class Sedimentology extends JavaPlugin {
private List<SedWorld> sedWorldList;
public Random rnd = new Random();
private long stat_considered;
private long stat_displaced;
private long stat_degraded;
private long stat_errors;
private long stat_protected;
private long stat_ignored_edge;
private long stat_ignored_type;
private long stat_ignored_storm;
private long stat_ignored_vegetation;
private long stat_ignored_resistance;
private long stat_ignored_water;
private long stat_ignored_wave;
private long stat_ignored_sand;
private long stat_ignored_hardness;
private long stat_ignored_lockedin;
private long stat_ignored_rate;
private int stat_lastx;
private int stat_lasty;
private int stat_lastz;
private long conf_blocks = 10;
private long conf_ticks = 1;
private boolean conf_protect = true;
private boolean conf_compensate = true;
private boolean have_factions = false;
private boolean have_towny = false;
private boolean have_worldguard = false;
private Object towny_universe = null;
private boolean enableWorld(String worldName)
{
getLogger().info("enabling world \"" + worldName + "\"");
if (org.bukkit.Bukkit.getWorld(worldName) == null) {
getLogger().info("No such world");
return false;
}
if (!sedWorldList.isEmpty()) {
for (SedWorld ww: sedWorldList) {
if (org.bukkit.Bukkit.getWorld(worldName).getName().equals(ww.world.getName())) {
getLogger().info("Already enabled for this world");
return false;
}
}
}
/* nether/end world environments are not supported */
if (org.bukkit.Bukkit.getWorld(worldName).getEnvironment() != Environment.NORMAL) {
getLogger().info("Invalid environment for this world");
return false;
}
List<String> worldStringList = getConfig().getStringList("worlds");
if (worldStringList.indexOf(worldName) == -1) {
worldStringList.add(worldName);
getConfig().set("worlds", worldStringList);
saveConfig();
}
World w = org.bukkit.Bukkit.getWorld(worldName);
SedWorld s = new SedWorld(w);
/* fill initial chunkmap here */
Chunk chunkList[] = w.getLoadedChunks();
for (Chunk c: chunkList)
s.load(c.getX(), c.getZ());
sedWorldList.add(s);
return true;
}
private boolean disableWorld(String worldName)
{
if (org.bukkit.Bukkit.getWorld(worldName) == null) {
getLogger().info("No such world");
return false;
}
for (SedWorld ww: sedWorldList) {
if (org.bukkit.Bukkit.getWorld(worldName).getName().equals(ww.world.getName())) {
List<String> worldStringList = getConfig().getStringList("worlds");
worldStringList.remove(worldName);
getConfig().set("worlds", worldStringList);
saveConfig();
sedWorldList.remove(ww);
return true;
}
}
getLogger().info("world not currently enabled");
return false;
}
private class offset {
public offset(int i, int j) {
x = i;
z = j;
}
public int x;
public int z;
}
private int walker_start;
private int walker_step;
private int walker_phase;
private offset walker[];
public offset walker_f(offset o) {
/*
* attempt to walk a grid as follows:
* a(4)-b(4)-c(4)-d(8)-e(4)
* edcde
* dbabd
* caOac
* dbabd
* edcde
*/
if (o.x == 0 && o.z == 0)
walker_step = 0;
switch (walker_step) {
case 0:
case 4:
case 8:
case 20:
walker_start = (int)Math.round(rnd.nextDouble() * 4.0);
walker_phase = 4;
break;
case 12:
walker_start = (int)Math.round(rnd.nextDouble() * 8.0);
walker_phase = 8;
break;
default:
break;
}
int section_start = walker_step - (walker_step % walker_phase);
int section_part = ((walker_step - section_start) + walker_start) % walker_phase;
walker_step++;
return walker[section_start + section_part];
}
private class SedDice {
private Random r;
public SedDice(Random random) {
this.r = random;
}
public boolean roll(double bet) {
return (r.nextDouble() > bet);
}
}
private class SedBlock {
private Block block;
public SedBlock(Block b) {
block = b;
}
/* arid envirnments where no precipitation happens */
public boolean inAridBiome() {
switch (block.getBiome()) {
case DESERT:
case DESERT_HILLS:
case DESERT_MOUNTAINS:
case MESA:
case MESA_BRYCE:
case MESA_PLATEAU:
case MESA_PLATEAU_FOREST:
case MESA_PLATEAU_FOREST_MOUNTAINS:
case MESA_PLATEAU_MOUNTAINS:
case SAVANNA:
case SAVANNA_MOUNTAINS:
case SAVANNA_PLATEAU:
case SAVANNA_PLATEAU_MOUNTAINS:
return true;
default:
return false;
}
}
/* environments where clay is naturally found */
public boolean inClayBiome() {
switch (block.getBiome()) {
case RIVER:
case OCEAN:
case DEEP_OCEAN:
case SWAMPLAND:
case FROZEN_RIVER:
case FROZEN_OCEAN:
return true;
default:
return false;
}
}
/* environments where sand is naturally found */
public boolean inSandBiome() {
switch (block.getBiome()) {
case OCEAN:
case BEACH:
case COLD_BEACH:
case STONE_BEACH:
case MUSHROOM_SHORE:
case DESERT:
case DESERT_HILLS:
case FROZEN_OCEAN:
case FROZEN_RIVER:
return true;
default:
return false;
}
}
public boolean isProtected() {
if (!conf_protect)
return false;
if (have_factions) {
Faction faction = BoardColls.get().getFactionAt(PS.valueOf(block.getLocation()));
if (!faction.isNone())
return true;
}
if (have_towny) {
if (((TownyUniverse)towny_universe).getTownBlock(block.getLocation()) != null)
return true;
}
if (have_worldguard) {
RegionManager rm = WGBukkit.getRegionManager(block.getWorld());
if (rm == null)
return false;
ApplicableRegionSet set = rm.getApplicableRegions(block.getLocation());
return (set.size() > 0);
}
return false;
}
public Material getType() {
return block.getType();
}
public void setType(Material material) {
block.setType(material);
}
@SuppressWarnings("deprecation")
public byte getData() {
return block.getData();
}
@SuppressWarnings("deprecation")
public void setData(byte data) {
block.setData(data);
}
public Biome getBiome() {
return block.getBiome();
}
}
private class SedWorld {
private Map<String, Integer> chunkMap;
private World world;
public SedWorld(World w) {
this.chunkMap = new HashMap<String, Integer>();
this.world = w;
}
public boolean isLoaded(int x, int z) {
String key = "(" + x + "," + z + ")";
if (chunkMap.get(key) == null)
return false;
return chunkMap.get(key) == 1;
}
public void load(int x, int z) {
String key = "(" + x + "," + z + ")";
chunkMap.put(key, 1);
}
public void unload(int x, int z) {
String key = "(" + x + "," + z + ")";
chunkMap.put(key, 0);
}
public void sedRandomBlock() {
Chunk ChunkList[] = world.getLoadedChunks();
Chunk c = ChunkList[(int) Math.abs(rnd.nextDouble() * ChunkList.length)];
int bx = (int)(Math.round(rnd.nextDouble() * 16));
int bz = (int)(Math.round(rnd.nextDouble() * 16));
/* don't bother touching chunks at the edges */
for (int xx = c.getX() - 1 ; xx <= c.getX() + 1; xx++) {
for (int zz = c.getZ() - 1 ; zz <= c.getZ() + 1; zz++) {
if (!this.isLoaded(xx, zz)) {
stat_ignored_edge++;
return;
}
}
}
int x = bx + (c.getX() * 16);
int z = bz + (c.getZ() * 16);
sedBlock(x, z);
}
public void sedBlock(int x, int z) {
World world = this.world;
SedDice dice = new SedDice(rnd);
int y;
double hardness;
double resistance;
double waterfactor;
double vegetationfactor;
double stormfactor;
boolean underwater = false;
boolean undermovingwater = false;
boolean targetunderwater = false;
boolean undersnow = false;
stat_considered++;
/* find highest block, even if underwater */
y = world.getHighestBlockYAt(x, z) - 1;
switch (world.getBlockAt(x, y, z).getType()) {
case WATER:
undermovingwater = true;
case STATIONARY_WATER:
underwater = true;
y = findDepositLocation(x, y, z) - 1;
break;
//FIXME: start handling ice from here
case SNOW:
case SNOW_BLOCK:
undersnow = true;
y = findDepositLocation(x, y, z) - 1;
break;
default:
break;
}
SedBlock b = new SedBlock(world.getBlockAt(x, y, z));
if (b.isProtected()) {
stat_protected++;
return;
}
/* filter out blocks we don't erode right now */
hardness = 1.0;
resistance = 1.0;
switch (b.getType()) {
case SOIL:
case DIRT:
case GRASS:
break;
case SAND: /* this covers red sand */
/*
* breaking sand into clay is hard, this also prevents all
* sand from turning into clay
*/
hardness = 0.01;
break;
case GRAVEL:
hardness = 0.15;
resistance = 0.75;
break;
case CLAY:
resistance = 0.3;
break;
case HARD_CLAY:
case STAINED_CLAY:
case SANDSTONE:
case MOSSY_COBBLESTONE:
case COBBLESTONE:
hardness = 0.05;
resistance = 0.05;
break;
case STONE:
hardness = 0.01;
resistance = 0.01;
break;
/* ores don't break down much at all, but they are displaced as easy stone */
case COAL_ORE:
case IRON_ORE:
case LAPIS_ORE:
case EMERALD_ORE:
case GOLD_ORE:
case DIAMOND_ORE:
case REDSTONE_ORE:
hardness = 0.0001;
resistance = 0.01;
break;
default:
stat_ignored_type++;
return;
}
/* lower overall chance due to lack of water */
stormfactor = 0.1;
if (world.hasStorm()) {
if (!b.inAridBiome())
stormfactor = 1.0;
}
if ((!underwater) && (dice.roll(stormfactor))) {
stat_ignored_storm++;
return;
}
// water increases displacement/degradation
waterfactor = 0.01; //this is probably too low
if (undermovingwater)
waterfactor = 1.0;
else if (underwater)
waterfactor = 0.5;
else {
waterloop:
for (int xx = x - 2; xx < x + 2; xx++) {
for (int zz = z - 2; zz < z + 2; zz++) {
for (int yy = y - 2; yy < y + 2; yy++) {
switch(world.getBlockAt(xx, yy, zz).getType()) {
case WATER:
waterfactor = 0.25;
break waterloop;
case STATIONARY_WATER:
waterfactor = 0.125;
break;
default:
break;
}
}
}
}
}
if (dice.roll(waterfactor)) {
stat_ignored_water++;
return;
}
/* a snow cover slows down things a bit */
if (undersnow) {
if (dice.roll(0.25)) {
stat_ignored_water++;
return;
}
}
/* slow down when deeper under the sealevel */
if (underwater) {
if (y < world.getSeaLevel()) {
/* exponentially slower with depth. 100% at 1 depth, 50% at 2, 25% at 3 etc... */
if (dice.roll(2.0 * Math.pow(0.5, world.getSeaLevel() - y))) {
stat_ignored_wave++;
return;
}
}
}
// vegetation slows down displacement
vegetationfactor = 1.0;
for (int xx = x - 3; xx < x + 3; xx++) {
for (int zz = z - 3; zz < z + 3; zz++) {
for (int yy = y - 3; yy < y + 3; yy++) {
switch(world.getBlockAt(xx, yy, zz).getType()) {
case LEAVES:
case CACTUS:
case SAPLING:
case LOG:
case LONG_GRASS:
case DEAD_BUSH:
case YELLOW_FLOWER:
case RED_ROSE:
case BROWN_MUSHROOM:
case RED_MUSHROOM:
case CROPS:
case MELON_STEM:
case PUMPKIN_STEM:
case MELON_BLOCK:
case PUMPKIN:
case VINE:
case SUGAR_CANE:
case DOUBLE_PLANT:
case LEAVES_2:
case LOG_2:
/* distance to vegetation: 3.0 (far) to 0.3 (near) */
double d = (Math.abs(xx - x) + Math.abs(yy - y) + Math.abs(zz -z)) / 3.0;
/* somewhat complex calculation here to make the chance
* proportional to the distance: 0.5 / (1.0 -> 3.7)
* Basically ends up being 0.5 (far) to 0.135 (near)
*/
double f = 0.5 / (4.0 - d);
if (f < vegetationfactor)
vegetationfactor = f;
break; //vegetationloop;
default:
break;
}
}
}
}
if (dice.roll(vegetationfactor)) {
stat_ignored_vegetation++;
return;
}
/* displace block? */
displace:
if (true) {
int step, steps;
/* our block must be able to move sideways, otherwise it could leave
* strange gaps. So check if all 4 sides horizontally are solid
*/
if (!(world.getBlockAt(x + 1, y, z).isEmpty() || world.getBlockAt(x + 1, y, z).isLiquid() ||
world.getBlockAt(x - 1, y, z).isEmpty() || world.getBlockAt(x - 1, y, z).isLiquid() ||
world.getBlockAt(x, y, z + 1).isEmpty() || world.getBlockAt(x, y, z + 1).isLiquid() ||
world.getBlockAt(x, y, z - 1).isEmpty() || world.getBlockAt(x, y, z - 1).isLiquid())) {
stat_ignored_lockedin++;
break displace;
}
/* find the most suitable target location to move this block to */
if ((b.getType() == Material.SAND) || (underwater))
steps = 24;
else
steps = 8;
int lowest = y;
offset lowestoffset = new offset(0, 0);
offset o = new offset(0, 0);
int tx = 0, ty = 0, tz = 0;
for (step = 0; step < steps; step++) {
o = walker_f(o);
int h = findDepositLocation(x + o.x, lowest, z + o.z);
if (h < lowest) {
lowest = h;
lowestoffset = o;
break;
}
}
/* flat ? */
if (lowest == y)
break displace;
tx = x + lowestoffset.x;
ty = lowest;
tz = z + lowestoffset.z;
SedBlock t = new SedBlock(world.getBlockAt(tx, ty, tz));
if (t.isProtected()) {
stat_protected++;
return;
}
/* roll to move it */
if (dice.roll(resistance)) {
stat_ignored_resistance++;
return;
}
/* It's time to move it, move it. */
switch (t.getType()) {
case AIR:
case WATER:
case STATIONARY_WATER:
case LEAVES:
case CACTUS:
case SAPLING:
case LONG_GRASS:
case DEAD_BUSH:
case YELLOW_FLOWER:
case RED_ROSE:
case BROWN_MUSHROOM:
case RED_MUSHROOM:
case CROPS:
case MELON_STEM:
case PUMPKIN_STEM:
case MELON_BLOCK:
case PUMPKIN:
case VINE:
case SUGAR_CANE:
case SNOW:
case SNOW_BLOCK:
case DOUBLE_PLANT:
case LEAVES_2:
/* play a sound at the deposition area */
Sound snd;
switch (world.getBlockAt(tx, ty, z).getType()) {
case WATER:
case STATIONARY_WATER:
targetunderwater = true;
break;
default:
break;
}
Material mat = b.getType();
byte dat = b.getData();
/* fix water issues at sealevel */
if ((y <= world.getSeaLevel()) &&
((world.getBlockAt(x - 1, y, z).getType() == Material.STATIONARY_WATER) ||
(world.getBlockAt(x + 1, y, z).getType() == Material.STATIONARY_WATER) ||
(world.getBlockAt(x, y, z - 1).getType() == Material.STATIONARY_WATER) ||
(world.getBlockAt(x, y, z + 1).getType() == Material.STATIONARY_WATER)) &&
((world.getBlockAt(x - 1, y, z).getType() != Material.AIR) &&
(world.getBlockAt(x + 1, y, z).getType() != Material.AIR) &&
(world.getBlockAt(x, y, z - 1).getType() != Material.AIR) &&
(world.getBlockAt(x, y, z + 1).getType() != Material.AIR)))
b.setType(Material.STATIONARY_WATER);
else
b.setType(Material.AIR);
b.setData((byte)0);
t.setType(mat);
t.setData(dat);
if (targetunderwater && !underwater) {
snd = Sound.SPLASH;
} else if (y - ty > 2) {
snd = Sound.FALL_BIG;
} else {
switch(b.getType()) {
case CLAY:
case SAND:
snd = Sound.DIG_SAND;
case DIRT:
case GRASS:
snd = Sound.DIG_GRASS;
break;
case GRAVEL:
snd = Sound.DIG_GRAVEL;
break;
case HARD_CLAY:
case STAINED_CLAY:
case COBBLESTONE:
case STONE:
case COAL_ORE:
case IRON_ORE:
case LAPIS_ORE:
case EMERALD_ORE:
case GOLD_ORE:
case DIAMOND_ORE:
case REDSTONE_ORE:
snd = Sound.DIG_STONE;
break;
default:
snd = Sound.FALL_SMALL;
break;
}
}
world.playSound(new Location(world, tx, ty, tz), snd, 1, 1);
stat_displaced++;
return;
default:
/* figure out how this happened */
stat_errors++;
getLogger().info("Attempted to move into a block of " + t.getType().name());
return;
}
}
/* degrade block? */
// degrade should factor in elevation?
//FIXME should detect the presence of ice near and factor in.
/*
* compensate for speed - this prevents at high block rates that
* everything just turns into a mudbath - We do want the occasional
* mudbath to appear, but only after rain or by chance, not always
*/
if (conf_compensate && (conf_blocks > 10) && (b.getType() == Material.GRASS)) {
if (dice.roll(10.0 / conf_blocks)) {
stat_ignored_rate++;
return;
}
}
/* do not decay sand further unless in a wet Biome, and under water */
if (b.getType() == Material.SAND) {
if (!(b.inClayBiome() && underwater)) {
stat_ignored_sand++;
return;
}
}
/* For now, don't decay into sand for biomes that are mostly dirtish, unless under water */
if (b.getType() == Material.DIRT){
if (!(b.inSandBiome() || underwater)) {
stat_ignored_sand++;
return;
}
}
if (dice.roll(hardness)) {
stat_ignored_hardness++;
return;
}
switch (b.getType()) {
case DIRT:
b.setType(Material.SAND);
b.setData((byte)0);
break;
case SOIL:
case GRASS:
b.setType(Material.DIRT);
break;
case SAND:
b.setType(Material.CLAY);
b.setData((byte)0);
break;
case GRAVEL:
b.setType(Material.DIRT);
break;
case CLAY:
/* we can displace clay, but not degrade */
return;
case HARD_CLAY:
case STAINED_CLAY:
case SANDSTONE:
case MOSSY_COBBLESTONE:
case COBBLESTONE:
b.setType(Material.GRAVEL);
b.setData((byte)0);
break;
case STONE:
switch (b.getBiome()) {
case MEGA_TAIGA:
case MEGA_TAIGA_HILLS:
case MEGA_SPRUCE_TAIGA:
case MEGA_SPRUCE_TAIGA_HILLS:
b.setType(Material.MOSSY_COBBLESTONE);
break;
default:
b.setType(Material.COBBLESTONE);
break;
}
case COAL_ORE:
case IRON_ORE:
case LAPIS_ORE:
case EMERALD_ORE:
case GOLD_ORE:
case DIAMOND_ORE:
case REDSTONE_ORE:
b.setType(Material.STONE);
break;
default:
stat_errors++;
return;
}
stat_lastx = x;
stat_lasty = y;
stat_lastz = z;
stat_degraded++;
}
/* helper function to find lowest deposit elevation ignoring water */
private int findDepositLocation(int x, int y, int z) {
int yy = y;
while (true) {
Block b = world.getBlockAt(x, yy, z);
if (isCrushable(b) || b.isLiquid() || b.isEmpty()) {
yy
if (yy == 0)
return yy;
} else {
return yy + 1;
}
}
}
private boolean isCrushable(Block b) {
switch (b.getType()) {
case LEAVES:
case CACTUS:
case SAPLING:
case LONG_GRASS:
case DEAD_BUSH:
case YELLOW_FLOWER:
case RED_ROSE:
case BROWN_MUSHROOM:
case RED_MUSHROOM:
case CROPS:
case MELON_STEM:
case PUMPKIN_STEM:
case MELON_BLOCK:
case PUMPKIN:
case VINE:
case SUGAR_CANE:
case DOUBLE_PLANT:
case LEAVES_2:
case SNOW:
case SNOW_BLOCK:
return true;
default:
return false;
}
}
}
private class SedimentologyRunnable implements Runnable {
public void run() {
for (SedWorld sedWorld: sedWorldList) {
for (int j = 0; j < conf_blocks; j++)
sedWorld.sedRandomBlock();
}
}
}
class SedimentologyCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
String msg = "unknown command";
String helpmsg = "\n" +
"/sedimentology help - display this help message\n" +
"/sedimentology stats - display statistics\n" +
"/sedimentology list - display enabled worlds\n" +
"/sedimentology blocks <int> - sed number of block attempts per cycle\n" +
"/sedimentology enable <world> - enable for world\n" +
"/sedimentology disable <world> - enable for world";
if (split.length >= 1) {
switch (split[0]) {
case "blocks":
if (split.length == 2) {
conf_blocks = Long.parseLong(split[1]);
getConfig().set("blocks", conf_blocks);
saveConfig();
}
msg = "number of blocks set to " + conf_blocks;
break;
case "list":
msg = "plugin enabled for worlds:\n";
for (SedWorld s: sedWorldList) {
msg += "- " + s.world.getName() + "\n";
}
break;
case "enable":
if (split.length != 2) {
msg = "enable requires a world name";
break;
};
if (!enableWorld(split[1]))
msg = "unable to enable for world \"" + split[1] + "\"";
else
msg = "enabled for world \"" + split[1] + "\"";
break;
case "disable":
if (split.length != 2) {
msg = "disable requires a world name";
break;
};
if (!disableWorld(split[1]))
msg = "unable to disable for world \"" + split[1] + "\"";
else
msg = "disabled for world \"" + split[1] + "\"";
break;
case "stats":
World world = org.bukkit.Bukkit.getWorld("world");
Chunk ChunkList[] = world.getLoadedChunks();
msg = String.format("blocks: %d ticks: %d protect: %s\n" +
"considered %d, displaced %d, degraded %d blocks in %d chunks %d errors\nlast one at %d %d %d\n" +
"ignored: edge %d, type %d, storm %d, vegetation %d, resistance %d, water %d, wave %d, sand %d, hardness %d," +
"protected %d, locked in %d, rate %d",
conf_blocks, conf_ticks, conf_protect ? "true" : "false",
stat_considered, stat_displaced, stat_degraded, ChunkList.length, stat_errors,
stat_lastx, stat_lasty, stat_lastz,
stat_ignored_edge, stat_ignored_type, stat_ignored_storm, stat_ignored_vegetation,
stat_ignored_resistance, stat_ignored_water, stat_ignored_wave, stat_ignored_sand, stat_ignored_hardness,
stat_protected, stat_ignored_lockedin, stat_ignored_rate);
break;
case "test":
if (split.length != 7) {
msg = "test requires 6 parameters: world x1 z1 x2 z2 blocks";
break;
};
for (SedWorld sw: sedWorldList) {
if (sw.world.getName().equals(split[1])) {
int x1 = Integer.parseInt(split[2]);
int z1 = Integer.parseInt(split[3]);
int x2 = Integer.parseInt(split[4]);
int z2 = Integer.parseInt(split[5]);
if (x1 > x2) {
int t = x1;
x1 = x2;
x2 = t;
}
if (z1 > z2) {
int t = z1;
z1 = z2;
z2 = t;
}
for (long i = 0; i < Long.parseLong(split[6]); i++)
for (int x = x1; x <= x2; x++)
for (int z = z1; z <= z2; z++)
sw.sedBlock(x, z);
msg = "test cycle finished";
break;
} else {
msg = "Invalid world name - world must be enabled already";
break;
}
}
break;
case "help":
default:
msg = helpmsg;
break;
}
} else {
msg = helpmsg;
}
if (!(sender instanceof Player)) {
getLogger().info(msg);
} else {
Player player = (Player) sender;
player.sendMessage(msg);
}
return true;
}
}
class SedimentologyListener implements Listener {
@EventHandler
public void onChunkLoadEvent(ChunkLoadEvent event) {
World w = event.getWorld();
for (SedWorld ww: sedWorldList) {
if (ww.world.equals(w)) {
Chunk c = event.getChunk();
ww.load(c.getX(), c.getZ());
}
}
}
@EventHandler
public void onChunkUnloadEvent(ChunkUnloadEvent event) {
World w = event.getWorld();
for (SedWorld ww: sedWorldList) {
if (ww.world.equals(w)) {
Chunk c = event.getChunk();
ww.unload(c.getX(), c.getZ());
}
}
}
}
public void onEnable() {
sedWorldList = new ArrayList<SedWorld>();
/* these are used to displace blocks */
walker = new offset[24];
walker[0] = new offset(0,1);
walker[1] = new offset(1,0);
walker[2] = new offset(0,-1);
walker[3] = new offset(-1,0);
walker[4] = new offset(1,1);
walker[5] = new offset(1,-1);
walker[6] = new offset(-1,1);
walker[7] = new offset(-1,-1);
walker[8] = new offset(2,0);
walker[9] = new offset(-2,0);
walker[10] = new offset(0,2);
walker[11] = new offset(0,-2);
walker[12] = new offset(2,1);
walker[13] = new offset(2,-1);
walker[14] = new offset(1,2);
walker[15] = new offset(1,-2);
walker[16] = new offset(-1,2);
walker[17] = new offset(-1,-2);
walker[18] = new offset(-2,1);
walker[19] = new offset(-2,-1);
walker[20] = new offset(2,2);
walker[21] = new offset(-2,2);
walker[22] = new offset(2,-2);
walker[23] = new offset(-2,-2);
/* config data handling */
saveDefaultConfig();
conf_blocks = getConfig().getInt("blocks");
conf_ticks = getConfig().getInt("ticks");
getLogger().info("blocks: " + conf_blocks + ", ticks: " + conf_ticks);
List<String> worldStringList = getConfig().getStringList("worlds");
/* populate chunk cache for each world */
for (int i = 0; i < worldStringList.size(); i++)
enableWorld(worldStringList.get(i));
/* Detect Factions */
if (org.bukkit.Bukkit.getPluginManager().isPluginEnabled("Factions"))
have_factions = true;
/* Towny */
if (org.bukkit.Bukkit.getPluginManager().isPluginEnabled("Towny")) {
Plugin p = org.bukkit.Bukkit.getPluginManager().getPlugin("Towny");
if (p != null) {
towny_universe = ((Towny)(p)).getTownyUniverse();
have_towny = true;
}
}
/* WorldGuard */
if (org.bukkit.Bukkit.getPluginManager().isPluginEnabled("WorldGuard"))
have_worldguard = true;
getLogger().info("Protection plugins: " +
(have_factions ? "+" : "-") + "Factions, " +
(have_towny ? "+" : "-") + "Towny, " +
(have_worldguard ? "+" : "-") + "WorldGuard, "
);
conf_protect = getConfig().getBoolean("protect");
getLogger().info("protection is " + (conf_protect ? "on" : "off"));
/* even handler takes care of updating it from there */
getServer().getPluginManager().registerEvents(new SedimentologyListener(), this);
getCommand("sedimentology").setExecutor(new SedimentologyCommand());
BukkitScheduler scheduler = Bukkit.getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new SedimentologyRunnable(), 1L, conf_ticks);
}
} |
package com.anders.michigantendiesapi;
import com.heroku.sdk.jdbc.DatabaseUrl;
import java.io.StringReader;
import java.sql.*;
import javax.json.*;
import static spark.Spark.*;
/**
*
* @author Anders
*/
public class Main {
public static String mDiningData;
public static String items;
public static String diningHalls;
public static String filterableEntries;
public static JsonObject itemsJson;
public static void getMDiningData() {
Connection connection = null;
try {
connection = DatabaseUrl.extract().getConnection();
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM dining_data");
result.next();
connection.close();
String data = result.getString("data");
mDiningData = data;
JsonReader reader = Json.createReader(new StringReader(mDiningData));
JsonObject allData = reader.readObject();
itemsJson = allData.getJsonObject("items");
items = allData.getJsonObject("items").toString();
diningHalls = allData.getJsonObject("diningHalls").toString();
filterableEntries = allData.getJsonArray("filterableEntries").toString();
} catch (Exception e) {
System.err.println("getMDiningData: " + e);
mDiningData = "UNABLE TO RETRIEVE DATA";
items = "UNABLE TO RETRIEVE DATA";
diningHalls = "UNABLE TO RETRIEVE DATA";
filterableEntries = "UNABLE TO RETRIEVE DATA";
}
}
public static void main(String args[]) {
port(Integer.valueOf(System.getenv("PORT")));
//staticFiles.location("/public");
getMDiningData();
System.out.println("Serving data on port " + System.getenv("PORT"));
get("/", (request, response) -> {
response.header("Content-Type", "application/json");
response.header("Access-Control-Allow-Origin", "*");
response.header("Content-Length", "" + mDiningData.length());
return mDiningData;
});
get("/items", (request, response) -> {
response.header("Content-Type", "application/json");
response.header("Access-Control-Allow-Origin", "*");
response.header("Content-Length", "" + items.length());
return items;
});
get("/dininghalls", (request, response) -> {
response.header("Content-Type", "application/json");
response.header("Access-Control-Allow-Origin", "*");
response.header("Content-Length", "" + diningHalls.length());
return diningHalls;
});
get("/filterableentries", (request, response) -> {
response.header("Content-Type", "application/json");
response.header("Access-Control-Allow-Origin", "*");
response.header("Content-Length", "" + filterableEntries.length());
return filterableEntries;
});
get("/item", (request, response) -> {
response.header("Content-Type", "application/json");
response.header("Access-Control-Allow-Origin", "*");
String item = itemsJson.getJsonObject(request.queryParams("name")).toString();
System.out.println(request.toString());
System.out.println(request.queryParams("name"));
System.out.println(item);
response.header("Content-Length", "" + item.length());
return item;
});
}
} |
package com.brajagopal.rmend.dao;
import com.brajagopal.rmend.data.ContentDictionary;
import com.brajagopal.rmend.data.beans.DocumentBean;
import com.brajagopal.rmend.data.meta.DocumentMeta;
import com.brajagopal.rmend.utils.JsonUtils;
import com.google.api.services.datastore.DatastoreV1.*;
import com.google.api.services.datastore.client.Datastore;
import com.google.api.services.datastore.client.DatastoreException;
import com.google.api.services.datastore.client.DatastoreHelper;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.apache.log4j.Logger;
import javax.annotation.Nullable;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @author <bxr4261>
*/
@SuppressWarnings("unused")
public class GCloudDao implements IRMendDao {
private static final Logger logger = Logger.getLogger(GCloudDao.class);
private final Datastore datastore;
private int batchSize;
static final String DOCUMENT_KIND = "document";
static final String DOCUMENT_MD5SUM_KIND = "md5sum";
static final String DOCUMENT_TITLE_KIND = "title";
static final String DOCUMENT_NUMBER_KIND = "docNumber";
static final String DOCUMENT_JSON_KIND = "docBody";
static final String DOCUMENT_TOPIC_KIND = "topic";
static final String KEY_PROPERTY = "__key__";
static final String ENTITY_KIND = "entity";
static final String DOCUMENT_SCORE_KIND = "score";
static final String ENTITIY_CLASSIFIER_KIND = "entityId";
static final String DOCUMENT_META_KIND = "docMeta";
private GCloudDao(boolean _isLocal) throws GeneralSecurityException, IOException {
this(_isLocal, 1);
}
private GCloudDao(boolean _isLocal, int _batchSize) throws GeneralSecurityException, IOException {
batchSize = _batchSize;
if (_isLocal) {
datastore = DatastoreHelper.getDatastoreFromEnv();
}
else {
datastore = null;
}
}
public static GCloudDao getLocalInstance() throws GeneralSecurityException, IOException {
return new GCloudDao(true);
}
public static GCloudDao getLocalInstance(int _batchSize) throws GeneralSecurityException, IOException {
return new GCloudDao(true, _batchSize);
}
@Override
public void putDocument(DocumentBean _docBean) throws DatastoreException {
putDocument(_docBean, _docBean.getDocId());
}
@Override
public void putDocument(DocumentBean _docBean, String _identifier) throws DatastoreException {
Collection<Value> topicValues = new ArrayList<Value>();
for (String topic : _docBean.getTopic()) {
topicValues.add(DatastoreHelper.makeValue(topic).build());
}
Entity article = Entity.newBuilder()
.setKey(DatastoreHelper.makeKey(DOCUMENT_KIND, _identifier))
.addProperty(DatastoreHelper.makeProperty(DOCUMENT_MD5SUM_KIND, DatastoreHelper.makeValue(_docBean.getContentMD5Sum()).setIndexed(false)))
.addProperty(DatastoreHelper.makeProperty(DOCUMENT_TITLE_KIND, DatastoreHelper.makeValue(_docBean.getTitle()).setIndexed(false)))
.addProperty(DatastoreHelper.makeProperty(DOCUMENT_TOPIC_KIND, DatastoreHelper.makeValue(topicValues)))
.addProperty(DatastoreHelper.makeProperty(DOCUMENT_NUMBER_KIND, DatastoreHelper.makeValue(_docBean.getDocumentNumber())))
.addProperty(DatastoreHelper.makeProperty(DOCUMENT_JSON_KIND, DatastoreHelper.makeValue(JsonUtils.getGsonInstance().toJson(_docBean)).setIndexed(false)))
.build();
CommitRequest request = CommitRequest.newBuilder()
.setMode(CommitRequest.Mode.NON_TRANSACTIONAL)
.setMutation(Mutation.newBuilder().addInsert(article))
.build();
datastore.commit(request);
}
@Override
public DocumentBean getDocument(Long _documentNumber) throws DatastoreException {
Query.Builder query = Query.newBuilder();
query.addKindBuilder().setName(DOCUMENT_KIND);
query.setFilter(DatastoreHelper.makeFilter(
DOCUMENT_NUMBER_KIND,
PropertyFilter.Operator.EQUAL,
DatastoreHelper.makeValue(_documentNumber)));
List<Entity> documents = runQuery(query.build());
if (documents.size() == 0) {
logger.warn("No Document found for DocumentNumber: " + _documentNumber);
}
else if (documents.size() == 1) {
Map<String, Value> propertyMap = DatastoreHelper.getPropertyMap(documents.get(0));
List<Value> topicValues = DatastoreHelper.getList(propertyMap.get(DOCUMENT_TOPIC_KIND));
Collection<String> topics = Lists.transform(topicValues, new Function<Value, String>() {
@Nullable
@Override
public String apply(Value value) {
return DatastoreHelper.getString(value);
}
});
return JsonUtils.getGsonInstance().fromJson(DatastoreHelper.getString(propertyMap.get(DOCUMENT_JSON_KIND)), DocumentBean.class);
}
return null;
}
@Override
public void putEntityMeta(Collection<Map.Entry<String , DocumentMeta>> _docMetaCollection) throws DatastoreException {
int ctr = 0;
Mutation.Builder builder = Mutation.newBuilder();
for (Map.Entry<String, DocumentMeta> entry : _docMetaCollection) {
String _entityIdentifier = entry.getKey();
DocumentMeta _docMeta = entry.getValue();
String identifier = _entityIdentifier + ContentDictionary.KEY_SEPARATOR + _docMeta.getDocId();
Entity article = Entity.newBuilder()
.setKey(DatastoreHelper.makeKey(ENTITY_KIND, identifier))
.addProperty(DatastoreHelper.makeProperty(ENTITIY_CLASSIFIER_KIND, DatastoreHelper.makeValue(_entityIdentifier)))
.addProperty(DatastoreHelper.makeProperty(DOCUMENT_SCORE_KIND, DatastoreHelper.makeValue(_docMeta.getScore())))
.addProperty(DatastoreHelper.makeProperty(DOCUMENT_META_KIND, DatastoreHelper.makeValue(JsonUtils.getGsonInstance().toJson(_docMeta)).setIndexed(false)))
.build();
builder.addInsert(article);
if ((ctr++ % batchSize) == 0) {
try {
persist(builder);
}
catch (DatastoreException e) {
logger.warn("Failed to persist : "+ identifier + " (" + e.getMessage() + ")");
}
finally {
builder = Mutation.newBuilder();
}
}
}
}
@Override
public Collection<DocumentMeta> getEntityMeta(String _metaIdentifier) throws DatastoreException {
Collection<DocumentMeta> retVal = null;
Query.Builder query = Query.newBuilder();
query.addKindBuilder().setName(ENTITY_KIND);
query.setFilter(DatastoreHelper.makeFilter(
ENTITIY_CLASSIFIER_KIND,
PropertyFilter.Operator.EQUAL,
DatastoreHelper.makeValue(_metaIdentifier)));
List<Entity> entityMetadata = runQuery(query.build());
if (entityMetadata.size() == 0) {
logger.warn("No Metadata found for EntityId: " + _metaIdentifier);
}
else if (entityMetadata.size() > 0) {
retVal = new ArrayList<DocumentMeta>(entityMetadata.size());
for (Entity entity : entityMetadata) {
Map<String, Value> propertyMap = DatastoreHelper.getPropertyMap(entity);
retVal.add(JsonUtils.getGsonInstance().fromJson(DatastoreHelper.getString(propertyMap.get(DOCUMENT_META_KIND)), DocumentMeta.class));
}
}
return retVal;
}
@Override
public Map<String, Collection<DocumentMeta>> getEntityMeta(Collection<String> _metaIdentifier) throws DatastoreException {
return null;
}
private void persist(Mutation.Builder _builder) throws DatastoreException {
CommitRequest request = CommitRequest.newBuilder()
.setMode(CommitRequest.Mode.NON_TRANSACTIONAL)
.setMutation(_builder)
.build();
datastore.commit(request);
}
private List<Entity> runQuery(Query query) throws DatastoreException {
RunQueryRequest.Builder request = RunQueryRequest.newBuilder();
request.setQuery(query);
RunQueryResponse response = datastore.runQuery(request.build());
if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {
System.err.println("WARNING: partial results\n");
}
List<EntityResult> results = response.getBatch().getEntityResultList();
List<Entity> entities = new ArrayList<Entity>(results.size());
for (EntityResult result : results) {
entities.add(result.getEntity());
}
return entities;
}
} |
package shape;
import javafx.scene.canvas.Canvas;
import javafx.scene.web.WebView;
public class Hexaflake extends FractalShape {
double centerX, centerY;
double X1, X2, Y1, Y2;
double REDUCE, square;
public Hexaflake(int maxDepth, Canvas canvas, WebView webView) {
super(maxDepth, canvas, webView);
square = Math.min(canvasHeight, canvasWidth);
centerX = canvasWidth/2;
centerY = canvasHeight/2;
X1 = 0.5;
X2 = 0.25;
Y1 = Math.sqrt(3)/4;
Y2 = 0;
REDUCE = 0.3333;
p = 7;
s = 3;
}
@Override
void drawLevel0() {
}
@Override
public void drawCurrentLevel() {
drawHexaflake(getCurrentDepth(), centerX, centerY, square - square * 0.1);
updateFractalDimension(getCurrentDepth());
}
public void drawHexaflake(int n, double cx, double cy, double sz){
double x0, y0, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5;
x0 = cx;
y0 = cy + (X1 * sz);
x1 = cx - (Y1 *sz);
y1 = cy + (X2 * sz);
x2 = cx - (Y1 *sz);
y2 = cy - (X2 * sz);
x3 = cx;
y3 = cy - (X1 * sz);
x4 = cx + (Y1 *sz);
y4 = cy - (X2 * sz);
x5 = x4;
y5 = cy + (X2 * sz);
double[] xArr = {x0, x1, x2, x3, x4, x5};
double[] yArr = {y0, y1, y2, y3, y4, y5};
if(n > 0) {
drawHexaflake(n-1, cx, cy, sz * REDUCE);
drawHexaflake(n-1, x0, cy + (y0 - y3)/3, sz * REDUCE);
drawHexaflake(n-1, cx - (x4 - x3)/3*2, cy + (y0 - y3)/6, sz * REDUCE);
drawHexaflake(n-1, cx - (x4 - x3)/3*2, cy - (y0 - y3)/6, sz * REDUCE);
drawHexaflake(n-1, x3, cy - (y0 - y3)/3, sz * REDUCE);
drawHexaflake(n-1, cx + (x4 - x3)/3*2, cy - (y0 - y3)/6, sz * REDUCE);
drawHexaflake(n-1, cx + (x4 - x3)/3*2, cy + (y0 - y3)/6, sz * REDUCE);
}
else {
gContext.fillPolygon(xArr, yArr, 6);
}
}
} |
/*
* @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a>
* @version $Id: PortletServlet.java 5032 2006-08-17 18:15:06Z novotny $
*/
package org.gridsphere.provider.portlet.jsr;
import org.gridsphere.portlet.*;
import org.gridsphere.portlet.jsrimpl.*;
import org.gridsphere.portlet.PortletLog;
import org.gridsphere.portlet.User;
import org.gridsphere.portlet.service.spi.PortletServiceFactory;
import org.gridsphere.portlet.service.PortletServiceException;
import org.gridsphere.portlet.impl.SportletLog;
import org.gridsphere.portlet.impl.SportletProperties;
import org.gridsphere.portlet.impl.ClientImpl;
import org.gridsphere.portletcontainer.ApplicationPortletConfig;
import org.gridsphere.portletcontainer.jsrimpl.JSRApplicationPortletImpl;
import org.gridsphere.portletcontainer.jsrimpl.JSRPortletWebApplicationImpl;
import org.gridsphere.portletcontainer.jsrimpl.descriptor.*;
import org.gridsphere.portletcontainer.jsrimpl.descriptor.types.TransportGuaranteeType;
import org.gridsphere.services.core.registry.PortletManagerService;
import org.gridsphere.services.core.registry.PortletRegistryService;
import org.gridsphere.services.core.security.auth.LoginService;
import javax.portlet.*;
import javax.portlet.PortletMode;
import javax.portlet.Portlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.portlet.UnavailableException;
import java.io.*;
import java.util.*;
import java.util.ResourceBundle;
public class PortletServlet extends HttpServlet
implements Servlet, ServletConfig,
HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener {
private transient PortletLog log = SportletLog.getInstance(PortletServlet.class);
private transient PortletRegistryService registryService = null;
private JSRPortletWebApplicationImpl portletWebApp = null;
private PortletContext portletContext = null;
private Map portlets = null;
private Map portletclasses = null;
private Map portletConfigHash = null;
private Map userKeys = new HashMap();
private List securePortlets = new ArrayList();
public void init(ServletConfig config) throws ServletException {
super.init(config);
log.debug("in init of PortletServlet");
portlets = new Hashtable();
portletclasses = new Hashtable();
portletConfigHash = new Hashtable();
}
public void initJSRPortletWebapp() {
ServletContext ctx = this.getServletContext();
try {
portletWebApp = new JSRPortletWebApplicationImpl(ctx, Thread.currentThread().getContextClassLoader());
} catch (Exception e) {
log.error("Unable to create portlet web application ", e);
return;
}
Collection appPortlets = portletWebApp.getAllApplicationPortlets();
Iterator it = appPortlets.iterator();
while (it.hasNext()) {
JSRApplicationPortletImpl appPortlet = (JSRApplicationPortletImpl) it.next();
String portletClass = appPortlet.getApplicationPortletClassName();
String portletName = appPortlet.getApplicationPortletName();
try {
// instantiate portlet classes
Portlet portletInstance = (Portlet) Class.forName(portletClass).newInstance();
//portlets.put(portletClass, portletInstance);
portlets.put(portletName, portletInstance);
// mappings between names and classes
portletclasses.put(portletClass, portletName);
log.debug("Creating new portlet instance: " + portletClass);
// put portlet web app in registry
} catch (Exception e) {
log.error("Unable to create jsr portlet instance: " + portletClass, e);
return;
}
}
UserAttribute[] userAttrs = portletWebApp.getUserAttributes();
if (userAttrs != null) {
String key = null;
for (int i = 0; i < userAttrs.length; i++) {
key = userAttrs[i].getName().getContent();
userKeys.put(key, "");
}
}
SecurityConstraint[] secConstraints = portletWebApp.getSecurityConstraints();
if (secConstraints != null) {
for (int i = 0; i < secConstraints.length; i++) {
PortletCollection portlets = secConstraints[i].getPortletCollection();
PortletName[] names = portlets.getPortletName();
UserDataConstraint userConstraint = secConstraints[i].getUserDataConstraint();
TransportGuaranteeType guaranteeType = userConstraint.getTransportGuarantee();
if (guaranteeType.equals(TransportGuaranteeType.NONE)) {
names = null;
}
if (names != null) {
for (int j = 0; j < names.length; j++) {
securePortlets.add(names[j].getContent());
}
}
}
}
// create portlet context
portletContext = new PortletContextImpl(ctx);
// load in any authentication modules if found-- this is a GridSphere extension
try {
LoginService loginService = (LoginService)PortletServiceFactory.createPortletService(LoginService.class, true);
InputStream is = getServletContext().getResourceAsStream("/WEB-INF/authmodules.xml");
if (is != null) {
String authModulePath = this.getServletContext().getRealPath("/WEB-INF/authmodules.xml");
loginService.loadAuthModules(authModulePath, Thread.currentThread().getContextClassLoader());
log.info("loading authentication modules from: " + authModulePath);
} else {
log.debug("no auth module descriptor found");
}
} catch (PortletServiceException e) {
log.error("Unable to create login service instance!", e);
}
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// security check
// make sure request comes only from gridsphere servlet same ip
//System.err.println("remote Address: " + request.getRemoteAddr());
// If no portlet ID exists, this may be a command to init or shutdown a portlet instance
// currently either all portlets are initialized or shutdown, not one individually...
String method = (String) request.getAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD);
if (method.equals(SportletProperties.INIT)) {
initJSRPortletWebapp();
Set set = portlets.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
String portletName = (String) it.next();
Portlet portlet = (Portlet) portlets.get(portletName);
log.debug("in PortletServlet: service(): Initializing portlet " + portletName);
PortletDefinition portletDef = portletWebApp.getPortletDefinition(portletName);
PortletConfig portletConfig = new PortletConfigImpl(getServletConfig(), portletDef, Thread.currentThread().getContextClassLoader());
try {
portlet.init(portletConfig);
portletConfigHash.put(portletName, portletConfig);
} catch (Exception e) {
log.error("in PortletServlet: service(): Unable to INIT portlet " + portletName, e);
// PLT.5.5.2.1 Portlet that fails to initialize must not be placed in active service
it.remove();
}
}
try {
PortletManagerService manager = (PortletManagerService)PortletServiceFactory.createPortletService(PortletManagerService.class, true);
manager.addPortletWebApplication(portletWebApp);
} catch (PortletServiceException e) {
log.error("Unable to create instance of PortletManagerService", e);
}
try {
registryService = (PortletRegistryService)PortletServiceFactory.createPortletService(PortletRegistryService.class, true);
} catch (PortletServiceException e) {
log.error("Unable to create instance of PortletRegistryService", e);
}
return;
} else if (method.equals(SportletProperties.INIT_CONCRETE)) {
// do nothing for concrete portlets
return;
} else if (method.equals(SportletProperties.DESTROY)) {
Iterator it = portlets.keySet().iterator();
while (it.hasNext()) {
String portletName = (String) it.next();
Portlet portlet = (Portlet) portlets.get(portletName);
log.debug("in PortletServlet: service(): Destroying portlet " + portletName);
try {
portlet.destroy();
} catch (RuntimeException e) {
log.error("Caught exception during portlet destroy", e);
}
}
return;
} else if (method.equals(SportletProperties.DESTROY_CONCRETE)) {
// do nothing for concrete portlets
return;
} else if (method.equals(SportletProperties.LOGIN)) {
} else if (method.equals(SportletProperties.LOGOUT)) {
request.getSession(true).invalidate();
}
// There must be a portlet ID to know which portlet to service
String pid = (String) request.getAttribute(SportletProperties.PORTLETID);
String cid = (String) request.getAttribute(SportletProperties.COMPONENT_ID);
if (pid == null) {
// it may be in the request parameter
pid = request.getParameter(SportletProperties.PORTLETID);
if (pid == null) {
log.debug("in PortletServlet: service(): No PortletID found in request!");
return;
}
request.setAttribute(SportletProperties.PORTLETID, pid);
}
log.debug("have a portlet id " + pid + " component id= " + cid);
String portletName = "";
int idx = pid.indexOf("
Portlet portlet = null;
if (idx > 0) {
portletName = pid.substring(idx+1);
// this hack uses the portletclasses hash that identifies classname to portlet mappings
} else {
portletName = (String)portletclasses.get(pid);
}
portlet = (Portlet) portlets.get(portletName);
request.setAttribute(SportletProperties.PORTLET_CONFIG, portletConfigHash.get(portletName));
JSRApplicationPortletImpl appPortlet =
(JSRApplicationPortletImpl) registryService.getApplicationPortlet(pid);
if (appPortlet == null) {
log.error("Unable to get portlet from registry identified by: " + pid);
return;
}
// set the supported mime types
Supports[] supports = appPortlet.getSupports();
List mimeTypes = new ArrayList();
for (int i = 0; i < supports.length; i++) {
Supports s = supports[i];
String mimeType = s.getMimeType().getContent();
mimeTypes.add(mimeType);
request.setAttribute(SportletProperties.MIME_TYPES, mimeTypes);
}
setPortletModes(request, appPortlet);
// perform user conversion from gridsphere to JSR model
User user = (User) request.getAttribute(SportletProperties.PORTLET_USER);
Map userInfo;
if (user != null) {
userInfo = new HashMap();
userInfo.putAll(userKeys);
if (userInfo.containsKey("user.name")) userInfo.put("user.name", user.getUserName());
if (userInfo.containsKey("user.id")) userInfo.put("user.id", user.getID());
if (userInfo.containsKey("user.email")) userInfo.put("user.email", user.getEmailAddress());
if (userInfo.containsKey("user.organization")) userInfo.put("user.organization", user.getOrganization());
if (userInfo.containsKey("user.lastlogintime")) userInfo.put("user.lastlogintime", new Long(user.getLastLoginTime()).toString());
if (userInfo.containsKey("user.name.full")) userInfo.put("user.name.full", user.getFullName());
if (userInfo.containsKey("user.timezone")) userInfo.put("user.timezone", user.getAttribute(User.TIMEZONE));
if (userInfo.containsKey("user.locale")) userInfo.put("user.locale", user.getAttribute(User.LOCALE));
if (userInfo.containsKey("user.theme")) userInfo.put("user.theme", user.getAttribute(User.THEME));
if (userInfo.containsKey("user.login.id")) userInfo.put("user.login.id", user.getUserName());
Enumeration e = user.getAttributeNames();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
if (userInfo.containsKey(key)) userInfo.put(key, user.getAttribute(key));
}
//userInfo.put("user.name.given", user.getGivenName());
//userInfo.put("user.name.family", user.getFamilyName());
request.setAttribute(PortletRequest.USER_INFO, userInfo);
// create user principal
UserPrincipal userPrincipal = new UserPrincipal(user.getUserName());
request.setAttribute(SportletProperties.PORTLET_USER_PRINCIPAL, userPrincipal);
}
/*
UserAttribute[] userAttrs = portletWebApp.getUserAttributes();
for (int i = 0; i < userAttrs.length; i++) {
UserAttribute userAttr = userAttrs[i];
String name = userAttr.getName().getContent();
userInfo.put(name, "");
}
request.setAttribute(PortletRequest.USER_INFO, userInfo);
*/
// portlet preferences
PortalContext portalContext = appPortlet.getPortalContext();
request.setAttribute(SportletProperties.PORTAL_CONTEXT, portalContext);
if (portlet == null) {
log.error("in PortletServlet: service(): No portlet matching " + pid + " found!");
return;
}
request.removeAttribute(SportletProperties.SSL_REQUIRED);
if (securePortlets.contains(pid)) {
request.setAttribute(SportletProperties.SSL_REQUIRED, "true");
}
if (method.equals(SportletProperties.SERVICE)) {
String action = (String) request.getAttribute(SportletProperties.PORTLET_ACTION_METHOD);
if (action != null) {
log.debug("in PortletServlet: action is not NULL");
if (action.equals(SportletProperties.DO_TITLE)) {
RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext, supports);
RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext);
renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest);
renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse);
log.debug("in PortletServlet: do title " + pid);
try {
doTitle(portlet, renderRequest, renderResponse);
} catch (Exception e) {
log.error("Error during doTitle:", e);
request.setAttribute(SportletProperties.PORTLETERROR + pid, new org.gridsphere.portlet.PortletException(e));
}
} else if (action.equals(SportletProperties.WINDOW_EVENT)) {
// do nothing
} else if (action.equals(SportletProperties.MESSAGE_RECEIVED)) {
// do nothing
} else if (action.equals(SportletProperties.ACTION_PERFORMED)) {
PortletPreferencesManager prefsManager = new PortletPreferencesManager();
javax.portlet.PreferencesValidator validator = appPortlet.getPreferencesValidator();
prefsManager.setValidator(validator);
prefsManager.setIsRender(false);
if (user != null) {
prefsManager.setUserId(user.getID());
}
prefsManager.setPortletId(appPortlet.getApplicationPortletID());
prefsManager.setPreferencesDesc(appPortlet.getPreferencesDescriptor());
request.setAttribute(SportletProperties.PORTLET_PREFERENCES_MANAGER, prefsManager);
ActionRequestImpl actionRequest = new ActionRequestImpl(request, portalContext, portletContext, supports);
ActionResponse actionResponse = new ActionResponseImpl(request, response, portalContext);
log.debug("in PortletServlet: action handling portlet " + pid);
try {
// INVOKE PORTLET ACTION
portlet.processAction(actionRequest, actionResponse);
Map params = ((ActionResponseImpl) actionResponse).getRenderParameters();
actionRequest.setAttribute(SportletProperties.RENDER_PARAM_PREFIX + pid + "_" + cid, params);
log.debug("placing render params in attribute: key= " + SportletProperties.RENDER_PARAM_PREFIX + pid + "_" + cid);
redirect(request, response, actionRequest, actionResponse, portalContext);
} catch (Exception e) {
log.error("Error during processAction:", e);
request.setAttribute(SportletProperties.PORTLETERROR + pid, new org.gridsphere.portlet.PortletException(e));
}
}
} else {
PortletPreferencesManager prefsManager = new PortletPreferencesManager();
javax.portlet.PreferencesValidator validator = appPortlet.getPreferencesValidator();
prefsManager.setValidator(validator);
prefsManager.setIsRender(true);
if (user != null) {
prefsManager.setUserId(user.getID());
}
prefsManager.setPortletId(appPortlet.getApplicationPortletID());
prefsManager.setPreferencesDesc(appPortlet.getPreferencesDescriptor());
request.setAttribute(SportletProperties.PORTLET_PREFERENCES_MANAGER, prefsManager);
RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext, supports);
RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext);
renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest);
renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse);
log.debug("in PortletServlet: rendering portlet " + pid);
if (renderRequest.getAttribute(SportletProperties.RESPONSE_COMMITTED) == null) {
try {
portlet.render(renderRequest, renderResponse);
} catch (UnavailableException e) {
log.error("in PortletServlet(): doRender() caught unavailable exception: ");
try {
portlet.destroy();
} catch (Exception d) {
log.error("in PortletServlet(): destroy caught unavailable exception: ", d);
}
} catch (Exception e) {
if (request.getAttribute(SportletProperties.PORTLETERROR + pid) == null) {
request.setAttribute(SportletProperties.PORTLETERROR + pid, e);
}
throw new ServletException(e);
}
}
}
request.removeAttribute(SportletProperties.PORTLET_ACTION_METHOD);
} else {
log.error("in PortletServlet: service(): No " + SportletProperties.PORTLET_LIFECYCLE_METHOD + " found in request!");
}
request.removeAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD);
}
/*
protected void setGroupAndRole(PortletRequest request, PortletResponse response) {
String ctxPath = this.getServletContext().getRealPath("");
int i = ctxPath.lastIndexOf(File.separator);
String groupName = ctxPath.substring(i+1);
PortletGroup group = aclService.getGroup(groupName);
if (group == null)
group = PortletGroupFactory.createPortletGroup(groupName);
PortletRole role = aclService.getRoleInGroup(request.getUser(), group);
log.debug("Setting Group: " + group.toString() + " Role: " + role.toString());
request.setAttribute(SportletProperties.PORTLET_GROUP, group);
request.setAttribute(SportletProperties.PORTLET_ROLE, role);
}
*/
protected void setPortletModes(HttpServletRequest request, JSRApplicationPortletImpl appPortlet) {
ApplicationPortletConfig appPortletConfig = appPortlet.getApplicationPortletConfig();
Client client = (Client)request.getSession().getAttribute(SportletProperties.CLIENT);
if (client == null) {
client = new ClientImpl(request);
request.getSession().setAttribute(SportletProperties.CLIENT, client);
}
List appModes = appPortletConfig.getSupportedModes(client.getMimeType());
// convert modes from GridSphere type to JSR
Iterator it = appModes.iterator();
List myModes = new ArrayList();
PortletMode m = PortletMode.VIEW;
while (it.hasNext()) {
org.gridsphere.portlet.Mode mode = (org.gridsphere.portlet.Mode)it.next();
if (mode == org.gridsphere.portlet.Mode.VIEW) {
m = PortletMode.VIEW;
} else if (mode == org.gridsphere.portlet.Mode.EDIT) {
m = PortletMode.EDIT;
} else if (mode == org.gridsphere.portlet.Mode.HELP) {
m = PortletMode.HELP;
} else if (mode == org.gridsphere.portlet.Mode.CONFIGURE) {
m = new PortletMode("config");
} else {
m = new PortletMode(mode.toString());
}
myModes.add(m.toString());
}
request.setAttribute(SportletProperties.ALLOWED_MODES, myModes);
}
protected void doTitle(Portlet portlet, RenderRequest request, RenderResponse response) throws IOException, PortletException {
Portlet por = (Portlet)portlet;
if (por instanceof GenericPortlet) {
GenericPortlet genPortlet = ((GenericPortlet) portlet);
if (genPortlet.getPortletConfig() == null) throw new PortletException("Unable to get PortletConfig from Portlet");
ResourceBundle resBundle = genPortlet.getPortletConfig().getResourceBundle(request.getLocale());
String title = resBundle.getString("javax.portlet.title");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(title);
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
super.doGet(req, res);
}
protected void doPut(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
super.doPut(req, res);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
super.doPost(req, res);
}
protected void doTrace(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
super.doTrace(req, res);
}
protected void doDelete(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
super.doDelete(req, res);
}
protected void redirect(HttpServletRequest servletRequest,
HttpServletResponse servletResponse,
ActionRequest actionRequest,
ActionResponse actionResponse, PortalContext portalContext)
throws IOException {
if (actionResponse instanceof ActionResponseImpl) {
ActionResponseImpl aResponse = (ActionResponseImpl) actionResponse;
String location = aResponse.getRedirectLocation();
if (location != null) {
javax.servlet.http.HttpServletResponse redirectResponse = servletResponse;
while (redirectResponse instanceof javax.servlet.http.HttpServletResponseWrapper) {
redirectResponse = (javax.servlet.http.HttpServletResponse)
((javax.servlet.http.HttpServletResponseWrapper) redirectResponse).getResponse();
}
log.debug("redirecting to location= " + location);
redirectResponse.sendRedirect(location);
}
}
}
/**
* Record the fact that a servlet context attribute was added.
*
* @param event The session attribute event
*/
public void attributeAdded(HttpSessionBindingEvent event) {
log.debug("attributeAdded('" + event.getSession().getId() + "', '" +
event.getName() + "', '" + event.getValue() + "')");
}
/**
* Record the fact that a servlet context attribute was removed.
*
* @param event The session attribute event
*/
public void attributeRemoved(HttpSessionBindingEvent event) {
log.debug("attributeRemoved('" + event.getSession().getId() + "', '" +
event.getName() + "', '" + event.getValue() + "')");
}
/**
* Record the fact that a servlet context attribute was replaced.
*
* @param event The session attribute event
*/
public void attributeReplaced(HttpSessionBindingEvent event) {
log.debug("attributeReplaced('" + event.getSession().getId() + "', '" +
event.getName() + "', '" + event.getValue() + "')");
}
/**
* Record the fact that a session has been created.
*
* @param event The session event
*/
public void sessionCreated(HttpSessionEvent event) {
log.debug("sessionCreated('" + event.getSession().getId() + "')");
//sessionManager.sessionCreated(event);
}
/**
* Record the fact that a session has been destroyed.
*
* @param event The session event
*/
public void sessionDestroyed(HttpSessionEvent event) {
//sessionManager.sessionDestroyed(event);
//loginService.sessionDestroyed(event.getSession());
log.debug("sessionDestroyed('" + event.getSession().getId() + "')");
//HttpSession session = event.getSession();
//User user = (User) session.getAttribute(SportletProperties.PORTLET_USER);
//System.err.println("user : " + user.getUserID() + " expired!");
//PortletLayoutEngine engine = PortletLayoutEngine.getDefault();
//engine.removeUser(user);
//engine.logoutPortlets(event);
}
/**
* Record the fact that a session has been created.
*
* @param event The session event
*/
public void sessionDidActivate(HttpSessionEvent event) {
log.debug("sessionDidActivate('" + event.getSession().getId() + "')");
//sessionManager.sessionCreated(event);
}
/**
* Record the fact that a session has been destroyed.
*
* @param event The session event
*/
public void sessionWillPassivate(HttpSessionEvent event) {
//sessionManager.sessionDestroyed(event);
//loginService.sessionDestroyed(event.getSession());
log.debug("sessionWillPassivate('" + event.getSession().getId() + "')");
//HttpSession session = event.getSession();
//User user = (User) session.getAttribute(SportletProperties.USER);
//System.err.println("user : " + user.getUserID() + " expired!");
//PortletLayoutEngine engine = PortletLayoutEngine.getDefault();
//engine.removeUser(user);
//engine.logoutPortlets(event);
}
} |
package com.couchbase.lite;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* An unsaved Couchbase Lite Document Revision.
*/
public class UnsavedRevision extends Revision {
private Map<String, Object> properties;
/**
* Constructor
* @exclude
*/
@InterfaceAudience.Private
/* package */ protected UnsavedRevision(Document document, SavedRevision parentRevision) {
super(document);
if (parentRevision == null) {
parentRevID = null;
} else {
parentRevID = parentRevision.getId();
}
Map<String, Object> parentRevisionProperties;
if (parentRevision == null) {
parentRevisionProperties = null;
} else {
parentRevisionProperties = parentRevision.getProperties();
}
if (parentRevisionProperties == null) {
properties = new HashMap<String, Object>();
properties.put("_id", document.getId());
if (parentRevID != null) {
properties.put("_rev", parentRevID);
}
}
else {
properties = new HashMap<String, Object>(parentRevisionProperties);
}
}
/**
* Set whether this revision is a deletion or not (eg, marks doc as deleted)
*/
@InterfaceAudience.Public
public void setIsDeletion(boolean isDeletion) {
if (isDeletion == true) {
properties.put("_deleted", true);
}
else {
properties.remove("_deleted");
}
}
/**
* Get the id of the owning document. In the case of an unsaved revision, may return null.
* @return
*/
@Override
@InterfaceAudience.Public
public String getId() {
return null;
}
/**
* Set the properties for this revision
*/
@InterfaceAudience.Public
public void setProperties(Map<String,Object> properties) {
this.properties = properties;
}
/**
* Saves the new revision to the database.
*
* This will throw an exception with a 412 error if its parent (the revision it was created from)
* is not the current revision of the document.
*
* Afterwards you should use the returned Revision instead of this object.
*
* @return A new Revision representing the saved form of the revision.
* @throws CouchbaseLiteException
*/
@InterfaceAudience.Public
public SavedRevision save() throws CouchbaseLiteException {
boolean allowConflict = false;
return document.putProperties(properties, parentRevID, allowConflict);
}
/**
* A special variant of -save: that always adds the revision, even if its parent is not the
* current revision of the document.
*
* This can be used to resolve conflicts, or to create them. If you're not certain that's what you
* want to do, you should use the regular -save: method instead.
*/
@InterfaceAudience.Public
public SavedRevision save(boolean allowConflict) throws CouchbaseLiteException {
return document.putProperties(properties, parentRevID, allowConflict);
}
/**
* Deletes any existing attachment with the given name.
* The attachment will be deleted from the database when the revision is saved.
* @param name The attachment name.
*/
@InterfaceAudience.Public
public void removeAttachment(String name) {
addAttachment(null, name);
}
/**
* Sets the userProperties of the Revision.
* Set replaces all properties except for those with keys prefixed with '_'.
*/
@InterfaceAudience.Public
public void setUserProperties(Map<String,Object> userProperties) {
Map<String, Object> newProps = new HashMap<String, Object>();
newProps.putAll(userProperties);
for (String key : properties.keySet()) {
if (key.startsWith("_")) {
newProps.put(key, properties.get(key)); // Preserve metadata properties
}
}
properties = newProps;
}
/**
* Sets the attachment with the given name. The Attachment data will be written to the Database when the Revision is saved.
*
* @param name The name of the Attachment to set.
* @param contentType The content-type of the Attachment.
* @param contentStream The Attachment content. The InputStream will be closed after it is no longer needed.
*/
@InterfaceAudience.Public
public void setAttachment(String name, String contentType, InputStream contentStream) {
Attachment attachment = new Attachment(contentStream, contentType);
addAttachment(attachment, name);
}
/**
* Sets the attachment with the given name. The Attachment data will be written to the Database when the Revision is saved.
*
* @param name The name of the Attachment to set.
* @param contentType The content-type of the Attachment.
* @param contentStreamURL The URL that contains the Attachment content.
*/
@InterfaceAudience.Public
public void setAttachment(String name, String contentType, URL contentStreamURL) {
try {
InputStream inputStream = contentStreamURL.openStream();
setAttachment(name, contentType, inputStream);
} catch (IOException e) {
Log.e(Database.TAG, "Error opening stream for url: " + contentStreamURL);
throw new RuntimeException(e);
}
}
@Override
@InterfaceAudience.Public
public Map<String, Object> getProperties() {
return properties;
}
@Override
@InterfaceAudience.Public
public SavedRevision getParent() {
if (parentRevID == null || parentRevID.length() == 0) {
return null;
}
return document.getRevision(parentRevID);
}
@Override
@InterfaceAudience.Public
public String getParentId() {
return parentRevID;
}
@Override
@InterfaceAudience.Public
public List<SavedRevision> getRevisionHistory() throws CouchbaseLiteException {
// (Don't include self in the array, because this revision doesn't really exist yet)
SavedRevision parent = getParent();
return parent != null ? parent.getRevisionHistory() : new ArrayList<SavedRevision>();
}
/**
* Creates or updates an attachment.
* The attachment data will be written to the database when the revision is saved.
* @param attachment A newly-created Attachment (not yet associated with any revision)
* @param name The attachment name.
*/
@InterfaceAudience.Private
/* package */ void addAttachment(Attachment attachment, String name) {
Map<String, Object> attachments = (Map<String, Object>) properties.get("_attachments");
if (attachments == null) {
attachments = new HashMap<String, Object>();
}
attachments.put(name, attachment);
properties.put("_attachments", attachments);
if (attachment != null) {
attachment.setName(name);
attachment.setRevision(this);
}
}
} |
package org.gridsphere.provider.portletui.tags;
import org.gridsphere.portlet.impl.SportletProperties;
import org.gridsphere.provider.portletui.beans.CalendarBean;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.portlet.RenderResponse;
/**
* A <code>TextFieldTag</code> represents a text field element
*/
public class CalendarTag extends BaseComponentTag {
protected CalendarBean calendarBean = null;
protected int size = 0;
protected int maxlength = 0;
/**
* Returns the (html) size of the field
*
* @return size of the field
*/
public int getSize() {
return size;
}
/**
* Sets the (html) size of the field
*
* @param size size of the field
*/
public void setSize(int size) {
this.size = size;
}
/**
* Returns the (html) max length of the field
*
* @return the max length of the field
*/
public int getMaxlength() {
return maxlength;
}
/**
* Sets the (html) max length of the field
*
* @param maxlength the max length of the field
*/
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public int doStartTag() throws JspException {
if (!beanId.equals("")) {
calendarBean = (CalendarBean) getTagBean();
if (calendarBean == null) {
//log.debug("Creating new text field bean");
calendarBean = new CalendarBean();
if (maxlength != 0) calendarBean.setMaxLength(maxlength);
if (size != 0) calendarBean.setSize(size);
this.setBaseComponentBean(calendarBean);
} else {
//log.debug("Using existing text field bean");
if (maxlength != 0) calendarBean.setMaxLength(maxlength);
if (size != 0) calendarBean.setSize(size);
this.updateBaseComponentBean(calendarBean);
}
} else {
calendarBean = new CalendarBean();
if (maxlength != 0) calendarBean.setMaxLength(maxlength);
if (size != 0) calendarBean.setSize(size);
this.setBaseComponentBean(calendarBean);
}
RenderResponse res = (RenderResponse)pageContext.getAttribute(SportletProperties.RENDER_RESPONSE, PageContext.REQUEST_SCOPE);
calendarBean.setRenderResponse(res);
calendarBean.setId("cal_" + pageContext.findAttribute(SportletProperties.COMPONENT_ID) + "_" + beanId);
try {
JspWriter out = pageContext.getOut();
out.print(calendarBean.toStartString());
} catch (Exception e) {
throw new JspException(e.getMessage());
}
return SKIP_BODY;
}
} |
package com.datastax.demo.xml.dao;
import com.datastax.demo.utils.PropertyHelper;
import com.datastax.demo.xml.model.Actor;
import com.datastax.demo.xml.model.Movie;
import com.datastax.driver.core.*;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MovieDao
{
private static final Logger logger = LoggerFactory.getLogger(MovieDao.class);
private static final String CONTACT_POINTS = "contactPoints";
private static final String LOCALHOST = "localhost";
private static final String DELIMITER = ",";
private static final String KEYSPACE = "datastax_xml_demo";
private static final String MOVIES_TABLE = KEYSPACE + ".movies";
private static final String ACTOR_UDT = "actor";
private static final String TITLE = "title";
private static final String YEAR = "year";
private static final String DIRECTED_BY = "directed_by";
private static final String GENRES = "genres";
private static final String CAST = "cast";
private static final String ACTOR_FIRST_NAME = "first_name";
private static final String ACTOR_LAST_NAME = "last_name";
private static final String SOURCE_BYTES = "source_bytes";
private static final String INSERT_MOVIE = String.format(
"INSERT INTO %s (title, year, directed_by, genres, cast, source_bytes) VALUES (?,?,?,?,?,?);", MOVIES_TABLE);
private static final String SELECT_MOVIE = String.format(
"SELECT title, year, directed_by, genres, cast FROM %s WHERE title = ? and year = ?", MOVIES_TABLE);
private Session session;
private PreparedStatement insertMoviePrep;
private PreparedStatement selectMoviePrep;
private UserType actorUDT;
public MovieDao(String[] contactPoints)
{
super();
prepareDao(contactPoints);
}
public ResultSetFuture insertMovieAsync(Movie movie)
{
List<UDTValue> actorUdtValues = null;
List<Actor> actors = movie.getCast();
if (actors != null)
{
actorUdtValues = new ArrayList<>();
for (Actor actor : movie.getCast())
{
UDTValue actorUdtValue = actorUDT.newValue()
.setString(ACTOR_FIRST_NAME, actor.getFirstName())
.setString(ACTOR_LAST_NAME, actor.getLastName());
actorUdtValues.add(actorUdtValue);
}
}
Integer year = movie.getYear();
int yearUnboxed = (year == null) ? Integer.MIN_VALUE : year;
BoundStatement bound = insertMoviePrep.bind()
.setString(TITLE, movie.getTitle())
.setInt(YEAR, yearUnboxed)
.setList(DIRECTED_BY, movie.getDirectedBy())
.setList(GENRES, movie.getGenres())
.setList(CAST, actorUdtValues)
.setBytes(SOURCE_BYTES, ByteBuffer.wrap(movie.getSourceBytes()));
return session.executeAsync(bound);
}
public Movie selectMovie(String title, int year)
{
BoundStatement bound = selectMoviePrep.bind()
.setString(0, title)
.setInt(1, year);
ResultSet resultSet = session.execute(bound);
Row row = resultSet.one();
Movie movie = null;
if (row != null)
{
String rTitle = row.getString(TITLE);
int rYear = row.getInt(YEAR);
List<String> directedBy = row.getList(DIRECTED_BY, String.class);
List<String> genres = row.getList(GENRES, String.class);
List<UDTValue> cast = row.getList(CAST, UDTValue.class);
List<Actor> actors = new ArrayList<>();
for (UDTValue actorUDT : cast)
{
String actorFirstName = actorUDT.getString(ACTOR_FIRST_NAME);
String actorLastName = actorUDT.getString(ACTOR_LAST_NAME);
Actor actor = new Actor(actorFirstName, actorLastName);
actors.add(actor);
}
ByteBuffer sourceByteBuffer = row.getBytes(SOURCE_BYTES);
movie = new Movie(rTitle, rYear, directedBy, genres, actors, sourceByteBuffer.array());
}
return movie;
}
public List<Movie> searchByGenre(String genre)
{
return null;
}
// public List<Vehicle> searchVehiclesByLonLatAndDistance(int distance, LatLong latLong)
// String cql = "select * from " + currentLocationTable
// + " where solr_query = '{\"q\": \"*:*\", \"fq\": \"{!geofilt sfield=lat_long pt="
// + latLong.getLat() + "," + latLong.getLon() + " d=" + distance + "}\"}' limit 1000";
// ResultSet resultSet = session.execute(cql);
// List<Vehicle> vehicleMovements = new ArrayList<Vehicle>();
// List<Row> all = resultSet.all();
// for (Row row : all)
// Date date = row.getTimestamp("date");
// String vehicleId = row.getString("vehicle");
// String lat_long = row.getString("lat_long");
// String tile = row.getString("tile2");
// Double lat = Double.parseDouble(lat_long.substring(0, lat_long.lastIndexOf(",")));
// Double lng = Double.parseDouble(lat_long.substring(lat_long.lastIndexOf(",") + 1));
// Vehicle vehicle = new Vehicle(vehicleId, date, new LatLong(lat, lng), tile, "");
// vehicleMovements.add(vehicle);
// return vehicleMovements;
// public List<Vehicle> getVehiclesByTile(String tile)
// String cql = "select * from " + currentLocationTable + " where solr_query = '{\"q\": \"tile1: " + tile + "\"}' limit 1000";
// ResultSet resultSet = session.execute(cql);
// List<Vehicle> vehicleMovements = new ArrayList<Vehicle>();
// List<Row> all = resultSet.all();
// for (Row row : all)
// Date date = row.getTimestamp("date");
// String vehicleId = row.getString("vehicle");
// String lat_long = row.getString("lat_long");
// String tile1 = row.getString("tile1");
// String tile2 = row.getString("tile2");
// Double lat = Double.parseDouble(lat_long.substring(0, lat_long.lastIndexOf(",")));
// Double lng = Double.parseDouble(lat_long.substring(lat_long.lastIndexOf(",") + 1));
// Vehicle vehicle = new Vehicle(vehicleId, date, new LatLong(lat, lng), tile1, tile2);
// vehicleMovements.add(vehicle);
// return vehicleMovements;
private void prepareDao(String[] contactPoints)
{
logger.debug(String.format("Preparing MovieDao with contact points: %s.", Arrays.toString(contactPoints)));
Cluster cluster = Cluster.builder()
.withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
.addContactPoints(contactPoints).build();
session = cluster.connect();
insertMoviePrep = session.prepare(INSERT_MOVIE);
selectMoviePrep = session.prepare(SELECT_MOVIE);
actorUDT = session.getCluster().getMetadata().getKeyspace(KEYSPACE).getUserType(ACTOR_UDT);
}
public static MovieDao build()
{
String contactPointsStr = PropertyHelper.getProperty(CONTACT_POINTS, LOCALHOST);
String[] contactPoints = contactPointsStr.split(DELIMITER);
return new MovieDao(contactPoints);
}
} |
package com.davidsoergel.stats;
import com.davidsoergel.dsutils.MathUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Multinomial<T>//extends HashMap<Double, T>
{
MultinomialDistribution dist = new MultinomialDistribution();
List<T> elements = new ArrayList<T>();
public Multinomial()
{
}
public Multinomial(T[] keys, Map<T, Double> values) throws DistributionException
{
for (T k : keys)
{
put(k, values.get(k));
}
normalize();
}
public void put(T obj, double prob) throws DistributionException//throws DistributionException
{
if (elements.contains(obj))
{
dist.update(elements.indexOf(obj), prob);
//dist.normalize();
//throw new DistributionException("Can't add the same element to a Multinomial twice");// don't bother to handle this properly
}
else
{
elements.add(obj);
dist.add(prob);
//dist.normalize();
}
}
public void normalize() throws DistributionException
{
dist.normalize();
}
public boolean isAlreadyNormalized() throws DistributionException
{
return dist.isAlreadyNormalized();
}
public double get(T obj) throws DistributionException//throws DistributionException
{
int i = elements.indexOf(obj);
if (i == -1)
{
//return 0;
//return Double.NaN;
throw new DistributionException("No probability known: " + obj);
}
return dist.probs[i];
}
public List<T> getElements()
{
return elements;
}
public T sample() throws DistributionException
{
return elements.get(dist.sample());
}
public Multinomial<T> clone()
{
Multinomial<T> result = new Multinomial<T>();
result.dist = new MultinomialDistribution(dist);
result.elements = new ArrayList<T>(elements);
return result;
}
public int size()
{
return elements.size();
}
public void mixIn(Multinomial<T> uniform, double smoothFactor) throws DistributionException
{
for (int c = 0; c < elements.size(); c++)
{
dist.probs[c] = (dist.probs[c] * (1. - smoothFactor)) + uniform.get(elements.get(c)) * smoothFactor;
}
}
public double KLDivergenceToThisFrom(Multinomial<T> belief) throws DistributionException
{
double divergence = 0;
for (T key : elements)
{
double p = get(key);
double q = belief.get(key);
if (p == 0 || q == 0)
{
throw new DistributionException("Can't compute KL divergence: distributions not smoothed");
}
divergence += p * MathUtils.approximateLog(p / q);
if (Double.isNaN(divergence))
{
throw new DistributionException("Got NaN when computing KL divergence.");
}
}
return divergence;
}
public static <T> Multinomial<T> mixture(Multinomial<T> basis, Multinomial<T> bias, double mixingProportion)
throws DistributionException
{
Multinomial<T> result = new Multinomial<T>();
// these may be slow, remove later?
assert basis.isAlreadyNormalized();
assert bias.isAlreadyNormalized();
assert basis.getElements().size() == bias.getElements().size();
for (T key : basis.getElements())
{
double p = (1. - mixingProportion) * basis.get(key) + mixingProportion * bias.get(key);
result.put(key, p);
}
assert result.isAlreadyNormalized();
return result;
}
} |
package com.defano.jmonet.tools;
import com.defano.jmonet.canvas.Scratch;
import com.defano.jmonet.model.PaintToolType;
import com.defano.jmonet.tools.base.AbstractPathTool;
import com.defano.jmonet.tools.util.CursorFactory;
import java.awt.*;
import java.awt.geom.Line2D;
/**
* Tool for drawing a single-pixel, black, free-form path on the canvas.
*/
public class PencilTool extends AbstractPathTool {
private boolean isErasing = false;
public PencilTool() {
super(PaintToolType.PENCIL);
setToolCursor(CursorFactory.makePencilCursor());
}
/** {@inheritDoc} */
@Override
protected void startPath(Scratch scratch, Stroke stroke, Paint fillPaint, Point initialPoint) {
Color pixel = new Color(getCanvas().getCanvasImage().getRGB(initialPoint.x, initialPoint.y), true);
isErasing = pixel.getAlpha() >= 128;
renderStroke(scratch, fillPaint, new Line2D.Float(initialPoint, initialPoint));
}
/** {@inheritDoc} */
@Override
protected void addPoint(Scratch scratch, Stroke stroke, Paint fillPaint, Point lastPoint, Point thisPoint) {
renderStroke(scratch, fillPaint, new Line2D.Float(lastPoint, thisPoint));
}
private void renderStroke(Scratch scratch, Paint fillPaint, Line2D stroke) {
Graphics2D g = isErasing ?
scratch.getRemoveScratchGraphics(this, new BasicStroke(1), stroke) :
scratch.getAddScratchGraphics(this, new BasicStroke(1), stroke);
g.setStroke(new BasicStroke(1));
g.setPaint(fillPaint);
g.draw(stroke);
}
} |
package org.pentaho.di.job.entries.ssh2get;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.integerValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.io.FileOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.vfs.FileType;
import org.w3c.dom.Node;
import org.pentaho.di.core.vfs.KettleVFS;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import com.trilead.ssh2.SFTPv3DirectoryEntry;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.SFTPv3Client;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.SFTPv3FileHandle;
import com.trilead.ssh2.SFTPv3FileAttributes;
import com.trilead.ssh2.HTTPProxyData;
/**
* This defines a SSH2 GET job entry.
*
* @author Samatar
* @since 17-12-2007
*
*/
public class JobEntrySSH2GET extends JobEntryBase implements Cloneable, JobEntryInterface
{
LogWriter log = LogWriter.getInstance();
private String serverName;
private String userName;
private String password;
private String serverPort;
private String ftpDirectory;
private String localDirectory;
private String wildcard;
private boolean onlyGettingNewFiles; /* Don't overwrite files */
private boolean usehttpproxy;
private String httpProxyHost;
private String httpproxyport;
private String httpproxyusername;
private String httpProxyPassword;
private boolean publicpublickey;
private String keyFilename;
private String keyFilePass;
private boolean useBasicAuthentication;
private String afterFtpPut;
private String destinationfolder;
private boolean createdestinationfolder;
private boolean cachehostkey;
private int timeout;
boolean createtargetfolder;
boolean includeSubFolders;
static KnownHosts database = new KnownHosts();
int nbfilestoget=0;
int nbgot=0;
int nbrerror=0;
public JobEntrySSH2GET(String n)
{
super(n, "");
serverName=null;
publicpublickey=false;
keyFilename=null;
keyFilePass=null;
usehttpproxy=false;
httpProxyHost=null;
httpproxyport=null;
httpproxyusername=null;
httpProxyPassword=null;
serverPort="22";
useBasicAuthentication=false;
afterFtpPut="do_nothing";
destinationfolder=null;
includeSubFolders=false;
createdestinationfolder=false;
createtargetfolder=false;
cachehostkey=false;
timeout=0;
setID(-1L);
setJobEntryType(JobEntryType.SSH2_GET);
}
public JobEntrySSH2GET()
{
this("");
}
public JobEntrySSH2GET(JobEntryBase jeb)
{
super(jeb);
}
public Object clone()
{
JobEntrySSH2GET je = (JobEntrySSH2GET) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("servername", serverName));
retval.append(" ").append(XMLHandler.addTagValue("username", userName));
retval.append(" ").append(XMLHandler.addTagValue("password", password));
retval.append(" ").append(XMLHandler.addTagValue("serverport", serverPort));
retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory));
retval.append(" ").append(XMLHandler.addTagValue("localdirectory", localDirectory));
retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard));
retval.append(" ").append(XMLHandler.addTagValue("only_new", onlyGettingNewFiles));
retval.append(" ").append(XMLHandler.addTagValue("usehttpproxy", usehttpproxy));
retval.append(" ").append(XMLHandler.addTagValue("httpproxyhost", httpProxyHost));
retval.append(" ").append(XMLHandler.addTagValue("httpproxyport", httpproxyport));
retval.append(" ").append(XMLHandler.addTagValue("httpproxyusername", httpproxyusername));
retval.append(" ").append(XMLHandler.addTagValue("httpproxypassword", httpProxyPassword));
retval.append(" ").append(XMLHandler.addTagValue("publicpublickey", publicpublickey));
retval.append(" ").append(XMLHandler.addTagValue("keyfilename", keyFilename));
retval.append(" ").append(XMLHandler.addTagValue("keyfilepass", keyFilePass));
retval.append(" ").append(XMLHandler.addTagValue("usebasicauthentication", useBasicAuthentication));
retval.append(" ").append(XMLHandler.addTagValue("afterftpput", afterFtpPut));
retval.append(" ").append(XMLHandler.addTagValue("destinationfolder", destinationfolder));
retval.append(" ").append(XMLHandler.addTagValue("createdestinationfolder", createdestinationfolder));
retval.append(" ").append(XMLHandler.addTagValue("cachehostkey", cachehostkey));
retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout));
retval.append(" ").append(XMLHandler.addTagValue("createtargetfolder", createtargetfolder));
retval.append(" ").append(XMLHandler.addTagValue("includeSubFolders", includeSubFolders));
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases, slaveServers);
serverName = XMLHandler.getTagValue(entrynode, "servername");
userName = XMLHandler.getTagValue(entrynode, "username");
password = XMLHandler.getTagValue(entrynode, "password");
serverPort = XMLHandler.getTagValue(entrynode, "serverport");
ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory");
localDirectory = XMLHandler.getTagValue(entrynode, "localdirectory");
wildcard = XMLHandler.getTagValue(entrynode, "wildcard");
onlyGettingNewFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "only_new") );
usehttpproxy = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "usehttpproxy") );
httpProxyHost = XMLHandler.getTagValue(entrynode, "httpproxyhost");
httpproxyport = XMLHandler.getTagValue(entrynode, "httpproxyport");
httpproxyusername = XMLHandler.getTagValue(entrynode, "httpproxyusername");
httpProxyPassword = XMLHandler.getTagValue(entrynode, "httpproxypassword");
publicpublickey = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "publicpublickey") );
keyFilename = XMLHandler.getTagValue(entrynode, "keyfilename");
keyFilePass = XMLHandler.getTagValue(entrynode, "keyfilepass");
useBasicAuthentication = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "usebasicauthentication") );
afterFtpPut = XMLHandler.getTagValue(entrynode, "afterftpput");
destinationfolder = XMLHandler.getTagValue(entrynode, "destinationfolder");
createdestinationfolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "createdestinationfolder") );
cachehostkey = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "cachehostkey") );
timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 0);
createtargetfolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "createtargetfolder") );
includeSubFolders = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "includeSubFolders") );
}
catch(KettleXMLException xe)
{
throw new KettleXMLException(Messages.getString("JobSSH2GET.Log.UnableLoadXML", xe.getMessage()));
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases, slaveServers);
serverName = rep.getJobEntryAttributeString(id_jobentry, "servername");
userName = rep.getJobEntryAttributeString(id_jobentry, "username");
password = rep.getJobEntryAttributeString(id_jobentry, "password");
serverPort =rep.getJobEntryAttributeString(id_jobentry, "serverport");
ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory");
localDirectory = rep.getJobEntryAttributeString(id_jobentry, "localdirectory");
wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard");
onlyGettingNewFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "only_new");
usehttpproxy = rep.getJobEntryAttributeBoolean(id_jobentry, "usehttpproxy");
httpProxyHost = rep.getJobEntryAttributeString(id_jobentry, "httpproxyhost");
httpproxyusername = rep.getJobEntryAttributeString(id_jobentry, "httpproxyusername");
httpProxyPassword = rep.getJobEntryAttributeString(id_jobentry, "httpproxypassword");
publicpublickey = rep.getJobEntryAttributeBoolean(id_jobentry, "publicpublickey");
keyFilename = rep.getJobEntryAttributeString(id_jobentry, "keyfilename");
keyFilePass = rep.getJobEntryAttributeString(id_jobentry, "keyfilepass");
useBasicAuthentication = rep.getJobEntryAttributeBoolean(id_jobentry, "usebasicauthentication");
afterFtpPut = rep.getJobEntryAttributeString(id_jobentry, "afterftpput");
destinationfolder = rep.getJobEntryAttributeString(id_jobentry, "destinationfolder");
createdestinationfolder = rep.getJobEntryAttributeBoolean(id_jobentry, "createdestinationfolder");
cachehostkey = rep.getJobEntryAttributeBoolean(id_jobentry, "cachehostkey");
timeout = (int)rep.getJobEntryAttributeInteger(id_jobentry, "timeout");
createtargetfolder = rep.getJobEntryAttributeBoolean(id_jobentry, "createtargetfolder");
includeSubFolders = rep.getJobEntryAttributeBoolean(id_jobentry, "includeSubFolders");
}
catch(KettleException dbe)
{
throw new KettleException(Messages.getString("JobSSH2GET.Log.UnableLoadRep",""+id_jobentry,dbe.getMessage()));
}
}
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "servername", serverName);
rep.saveJobEntryAttribute(id_job, getID(), "username", userName);
rep.saveJobEntryAttribute(id_job, getID(), "password", password);
rep.saveJobEntryAttribute(id_job, getID(), "serverport", serverPort);
rep.saveJobEntryAttribute(id_job, getID(), "ftpdirectory", ftpDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "localdirectory", localDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard);
rep.saveJobEntryAttribute(id_job, getID(), "only_new", onlyGettingNewFiles);
rep.saveJobEntryAttribute(id_job, getID(), "usehttpproxy", usehttpproxy);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxyhost", httpProxyHost);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxyport", httpproxyport);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxyusername", httpproxyusername);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxypassword", httpProxyPassword);
rep.saveJobEntryAttribute(id_job, getID(), "publicpublickey", publicpublickey);
rep.saveJobEntryAttribute(id_job, getID(), "keyfilename", keyFilename);
rep.saveJobEntryAttribute(id_job, getID(), "keyfilepass", keyFilePass);
rep.saveJobEntryAttribute(id_job, getID(), "usebasicauthentication", useBasicAuthentication);
rep.saveJobEntryAttribute(id_job, getID(), "afterftpput", afterFtpPut);
rep.saveJobEntryAttribute(id_job, getID(), "destinationfolder", destinationfolder);
rep.saveJobEntryAttribute(id_job, getID(), "createdestinationfolder", createdestinationfolder);
rep.saveJobEntryAttribute(id_job, getID(), "cachehostkey", cachehostkey);
rep.saveJobEntryAttribute(id_job, getID(), "timeout", timeout);
rep.saveJobEntryAttribute(id_job, getID(), "createtargetfolder", createtargetfolder);
rep.saveJobEntryAttribute(id_job, getID(), "includeSubFolders", includeSubFolders);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("JobSSH2GET.Log.UnableSaveRep",""+id_job,dbe.getMessage()));
}
}
/**
* @return Returns the directory.
*/
public String getFtpDirectory()
{
return ftpDirectory;
}
/**
* @param directory The directory to set.
*/
public void setFtpDirectory(String directory)
{
this.ftpDirectory = directory;
}
/**
* @return Returns the password.
*/
public String getPassword()
{
return password;
}
/**
* @param password The password to set.
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* @return Returns the afterftpput.
*/
public String getAfterFTPPut()
{
return afterFtpPut;
}
/**
* @param afterFtpPut The action after (FTP/SSH) transfer to execute
*/
public void setAfterFTPPut(String afterFtpPut)
{
this.afterFtpPut = afterFtpPut;
}
/**
* @param proxyPassword The httpproxypassword to set.
*/
public void setHTTPProxyPassword(String proxyPassword)
{
this.httpProxyPassword = proxyPassword;
}
/**
* @return Returns the password.
*/
public String getHTTPProxyPassword()
{
return httpProxyPassword;
}
/**
* @param keyFilePass The key file pass to set.
*/
public void setKeyFilePass(String keyFilePass)
{
this.keyFilePass = keyFilePass;
}
/**
* @return Returns the key file pass.
*/
public String getKeyFilePass()
{
return keyFilePass;
}
/**
* @return Returns the serverName.
*/
public String getServerName()
{
return serverName;
}
/**
* @param serverName The serverName to set.
*/
public void setServerName(String serverName)
{
this.serverName = serverName;
}
/**
* @param proxyhost The httpproxyhost to set.
*/
public void setHTTPProxyHost(String proxyhost)
{
this.httpProxyHost = proxyhost;
}
/**
* @return Returns the HTTP proxy host.
*/
public String getHTTPProxyHost()
{
return httpProxyHost;
}
/**
* @param keyfilename The key filename to set.
*/
public void setKeyFilename(String keyfilename)
{
this.keyFilename = keyfilename;
}
/**
* @return Returns the key filename.
*/
public String getKeyFilename()
{
return keyFilename;
}
/**
* @return Returns the userName.
*/
public String getUserName()
{
return userName;
}
/**
* @param userName The userName to set.
*/
public void setUserName(String userName)
{
this.userName = userName;
}
/**
* @param proxyusername The httpproxyusername to set.
*/
public void setHTTPProxyUsername(String proxyusername)
{
this.httpproxyusername = proxyusername;
}
/**
* @return Returns the userName.
*/
public String getHTTPProxyUsername()
{
return httpproxyusername;
}
/**
* @return Returns the wildcard.
*/
public String getWildcard()
{
return wildcard;
}
/**
* @param wildcard The wildcard to set.
*/
public void setWildcard(String wildcard)
{
this.wildcard = wildcard;
}
/**
* @return Returns the localDirectory.
*/
public String getlocalDirectory()
{
return localDirectory;
}
/**
* @param localDirectory The localDirectory to set.
*/
public void setlocalDirectory(String localDirectory)
{
this.localDirectory = localDirectory;
}
/**
* @return Returns the onlyGettingNewFiles.
*/
public boolean isOnlyGettingNewFiles()
{
return onlyGettingNewFiles;
}
/**
* @param onlyGettingNewFiles The onlyGettingNewFiles to set.
*/
public void setOnlyGettingNewFiles(boolean onlyGettingNewFiles)
{
this.onlyGettingNewFiles = onlyGettingNewFiles;
}
/**
* @param cachehostkeyin The cachehostkey to set.
*/
public void setCacheHostKey(boolean cachehostkeyin)
{
this.cachehostkey = cachehostkeyin;
}
/**
* @return Returns the cachehostkey.
*/
public boolean isCacheHostKey()
{
return cachehostkey;
}
/**
* @param httpproxy The usehttpproxy to set.
*/
public void setUseHTTPProxy(boolean httpproxy)
{
this.usehttpproxy = httpproxy;
}
/**
* @return Returns the usehttpproxy.
*/
public boolean isUseHTTPProxy()
{
return usehttpproxy;
}
/**
* @return Returns the use basic authentication flag.
*/
public boolean isUseBasicAuthentication()
{
return useBasicAuthentication;
}
/**
* @param useBasicAuthentication The use basic authentication flag to set.
*/
public void setUseBasicAuthentication(boolean useBasicAuthentication)
{
this.useBasicAuthentication = useBasicAuthentication;
}
/**
* @param includeSubFolders The include sub folders flag to set.
*/
public void setIncludeSubFolders(boolean includeSubFolders)
{
this.includeSubFolders = includeSubFolders;
}
/**
* @return Returns the include sub folders flag.
*/
public boolean isIncludeSubFolders()
{
return includeSubFolders;
}
/**
* @param createdestinationfolderin The createdestinationfolder to set.
*/
public void setCreateDestinationFolder(boolean createdestinationfolderin)
{
this.createdestinationfolder = createdestinationfolderin;
}
/**
* @return Returns the createdestinationfolder.
*/
public boolean isCreateDestinationFolder()
{
return createdestinationfolder;
}
/**
* @return Returns the CreateTargetFolder.
*/
public boolean isCreateTargetFolder()
{
return createtargetfolder;
}
/**
* @param createtargetfolderin The createtargetfolder to set.
*/
public void setCreateTargetFolder(boolean createtargetfolderin)
{
this.createtargetfolder = createtargetfolderin;
}
/**
* @param publickey The publicpublickey to set.
*/
public void setUsePublicKey(boolean publickey)
{
this.publicpublickey = publickey;
}
/**
* @return Returns the usehttpproxy.
*/
public boolean isUsePublicKey()
{
return publicpublickey;
}
public String getServerPort() {
return serverPort;
}
public void setServerPort(String serverPort) {
this.serverPort = serverPort;
}
public void setHTTPProxyPort(String proxyport) {
this.httpproxyport = proxyport;
}
public String getHTTPProxyPort() {
return httpproxyport;
}
public void setDestinationFolder(String destinationfolderin) {
this.destinationfolder = destinationfolderin;
}
public String getDestinationFolder() {
return destinationfolder;
}
/**
* @param timeout The timeout to set.
*/
public void setTimeout(int timeout)
{
this.timeout = timeout;
}
/**
* @return Returns the timeout.
*/
public int getTimeout()
{
return timeout;
}
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = previousResult;
result.setResult( false );
if(log.isRowLevel()) log.logRowlevel(toString(), Messages.getString("JobSSH2GET.Log.GettingFieldsValue"));
// Get real variable value
String realServerName=environmentSubstitute(serverName);
int realServerPort=Const.toInt(environmentSubstitute(serverPort),22);
String realUserName=environmentSubstitute(userName);
String realServerPassword=environmentSubstitute(password);
// Proxy Host
String realProxyHost=environmentSubstitute(httpProxyHost);
int realProxyPort=Const.toInt(environmentSubstitute(httpproxyport),22);
String realproxyUserName=environmentSubstitute(httpproxyusername);
String realProxyPassword=environmentSubstitute(httpProxyPassword);
// Key file
String realKeyFilename=environmentSubstitute(keyFilename);
String relKeyFilepass=environmentSubstitute(keyFilePass);
// target files
String realLocalDirectory=environmentSubstitute(localDirectory);
String realwildcard=environmentSubstitute(wildcard);
// Remote source
String realftpDirectory=environmentSubstitute(ftpDirectory);
// Destination folder (Move to)
String realDestinationFolder=environmentSubstitute(destinationfolder);
// Check for mandatory fields
if(log.isRowLevel()) log.logRowlevel(toString(), Messages.getString("JobSSH2GET.Log.CheckingMandatoryFields"));
boolean mandatoryok=true;
if(Const.isEmpty(realServerName))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.ServernameMissing"));
}
if(usehttpproxy)
{
if(Const.isEmpty(realProxyHost))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.HttpProxyhostMissing"));
}
}
if(publicpublickey)
{
if(Const.isEmpty(realKeyFilename))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.KeyFileMissing"));
}else
{
// Let's check if key file exists...
if(!new File(realKeyFilename).exists())
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.KeyFileNotExist"));
}
}
}
if(Const.isEmpty(realLocalDirectory))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.LocalFolderMissing"));
}else{
// Check if target folder exists...
if(!new File(realLocalDirectory).exists())
{
if(createtargetfolder)
{
// Create Target folder
if(!CreateFolder(realLocalDirectory)) mandatoryok=false;
}else
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.LocalFolderNotExists"));
}
}else{
if(!new File(realLocalDirectory).isDirectory())
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.LocalFolderNotFolder",realLocalDirectory));
}
}
}
if(afterFtpPut.equals("move_file"))
{
if(Const.isEmpty(realDestinationFolder))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.DestinatFolderMissing"));
}
}
if(mandatoryok)
{
Connection conn = null;
SFTPv3Client client = null;
boolean good=true;
try
{
// Create a connection instance
conn = getConnection(realServerName,realServerPort,realProxyHost,realProxyPort,realproxyUserName,realProxyPassword);
if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.ConnectionInstanceCreated"));
if(timeout>0)
{
// Use timeout
// Cache Host Key
if(cachehostkey) conn.connect(new SimpleVerifier(database),0,timeout*1000);
else conn.connect(null,0,timeout*1000);
}else
{
// Cache Host Key
if(cachehostkey) conn.connect(new SimpleVerifier(database));
else conn.connect();
}
// Authenticate
boolean isAuthenticated = false;
if(publicpublickey)
{
isAuthenticated=conn.authenticateWithPublicKey(realUserName, new File(realKeyFilename), relKeyFilepass);
}else
{
isAuthenticated=conn.authenticateWithPassword(realUserName, realServerPassword);
}
// LET'S CHECK AUTHENTICATION ...
if (isAuthenticated == false)
log.logError(toString(),Messages.getString("JobSSH2GET.Log.AuthenticationFailed"));
else
{
log.logBasic(toString(),Messages.getString("JobSSH2GET.Log.Connected",serverName,userName));
client = new SFTPv3Client(conn);
if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.ProtocolVersion",""+client.getProtocolVersion()));
// Check if ftp (source) directory exists
if(realftpDirectory!=null)
{
if (!sshDirectoryExists(client, realftpDirectory))
{
good=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.RemoteDirectoryNotExist",realftpDirectory));
}
else
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2GET.Log.RemoteDirectoryExist",realftpDirectory));
}
if(realDestinationFolder!=null)
{
// Check now destination folder
if(!sshDirectoryExists(client , realDestinationFolder))
{
if(createdestinationfolder)
{
if(!CreateRemoteFolder(client,realDestinationFolder)) good=false;
}else
{
good=false;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.DestinatFolderNotExist",realDestinationFolder));
}
}
}
if(good)
{
if(includeSubFolders)
{
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2GET.Log.RecursiveModeOn"));
copyRecursive( realftpDirectory ,realLocalDirectory, client,realwildcard);
}else{
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2GET.Log.RecursiveModeOff"));
GetFiles(realftpDirectory, realLocalDirectory,client,realwildcard);
}
if(log.isDetailed())
{
log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.Result.JobEntryEnd1"));
log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.Result.TotalFiles",""+nbfilestoget));
log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.Result.TotalFilesPut",""+nbgot));
log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.Result.TotalFilesError",""+nbrerror));
log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.Result.JobEntryEnd2"));
}
if(nbrerror==0) result.setResult(true);
}
}
}
catch (Exception e)
{
result.setNrErrors(nbrerror);
log.logError(toString(), Messages.getString("JobSSH2GET.Log.Error.ErrorFTP",e.getMessage()));
}
finally
{
if (conn!=null) conn.close();
if(client!=null) client.close();
}
}
return result;
}
private Connection getConnection(String servername,int serverport,
String proxyhost,int proxyport,String proxyusername,String proxypassword)
{
/* Create a connection instance */
Connection conn = new Connection(servername,serverport);
/* We want to connect through a HTTP proxy */
if(usehttpproxy)
{
conn.setProxyData(new HTTPProxyData(proxyhost, proxyport));
/* Now connect */
// if the proxy requires basic authentication:
if(useBasicAuthentication)
{
conn.setProxyData(new HTTPProxyData(proxyhost, proxyport, proxyusername, proxypassword));
}
}
return conn;
}
/**
* Check existence of a file
*
* @param sftpClient
* @param filename
* @return true, if file exists
* @throws Exception
*/
public boolean sshFileExists(SFTPv3Client sftpClient, String filename) {
try {
SFTPv3FileAttributes attributes = sftpClient.stat(filename);
if (attributes != null) {
return (attributes.isRegularFile());
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
/**
* Check existence of a local file
*
* @param filename
* @return true, if file exists
*/
public boolean FileExists(String filename) {
FileObject file=null;
try {
file=KettleVFS.getFileObject(filename);
if(!file.exists()) return false;
else
{
if(file.getType() == FileType.FILE) return true;
else return false;
}
} catch (Exception e) {
return false;
}
}
/**
* Checks if file is a directory
*
* @param sftpClient
* @param filename
* @return true, if filename is a directory
*/
public boolean isDirectory(SFTPv3Client sftpClient, String filename)
{
try
{
return sftpClient.stat(filename).isDirectory();
}
catch(Exception e) {}
return false;
}
/**
* Checks if a directory exists
*
* @param sftpClient
* @param directory
* @return true, if directory exists
*/
public boolean sshDirectoryExists(SFTPv3Client sftpClient, String directory) {
try {
SFTPv3FileAttributes attributes = sftpClient.stat(directory);
if (attributes != null) {
return (attributes.isDirectory());
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
/**
* Returns the file size of a file
*
* @param sftpClient
* @param filename
* @return the size of the file
* @throws Exception
*/
public long getFileSize(SFTPv3Client sftpClient, String filename) throws Exception
{
return sftpClient.stat(filename).size.longValue();
}
private boolean GetFileWildcard(String selectedfile, String wildcard)
{
Pattern pattern = null;
boolean getIt=true;
if (!Const.isEmpty(wildcard))
{
pattern = Pattern.compile(wildcard);
// First see if the file matches the regular expression!
if (pattern!=null)
{
Matcher matcher = pattern.matcher(selectedfile);
getIt = matcher.matches();
}
}
return getIt;
}
private boolean deleteOrMoveFiles(SFTPv3Client sftpClient, String filename,String destinationFolder)
{
boolean retval=false;
// Delete the file if this is needed!
if (afterFtpPut.equals("delete_file"))
{
try
{
sftpClient.rm(filename);
retval=true;
if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.DeletedFile",filename));
}catch (Exception e)
{
log.logError(toString(),Messages.getString("JobSSH2GET.Log.Error.CanNotDeleteRemoteFile",filename));
}
}
else if (afterFtpPut.equals("move_file"))
{
String DestinationFullFilename=destinationFolder+Const.FILE_SEPARATOR+filename;
try
{
sftpClient.mv(filename, DestinationFullFilename);
retval=true;
if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.DeletedFile",filename));
}catch (Exception e)
{
log.logError(toString(),Messages.getString("JobSSH2GET.Log.Error.MovedFile",filename,destinationFolder));
}
}
return retval;
}
/**
* copy a directory from the remote host to the local one.
*
* @param sourceLocation the source directory on the remote host
* @param targetLocation the target directory on the local host
* @param sftpClient is an instance of SFTPv3Client that makes SFTP client connection over SSH-2
* @return the number of files successfully copied
* @throws Exception
*/
@SuppressWarnings("unchecked")
private void GetFiles(String sourceLocation, String targetLocation,
SFTPv3Client sftpClient,String wildcardin) throws Exception
{
String sourceFolder=".";
if (sourceLocation!=null)
sourceFolder=sourceLocation + "/";
else
sourceFolder="./";
Vector<SFTPv3DirectoryEntry> filelist = sftpClient.ls(sourceFolder);
if(filelist!=null)
{
Iterator<SFTPv3DirectoryEntry> iterator = filelist.iterator();
while (iterator.hasNext())
{
SFTPv3DirectoryEntry dirEntry = iterator.next();
if (dirEntry == null) continue;
if (dirEntry.filename.equals(".")
|| dirEntry.filename.equals("..") || isDirectory(sftpClient, sourceFolder+dirEntry.filename))
continue;
if(GetFileWildcard(dirEntry.filename,wildcardin))
{
// Copy file from remote host
copyFile(sourceFolder + dirEntry.filename, targetLocation + "/" + dirEntry.filename, sftpClient);
}
}
}
}
/**
* copy a directory from the remote host to the local one recursivly.
*
* @param sourceLocation the source directory on the remote host
* @param targetLocation the target directory on the local host
* @param sftpClient is an instance of SFTPv3Client that makes SFTP client connection over SSH-2
* @return the number of files successfully copied
* @throws Exception
*/
@SuppressWarnings("unchecked")
private void copyRecursive(String sourceLocation, String targetLocation,
SFTPv3Client sftpClient,String wildcardin) throws Exception
{
String sourceFolder="";
if (sourceLocation!=null) sourceFolder=sourceLocation + "/";
if (this.isDirectory(sftpClient, sourceFolder))
{
Vector<SFTPv3DirectoryEntry> filelist = sftpClient.ls(sourceFolder);
Iterator<SFTPv3DirectoryEntry> iterator = filelist.iterator();
while (iterator.hasNext())
{
SFTPv3DirectoryEntry dirEntry = iterator.next();
if (dirEntry == null) continue;
if (dirEntry.filename.equals(".")|| dirEntry.filename.equals("..")) continue;
copyRecursive(sourceFolder + dirEntry.filename, targetLocation + "/" + dirEntry.filename, sftpClient,wildcardin);
}
}
else
{
if(GetFileWildcard(sourceFolder,wildcardin))
{
// It's a file...so let's start transferring it
copyFile(sourceFolder, targetLocation, sftpClient);
}
}
}
/**
*
* @param sourceLocation
* @param targetLocation
* @param sftpClient
* @return
*/
private void copyFile(String sourceLocation, String targetLocation, SFTPv3Client sftpClient)
{
SFTPv3FileHandle sftpFileHandle = null;
FileOutputStream fos = null;
File transferFile = null;
long remoteFileSize = -1;
boolean filecopied=true;
try
{
transferFile = new File(targetLocation);
if ((onlyGettingNewFiles == false) ||
(onlyGettingNewFiles == true) && !FileExists(transferFile.getAbsolutePath()))
{
new File(transferFile.getParent()).mkdirs();
remoteFileSize = this.getFileSize(sftpClient, sourceLocation);
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2GET.Log.ReceivingFile",sourceLocation,transferFile.getAbsolutePath(),""+remoteFileSize));
sftpFileHandle = sftpClient.openFileRO(sourceLocation);
fos = null;
long offset = 0;
fos = new FileOutputStream(transferFile);
byte[] buffer = new byte[2048];
while (true)
{
//int len = sftpClient.read(sftpFileHandle, offset,buffer, 0, buffer.length);
int len = sftpClient.read(sftpFileHandle, offset,buffer, 0, buffer.length);
if (len <= 0) break;
fos.write(buffer, 0, len);
offset += len;
}
fos.flush();
fos.close();
fos = null;
nbfilestoget++;
if (remoteFileSize > 0 && remoteFileSize != transferFile.length())
{
filecopied=false;
nbrerror++;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.Error.RemoteFileLocalDifferent",""+remoteFileSize,transferFile.length()+"","" + offset));
}
else
{
nbgot++;
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2GET.Log.RemoteFileLocalCopied",sourceLocation,transferFile+""));
}
}
// Let's now delete or move file if needed...
if(filecopied && !afterFtpPut.equals("do_nothing"))
{
deleteOrMoveFiles(sftpClient, sourceLocation,environmentSubstitute(destinationfolder));
}
}
catch (Exception e)
{
nbrerror++;
log.logError(toString(),Messages.getString("JobSSH2GET.Log.Error.WritingFile",transferFile.getAbsolutePath(),e.getMessage()));
}
finally
{
try {
if(sftpFileHandle!=null)
{
sftpClient.closeFile(sftpFileHandle);
sftpFileHandle = null;
}
if (fos != null)
try
{
fos.close();
fos = null;
}
catch (Exception ex)
{
}
}
catch(Exception e ) {}
}
}
private boolean CreateFolder(String filefolder)
{
FileObject folder=null;
try
{
folder= KettleVFS.getFileObject(filefolder);
if(!folder.exists())
{
if(createtargetfolder)
{
folder.createFolder();
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2GET.Log.FolderCreated",folder.toString()));
}
else
return false;
}
return true;
}
catch (Exception e) {
log.logError(toString(),Messages.getString("JobSSH2GET.Log.CanNotCreateFolder", folder.toString()));
}
finally {
if ( folder != null )
{
try {
folder.close();
}
catch (Exception ex ) {};
}
}
return false;
}
/**
* Create remote folder
*
* @param sftpClient
* @param foldername
* @return true, if foldername is created
*/
private boolean CreateRemoteFolder(SFTPv3Client sftpClient, String foldername)
{
LogWriter log = LogWriter.getInstance();
boolean retval=false;
if(!sshDirectoryExists(sftpClient, foldername))
{
try
{
sftpClient.mkdir(foldername, 0700);
retval=true;
if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2GET.Log.RemoteFolderCreated",foldername));
}catch (Exception e)
{
log.logError(toString(), Messages.getString("JobSSH2GET.Log.Error.CreatingRemoteFolder",foldername));
}
}
return retval;
}
public boolean evaluates()
{
return true;
}
public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) {
List<ResourceReference> references = super.getResourceDependencies(jobMeta);
if (!Const.isEmpty(serverName)) {
String realServerName = jobMeta.environmentSubstitute(serverName);
ResourceReference reference = new ResourceReference(this);
reference.getEntries().add( new ResourceEntry(realServerName, ResourceType.SERVER));
references.add(reference);
}
return references;
}
@Override
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
andValidator().validate(this, "serverName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
andValidator()
.validate(this, "localDirectory", remarks, putValidators(notBlankValidator(), fileExistsValidator())); //$NON-NLS-1$
andValidator().validate(this, "userName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
andValidator().validate(this, "password", remarks, putValidators(notNullValidator())); //$NON-NLS-1$
andValidator().validate(this, "serverPort", remarks, putValidators(integerValidator())); //$NON-NLS-1$
}
} |
package com.elmakers.mine.bukkit.wand;
import java.util.*;
import java.util.regex.Matcher;
import com.elmakers.mine.bukkit.api.spell.CastingCost;
import com.elmakers.mine.bukkit.api.spell.CostReducer;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.block.MaterialBrush;
import com.elmakers.mine.bukkit.effect.builtin.EffectRing;
import com.elmakers.mine.bukkit.magic.Mage;
import com.elmakers.mine.bukkit.magic.MagicController;
import com.elmakers.mine.bukkit.spell.BrushSpell;
import com.elmakers.mine.bukkit.spell.UndoableSpell;
import com.elmakers.mine.bukkit.utility.ColorHD;
import com.elmakers.mine.bukkit.utility.CompatibilityUtils;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import com.elmakers.mine.bukkit.utility.Messages;
import de.slikey.effectlib.util.ParticleEffect;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
public class Wand implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand {
public static Plugin metadataProvider;
public final static int INVENTORY_SIZE = 27;
public final static int HOTBAR_SIZE = 9;
public final static float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f;
public final static float DEFAULT_WAND_COLOR_MIX_WEIGHT = 1.0f;
// REMEMBER! Each of these MUST have a corresponding class in .traders, else traders will
// destroy the corresponding data.
public final static String[] PROPERTY_KEYS = {
"active_spell", "active_material",
"path",
"xp", "xp_regeneration", "xp_max",
"bound", "uses", "upgrade", "indestructible", "undroppable",
"cost_reduction", "cooldown_reduction", "effect_bubbles", "effect_color",
"effect_particle", "effect_particle_count", "effect_particle_data", "effect_particle_interval",
"effect_sound", "effect_sound_interval", "effect_sound_pitch", "effect_sound_volume",
"haste",
"health_regeneration", "hunger_regeneration",
"icon", "mode", "keep", "locked", "quiet", "force", "randomize", "rename",
"power", "overrides",
"protection", "protection_physical", "protection_projectiles",
"protection_falling", "protection_fire", "protection_explosions",
"materials", "spells"
};
public final static String[] HIDDEN_PROPERTY_KEYS = {
"id", "owner", "owner_id", "name", "description", "template",
"organize", "fill"
};
public final static String[] ALL_PROPERTY_KEYS = (String[])ArrayUtils.addAll(PROPERTY_KEYS, HIDDEN_PROPERTY_KEYS);
protected ItemStack item;
protected MagicController controller;
protected Mage mage;
// Cached state
private String id = "";
private Inventory hotbar;
private List<Inventory> inventories;
private Set<String> spells = new HashSet<String>();
private Set<String> brushes = new HashSet<String>();
private String activeSpell = "";
private String activeMaterial = "";
protected String wandName = "";
protected String description = "";
private String owner = "";
private String ownerId = "";
private String template = "";
private String path = "";
private boolean bound = false;
private boolean indestructible = false;
private boolean undroppable = false;
private boolean keep = false;
private boolean autoOrganize = false;
private boolean autoFill = false;
private boolean isUpgrade = false;
private boolean randomize = false;
private boolean rename = false;
private MaterialAndData icon = null;
private float costReduction = 0;
private float cooldownReduction = 0;
private float damageReduction = 0;
private float damageReductionPhysical = 0;
private float damageReductionProjectiles = 0;
private float damageReductionFalling = 0;
private float damageReductionFire = 0;
private float damageReductionExplosions = 0;
private float power = 0;
private boolean hasInventory = false;
private boolean locked = false;
private boolean forceUpgrade = false;
private int uses = 0;
private int xp = 0;
private int xpRegeneration = 0;
private int xpMax = 0;
private float healthRegeneration = 0;
private PotionEffect healthRegenEffect = null;
private float hungerRegeneration = 0;
private PotionEffect hungerRegenEffect = null;
private ColorHD effectColor = null;
private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT;
private float effectColorMixWeight = DEFAULT_WAND_COLOR_MIX_WEIGHT;
private ParticleEffect effectParticle = null;
private float effectParticleData = 0;
private int effectParticleCount = 0;
private int effectParticleInterval = 0;
private int effectParticleCounter = 0;
private boolean effectBubbles = false;
private EffectRing effectPlayer = null;
private Sound effectSound = null;
private int effectSoundInterval = 0;
private int effectSoundCounter = 0;
private float effectSoundVolume = 0;
private float effectSoundPitch = 0;
private float speedIncrease = 0;
private PotionEffect hasteEffect = null;
private int quietLevel = 0;
private String[] castParameters = null;
private int storedXpLevel = 0;
private int storedXp = 0;
private float storedXpProgress = 0;
// Inventory functionality
private WandMode mode = null;
private int openInventoryPage = 0;
private boolean inventoryIsOpen = false;
private Inventory displayInventory = null;
// Kinda of a hacky initialization optimization :\
private boolean suspendSave = false;
// Wand configurations
protected static Map<String, ConfigurationSection> wandTemplates = new HashMap<String, ConfigurationSection>();
public static boolean displayManaAsBar = true;
public static boolean retainLevelDisplay = true;
public static Material DefaultUpgradeMaterial = Material.NETHER_STAR;
public static Material DefaultWandMaterial = Material.BLAZE_ROD;
public static Material EnchantableWandMaterial = null;
public static boolean EnableGlow = true;
public Wand(MagicController controller, ItemStack itemStack) {
this.controller = controller;
hotbar = CompatibilityUtils.createInventory(null, 9, "Wand");
this.icon = new MaterialAndData(itemStack.getType(), (byte)itemStack.getDurability());
inventories = new ArrayList<Inventory>();
item = itemStack;
indestructible = controller.getIndestructibleWands();
loadState();
}
public Wand(MagicController controller) {
this(controller, DefaultWandMaterial, (short)0);
}
protected Wand(MagicController controller, String templateName) throws UnknownWandException {
this(controller);
suspendSave = true;
String wandName = Messages.get("wand.default_name");
String wandDescription = "";
// Check for default wand
if ((templateName == null || templateName.length() == 0) && wandTemplates.containsKey("default"))
{
templateName = "default";
}
// See if there is a template with this key
if (templateName != null && templateName.length() > 0) {
// Check for randomized/pre-enchanted wands
int level = 0;
if (templateName.contains("(")) {
String levelString = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1);
try {
level = Integer.parseInt(levelString);
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
templateName = templateName.substring(0, templateName.indexOf('('));
}
if (!wandTemplates.containsKey(templateName)) {
throw new UnknownWandException(templateName);
}
ConfigurationSection wandConfig = wandTemplates.get(templateName);
// Default to template names, override with localizations
wandName = wandConfig.getString("name", wandName);
wandName = Messages.get("wands." + templateName + ".name", wandName);
wandDescription = wandConfig.getString("description", wandDescription);
wandDescription = Messages.get("wands." + templateName + ".description", wandDescription);
// Load all properties
loadProperties(wandConfig);
// Enchant, if an enchanting level was provided
if (level > 0) {
// Account for randomized locked wands
boolean wasLocked = locked;
locked = false;
randomize(level, false);
locked = wasLocked;
}
}
setDescription(wandDescription);
setName(wandName);
// Don't randomize now if set to randomize later
// Otherwise, do this here so the description updates
if (!randomize) {
randomize();
}
setTemplate(templateName);
suspendSave = false;
saveState();
}
public Wand(MagicController controller, Material icon, short iconData) {
// This will make the Bukkit ItemStack into a real ItemStack with NBT data.
this(controller, InventoryUtils.makeReal(new ItemStack(icon, 1, iconData)));
wandName = Messages.get("wand.default_name");
updateName();
saveState();
}
public void unenchant() {
item = new ItemStack(item.getType(), 1, (short)item.getDurability());
}
public void setIcon(Material material, byte data) {
setIcon(material == null ? null : new MaterialAndData(material, data));
}
public void setIcon(MaterialAndData materialData) {
icon = materialData;
if (icon != null) {
item.setType(icon.getMaterial());
item.setDurability(icon.getData());
}
}
public void makeUpgrade() {
if (!isUpgrade) {
isUpgrade = true;
String oldName = wandName;
wandName = Messages.get("wand.upgrade_name");
wandName = wandName.replace("$name", oldName);
description = Messages.get("wand.upgrade_default_description");
if (template != null && template.length() > 0) {
description = Messages.get("wands." + template + ".upgrade_description", description);
}
setIcon(DefaultUpgradeMaterial, (byte) 0);
saveState();
updateName(true);
updateLore();
}
}
protected void activateBrush(String materialKey) {
setActiveBrush(materialKey);
if (materialKey != null) {
com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush();
if (brush != null) {
brush.activate(mage.getLocation(), materialKey);
}
}
}
public void activateBrush(ItemStack itemStack) {
if (!isBrush(itemStack)) return;
activateBrush(getBrush(itemStack));
}
public String getLostId() { return id; }
public void clearLostId() {
if (id != null) {
id = null;
saveState();
}
}
public int getXpRegeneration() {
return xpRegeneration;
}
public int getXpMax() {
return xpMax;
}
public int getExperience() {
return xp;
}
public void removeExperience(int amount) {
xp = Math.max(0, xp - amount);
updateMana();
}
public float getHealthRegeneration() {
return healthRegeneration;
}
public float getHungerRegeneration() {
return hungerRegeneration;
}
public boolean isModifiable() {
return !locked;
}
public boolean isIndestructible() {
return indestructible;
}
public boolean isUndroppable() {
return undroppable;
}
public boolean isUpgrade() {
return isUpgrade;
}
public boolean usesMana() {
return xpMax > 0 && xpRegeneration > 0 && !isCostFree();
}
public float getCooldownReduction() {
return controller.getCooldownReduction() + cooldownReduction * WandLevel.maxCooldownReduction;
}
public float getCostReduction() {
if (isCostFree()) return 1.0f;
return controller.getCostReduction() + costReduction * WandLevel.maxCostReduction;
}
public void setCooldownReduction(float reduction) {
cooldownReduction = reduction;
}
public boolean getHasInventory() {
return hasInventory;
}
public float getPower() {
return power;
}
public boolean isSuperProtected() {
return damageReduction > 1;
}
public boolean isSuperPowered() {
return power > 1;
}
public boolean isCostFree() {
return costReduction > 1;
}
public boolean isCooldownFree() {
return cooldownReduction > 1;
}
public float getDamageReduction() {
return damageReduction * WandLevel.maxDamageReduction;
}
public float getDamageReductionPhysical() {
return damageReductionPhysical * WandLevel.maxDamageReductionPhysical;
}
public float getDamageReductionProjectiles() {
return damageReductionProjectiles * WandLevel.maxDamageReductionProjectiles;
}
public float getDamageReductionFalling() {
return damageReductionFalling * WandLevel.maxDamageReductionFalling;
}
public float getDamageReductionFire() {
return damageReductionFire * WandLevel.maxDamageReductionFire;
}
public float getDamageReductionExplosions() {
return damageReductionExplosions * WandLevel.maxDamageReductionExplosions;
}
public int getUses() {
return uses;
}
public String getName() {
return wandName;
}
public String getDescription() {
return description;
}
public String getOwner() {
return owner;
}
public long getWorth() {
long worth = 0;
// TODO: Item properties, brushes, etc
Set<String> spells = getSpells();
for (String spellKey : spells) {
SpellTemplate spell = controller.getSpellTemplate(spellKey);
if (spell != null) {
worth += spell.getWorth();
}
}
return worth;
}
public void setName(String name) {
wandName = ChatColor.stripColor(name);
updateName();
}
public void setTemplate(String templateName) {
this.template = templateName;
}
public String getTemplate() {
return this.template;
}
public WandUpgradePath getPath() {
String pathKey = path;
if (pathKey == null || pathKey.length() == 0) {
pathKey = controller.getDefaultWandPath();
}
return WandUpgradePath.getPath(pathKey);
}
public boolean hasPath() {
return path != null && path.length() > 0;
}
public void setDescription(String description) {
this.description = description;
updateLore();
}
public void tryToOwn(Player player) {
if (ownerId == null || ownerId.length() == 0) {
// Backwards-compatibility, don't overwrite unless the
// name matches
if (owner != null && !owner.equals(player.getName())) {
return;
}
takeOwnership(player);
}
}
protected void takeOwnership(Player player) {
takeOwnership(player, controller != null && controller.bindWands(), controller != null && controller.keepWands());
}
public void takeOwnership(Player player, boolean setBound, boolean setKeep) {
owner = player.getName();
ownerId = player.getUniqueId().toString();
if (setBound) {
bound = true;
}
if (setKeep) {
keep = true;
}
updateLore();
}
public ItemStack getItem() {
return item;
}
protected List<Inventory> getAllInventories() {
List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1);
allInventories.add(hotbar);
allInventories.addAll(inventories);
return allInventories;
}
public Set<String> getSpells() {
return spells;
}
protected String getSpellString() {
Set<String> spellNames = new TreeSet<String>();
List<Inventory> allInventories = getAllInventories();
int index = 0;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int i = 0; i < items.length; i++) {
if (items[i] != null && isSpell(items[i])) {
String spellName = getSpell(items[i]) + "@" + index;
spellNames.add(spellName);
}
index++;
}
}
return StringUtils.join(spellNames, ",");
}
public Set<String> getBrushes() {
return brushes;
}
protected String getMaterialString() {
Set<String> materialNames = new TreeSet<String>();
List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1);
allInventories.add(hotbar);
allInventories.addAll(inventories);
int index = 0;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int i = 0; i < items.length; i++) {
if (items[i] != null && isBrush(items[i])) {
String materialKey = getBrush(items[i]);
if (materialKey != null) {
materialKey += "@" + index;
materialNames.add(materialKey);
}
}
index++;
}
}
return StringUtils.join(materialNames, ",");
}
protected Integer parseSlot(String[] pieces) {
Integer slot = null;
if (pieces.length > 0) {
try {
slot = Integer.parseInt(pieces[1]);
} catch (Exception ex) {
slot = null;
}
if (slot != null && slot < 0) {
slot = null;
}
}
return slot;
}
protected void addToInventory(ItemStack itemStack) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
return;
}
// Set the wand item
Integer selectedItem = null;
if (getMode() == WandMode.INVENTORY && mage != null && mage.getPlayer() != null) {
selectedItem = mage.getPlayer().getInventory().getHeldItemSlot();
// Toss the item back into the wand inventory, it'll find a home somewhere.
// We hope this doesn't recurse too badly! :\
ItemStack existingHotbar = hotbar.getItem(selectedItem);
if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) {
hotbar.setItem(selectedItem, item);
addToInventory(existingHotbar); }
hotbar.setItem(selectedItem, item);
}
List<Inventory> checkInventories = getAllInventories();
boolean added = false;
for (Inventory inventory : checkInventories) {
HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack);
if (returned.size() == 0) {
added = true;
break;
}
}
if (!added) {
Inventory newInventory = CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand");
newInventory.addItem(itemStack);
inventories.add(newInventory);
}
// Restore empty wand slot
if (selectedItem != null) {
hotbar.setItem(selectedItem, null);
}
}
protected Inventory getDisplayInventory() {
if (displayInventory == null) {
displayInventory = CompatibilityUtils.createInventory(null, INVENTORY_SIZE + HOTBAR_SIZE, "Wand");
}
return displayInventory;
}
protected Inventory getInventoryByIndex(int inventoryIndex) {
while (inventoryIndex >= inventories.size()) {
inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand"));
}
return inventories.get(inventoryIndex);
}
protected Inventory getInventory(Integer slot) {
Inventory inventory = hotbar;
if (slot >= HOTBAR_SIZE) {
int inventoryIndex = (slot - HOTBAR_SIZE) / INVENTORY_SIZE;
inventory = getInventoryByIndex(inventoryIndex);
}
return inventory;
}
protected int getInventorySlot(Integer slot) {
if (slot < HOTBAR_SIZE) {
return slot;
}
return ((slot - HOTBAR_SIZE) % INVENTORY_SIZE);
}
protected void addToInventory(ItemStack itemStack, Integer slot) {
if (slot == null) {
addToInventory(itemStack);
return;
}
Inventory inventory = getInventory(slot);
slot = getInventorySlot(slot);
ItemStack existing = inventory.getItem(slot);
inventory.setItem(slot, itemStack);
if (existing != null && existing.getType() != Material.AIR) {
addToInventory(existing);
}
}
protected void parseInventoryStrings(String spellString, String materialString) {
hotbar.clear();
inventories.clear();
spells.clear();
brushes.clear();
// Support YML-List-As-String format and |-delimited format
spellString = spellString.replaceAll("[\\]\\[]", "");
String[] spellNames = StringUtils.split(spellString, "|,");
for (String spellName : spellNames) {
String[] pieces = spellName.split("@");
Integer slot = parseSlot(pieces);
String spellKey = pieces[0].trim();
spells.add(spellKey);
ItemStack itemStack = createSpellIcon(spellKey);
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create spell icon for key " + spellKey);
continue;
}
if (activeSpell == null || activeSpell.length() == 0) activeSpell = spellKey;
addToInventory(itemStack, slot);
}
materialString = materialString.replaceAll("[\\]\\[]", "");
String[] materialNames = StringUtils.split(materialString, "|,");
for (String materialName : materialNames) {
String[] pieces = materialName.split("@");
Integer slot = parseSlot(pieces);
String materialKey = pieces[0].trim();
brushes.add(materialKey);
ItemStack itemStack = createBrushIcon(materialKey);
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create material icon for key " + materialKey);
continue;
}
if (activeMaterial == null || activeMaterial.length() == 0) activeMaterial = materialKey;
addToInventory(itemStack, slot);
}
hasInventory = spellNames.length + materialNames.length > 1;
}
protected ItemStack createSpellIcon(SpellTemplate spell) {
return createSpellItem(spell, controller, this, false);
}
public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) {
return createSpellItem(controller.getSpellTemplate(spellKey), controller, wand, isItem);
}
@SuppressWarnings("deprecation")
public static ItemStack createSpellItem(SpellTemplate spell, MagicController controller, Wand wand, boolean isItem) {
if (spell == null) return null;
com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon();
if (icon == null) {
controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material");
return null;
}
ItemStack itemStack = null;
ItemStack originalItemStack = null;
try {
originalItemStack = new ItemStack(icon.getMaterial(), 1, (short)0, (byte)icon.getData());
itemStack = InventoryUtils.makeReal(originalItemStack);
} catch (Exception ex) {
itemStack = null;
}
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getKey() + " with material " + icon.getMaterial().name());
return originalItemStack;
}
updateSpellItem(itemStack, spell, wand, wand == null ? null : wand.activeMaterial, isItem);
return itemStack;
}
protected ItemStack createSpellIcon(String spellKey) {
return createSpellItem(spellKey, controller, this, false);
}
private String getActiveWandName(String materialKey) {
SpellTemplate spell = null;
if (activeSpell != null && activeSpell.length() > 0) {
spell = controller.getSpellTemplate(activeSpell);
}
return getActiveWandName(spell, materialKey);
}
protected ItemStack createBrushIcon(String materialKey) {
return createBrushItem(materialKey, controller, this, false);
}
@SuppressWarnings("deprecation")
public static ItemStack createBrushItem(String materialKey, MagicController controller, Wand wand, boolean isItem) {
MaterialAndData brushData = MaterialBrush.parseMaterialKey(materialKey, false);
if (brushData == null) return null;
Material material = brushData.getMaterial();
if (material == null || material == Material.AIR) {
return null;
}
byte dataId = brushData.getData();
ItemStack originalItemStack = new ItemStack(material, 1, (short)0, (byte)dataId);
ItemStack itemStack = InventoryUtils.makeReal(originalItemStack);
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create material icon for " + material.name() + ": " + materialKey);
return null;
}
List<String> lore = new ArrayList<String>();
if (material != null) {
lore.add(ChatColor.GRAY + Messages.get("wand.building_material_info").replace("$material", MaterialBrush.getMaterialName(materialKey)));
if (material == MaterialBrush.EraseMaterial) {
lore.add(Messages.get("wand.erase_material_description"));
} else if (material == MaterialBrush.CopyMaterial) {
lore.add(Messages.get("wand.copy_material_description"));
} else if (material == MaterialBrush.CloneMaterial) {
lore.add(Messages.get("wand.clone_material_description"));
} else if (material == MaterialBrush.ReplicateMaterial) {
lore.add(Messages.get("wand.replicate_material_description"));
} else if (material == MaterialBrush.MapMaterial) {
lore.add(Messages.get("wand.map_material_description"));
} else if (material == MaterialBrush.SchematicMaterial) {
lore.add(Messages.get("wand.schematic_material_description").replace("$schematic", brushData.getCustomName()));
} else {
lore.add(ChatColor.LIGHT_PURPLE + Messages.get("wand.building_material_description"));
}
}
if (isItem) {
lore.add(ChatColor.YELLOW + Messages.get("wand.brush_item_description"));
}
CompatibilityUtils.setLore(itemStack, lore);
updateBrushItem(itemStack, materialKey, wand);
return itemStack;
}
protected void saveState() {
if (suspendSave || item == null) return;
ConfigurationSection stateNode = new MemoryConfiguration();
saveProperties(stateNode);
// Save legacy data as well until migration is settled
Object wandNode = InventoryUtils.createNode(item, "wand");
if (wandNode == null) {
controller.getLogger().warning("Failed to save legacy wand state for wand id " + id + " to : " + item + " of class " + item.getClass());
} else {
InventoryUtils.saveTagsToNBT(stateNode, wandNode, ALL_PROPERTY_KEYS);
}
// TODO: Re-implement using Metadata API in 4.0
Object magicNode = CompatibilityUtils.createMetadataNode(item, metadataProvider, isUpgrade ? "upgrade" : "wand");
if (magicNode == null) {
controller.getLogger().warning("Failed to save wand state for wand id " + id + " to : " + item + " of class " + item.getClass());
return;
}
// Clean up any extra data that might be on here
if (isUpgrade) {
CompatibilityUtils.removeMetadata(item, metadataProvider, "wand");
} else {
CompatibilityUtils.removeMetadata(item, metadataProvider, "upgrade");
}
CompatibilityUtils.removeMetadata(item, metadataProvider, "spell");
CompatibilityUtils.removeMetadata(item, metadataProvider, "brush");
InventoryUtils.saveTagsToNBT(stateNode, magicNode, ALL_PROPERTY_KEYS);
}
protected void loadState() {
if (item == null) return;
boolean isWand = CompatibilityUtils.hasMetadata(item, metadataProvider, "wand");
boolean isUpgrade = !isWand && CompatibilityUtils.hasMetadata(item, metadataProvider, "upgrade");
if (isWand || isUpgrade) {
// TODO: Re-implement using Metadata API in 4.0
Object magicNode = CompatibilityUtils.getMetadataNode(item, metadataProvider, isUpgrade ? "upgrade" : "wand");
if (magicNode == null) {
return;
}
ConfigurationSection stateNode = new MemoryConfiguration();
InventoryUtils.loadTagsFromNBT(stateNode, magicNode, ALL_PROPERTY_KEYS);
loadProperties(stateNode);
} else {
Object wandNode = InventoryUtils.getNode(item, "wand");
if (wandNode == null) {
return;
}
ConfigurationSection stateNode = new MemoryConfiguration();
InventoryUtils.loadTagsFromNBT(stateNode, wandNode, ALL_PROPERTY_KEYS);
loadProperties(stateNode);
}
}
public void saveProperties(ConfigurationSection node) {
node.set("id", id);
node.set("materials", getMaterialString());
node.set("spells", getSpellString());
node.set("active_spell", activeSpell);
node.set("active_material", activeMaterial);
node.set("name", wandName);
node.set("description", description);
node.set("owner", owner);
node.set("owner_id", ownerId);
node.set("cost_reduction", costReduction);
node.set("cooldown_reduction", cooldownReduction);
node.set("power", power);
node.set("protection", damageReduction);
node.set("protection_physical", damageReductionPhysical);
node.set("protection_projectiles", damageReductionProjectiles);
node.set("protection_falling", damageReductionFalling);
node.set("protection_fire", damageReductionFire);
node.set("protection_explosions", damageReductionExplosions);
node.set("haste", speedIncrease);
node.set("xp", xp);
node.set("xp_regeneration", xpRegeneration);
node.set("xp_max", xpMax);
node.set("health_regeneration", healthRegeneration);
node.set("hunger_regeneration", hungerRegeneration);
node.set("uses", uses);
node.set("locked", locked);
node.set("effect_color", effectColor == null ? "none" : effectColor.toString());
node.set("effect_bubbles", effectBubbles);
node.set("effect_particle_data", Float.toString(effectParticleData));
node.set("effect_particle_count", effectParticleCount);
node.set("effect_particle_interval", effectParticleInterval);
node.set("effect_sound_interval", effectSoundInterval);
node.set("effect_sound_volume", Float.toString(effectSoundVolume));
node.set("effect_sound_pitch", Float.toString(effectSoundPitch));
node.set("quiet", quietLevel);
node.set("keep", keep);
node.set("randomize", randomize);
node.set("rename", rename);
node.set("bound", bound);
node.set("force", forceUpgrade);
node.set("indestructible", indestructible);
node.set("undroppable", undroppable);
node.set("fill", autoFill);
node.set("upgrade", isUpgrade);
node.set("organize", autoOrganize);
if (castParameters != null && castParameters.length > 0) {
node.set("overrides", StringUtils.join(castParameters, ' '));
} else {
node.set("overrides", null);
}
if (effectSound != null) {
node.set("effect_sound", effectSound.name());
} else {
node.set("effectSound", null);
}
if (effectParticle != null) {
node.set("effect_particle", effectParticle.name());
} else {
node.set("effect_particle", null);
}
if (mode != null) {
node.set("mode", mode.name());
} else {
node.set("mode", null);
}
if (icon != null) {
String iconKey = MaterialBrush.getMaterialKey(icon);
if (iconKey != null && iconKey.length() > 0) {
node.set("icon", iconKey);
} else {
node.set("icon", null);
}
} else {
node.set("icon", null);
}
if (template != null && template.length() > 0) {
node.set("template", template);
} else {
node.set("template", null);
}
if (path != null && path.length() > 0) {
node.set("path", path);
} else {
node.set("path", null);
}
}
public void loadProperties(ConfigurationSection wandConfig) {
loadProperties(wandConfig, false);
}
public void setEffectColor(String hexColor) {
// Annoying config conversion issue :\
if (hexColor.contains(".")) {
hexColor = hexColor.substring(0, hexColor.indexOf('.'));
}
if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) {
effectColor = null;
return;
}
effectColor = new ColorHD(hexColor);
}
public void loadProperties(ConfigurationSection wandConfig, boolean safe) {
locked = (boolean)wandConfig.getBoolean("locked", locked);
float _costReduction = (float)wandConfig.getDouble("cost_reduction", costReduction);
costReduction = safe ? Math.max(_costReduction, costReduction) : _costReduction;
float _cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction", cooldownReduction);
cooldownReduction = safe ? Math.max(_cooldownReduction, cooldownReduction) : _cooldownReduction;
float _power = (float)wandConfig.getDouble("power", power);
power = safe ? Math.max(_power, power) : _power;
float _damageReduction = (float)wandConfig.getDouble("protection", damageReduction);
damageReduction = safe ? Math.max(_damageReduction, damageReduction) : _damageReduction;
float _damageReductionPhysical = (float)wandConfig.getDouble("protection_physical", damageReductionPhysical);
damageReductionPhysical = safe ? Math.max(_damageReductionPhysical, damageReductionPhysical) : _damageReductionPhysical;
float _damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles", damageReductionProjectiles);
damageReductionProjectiles = safe ? Math.max(_damageReductionProjectiles, damageReductionPhysical) : _damageReductionProjectiles;
float _damageReductionFalling = (float)wandConfig.getDouble("protection_falling", damageReductionFalling);
damageReductionFalling = safe ? Math.max(_damageReductionFalling, damageReductionFalling) : _damageReductionFalling;
float _damageReductionFire = (float)wandConfig.getDouble("protection_fire", damageReductionFire);
damageReductionFire = safe ? Math.max(_damageReductionFire, damageReductionFire) : _damageReductionFire;
float _damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions", damageReductionExplosions);
damageReductionExplosions = safe ? Math.max(_damageReductionExplosions, damageReductionExplosions) : _damageReductionExplosions;
int _xpRegeneration = wandConfig.getInt("xp_regeneration", xpRegeneration);
xpRegeneration = safe ? Math.max(_xpRegeneration, xpRegeneration) : _xpRegeneration;
int _xpMax = wandConfig.getInt("xp_max", xpMax);
xpMax = safe ? Math.max(_xpMax, xpMax) : _xpMax;
int _xp = wandConfig.getInt("xp", xp);
xp = safe ? Math.max(_xp, xp) : _xp;
float _healthRegeneration = (float)wandConfig.getDouble("health_regeneration", healthRegeneration);
healthRegeneration = safe ? Math.max(_healthRegeneration, healthRegeneration) : _healthRegeneration;
float _hungerRegeneration = (float)wandConfig.getDouble("hunger_regeneration", hungerRegeneration);
hungerRegeneration = safe ? Math.max(_hungerRegeneration, hungerRegeneration) : _hungerRegeneration;
int _uses = wandConfig.getInt("uses", uses);
uses = safe ? Math.max(_uses, uses) : _uses;
float _speedIncrease = (float)wandConfig.getDouble("haste", speedIncrease);
speedIncrease = safe ? Math.max(_speedIncrease, speedIncrease) : _speedIncrease;
if (wandConfig.contains("effect_color") && !safe) {
setEffectColor(wandConfig.getString("effect_color"));
}
// Don't change any of this stuff in safe mode
if (!safe) {
id = wandConfig.getString("id", id);
isUpgrade = wandConfig.getBoolean("upgrade", isUpgrade);
quietLevel = wandConfig.getInt("quiet", quietLevel);
effectBubbles = wandConfig.getBoolean("effect_bubbles", effectBubbles);
keep = wandConfig.getBoolean("keep", keep);
indestructible = wandConfig.getBoolean("indestructible", indestructible);
undroppable = wandConfig.getBoolean("undroppable", undroppable);
bound = wandConfig.getBoolean("bound", bound);
forceUpgrade = wandConfig.getBoolean("force", forceUpgrade);
autoOrganize = wandConfig.getBoolean("organize", autoOrganize);
autoFill = wandConfig.getBoolean("fill", autoFill);
randomize = wandConfig.getBoolean("randomize", randomize);
rename = wandConfig.getBoolean("rename", rename);
if (wandConfig.contains("effect_particle")) {
parseParticleEffect(wandConfig.getString("effect_particle"));
effectParticleData = 0;
}
if (wandConfig.contains("effect_sound")) {
parseSoundEffect(wandConfig.getString("effect_sound"));
}
effectParticleData = (float)wandConfig.getDouble("effect_particle_data", effectParticleData);
effectParticleCount = wandConfig.getInt("effect_particle_count", effectParticleCount);
effectParticleInterval = wandConfig.getInt("effect_particle_interval", effectParticleInterval);
effectSoundInterval = wandConfig.getInt("effect_sound_interval", effectSoundInterval);
effectSoundVolume = (float)wandConfig.getDouble("effect_sound_volume", effectSoundVolume);
effectSoundPitch = (float)wandConfig.getDouble("effect_sound_pitch", effectSoundPitch);
setMode(parseWandMode(wandConfig.getString("mode"), mode));
owner = wandConfig.getString("owner", owner);
ownerId = wandConfig.getString("owner_id", ownerId);
wandName = wandConfig.getString("name", wandName);
description = wandConfig.getString("description", description);
template = wandConfig.getString("template", template);
path = wandConfig.getString("path", path);
activeSpell = wandConfig.getString("active_spell", activeSpell);
activeMaterial = wandConfig.getString("active_material", activeMaterial);
String wandMaterials = wandConfig.getString("materials", "");
String wandSpells = wandConfig.getString("spells", "");
if (wandMaterials.length() > 0 || wandSpells.length() > 0) {
wandMaterials = wandMaterials.length() == 0 ? getMaterialString() : wandMaterials;
wandSpells = wandSpells.length() == 0 ? getSpellString() : wandSpells;
parseInventoryStrings(wandSpells, wandMaterials);
}
if (wandConfig.contains("randomize_icon")) {
setIcon(ConfigurationUtils.toMaterialAndData(wandConfig.getString("randomize_icon")));
randomize = true;
} else if (!randomize && wandConfig.contains("icon")) {
String iconKey = wandConfig.getString("icon");
if (iconKey.contains(",")) {
Random r = new Random();
String[] keys = StringUtils.split(iconKey, ',');
iconKey = keys[r.nextInt(keys.length)];
}
setIcon(ConfigurationUtils.toMaterialAndData(iconKey));
}
if (wandConfig.contains("overrides")) {
castParameters = null;
String overrides = wandConfig.getString("overrides", null);
if (overrides != null && !overrides.isEmpty()) {
castParameters = StringUtils.split(overrides, ' ');
}
}
}
// Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders)
// so try to keep defaults as 0/0.0/false.
if (effectSound == null) {
effectSoundInterval = 0;
effectSoundVolume = 0;
effectSoundPitch = 0;
} else {
effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval;
effectSoundVolume = (effectSoundVolume < 0.01f) ? 0.8f : effectSoundVolume;
effectSoundPitch = (effectSoundPitch < 0.01f) ? 1.1f : effectSoundPitch;
}
if (effectParticle == null) {
effectParticleInterval = 0;
} else {
effectParticleInterval = (effectParticleInterval == 0) ? 2 : effectParticleInterval;
effectParticleCount = (effectParticleCount == 0) ? 1 : effectParticleCount;
}
if (xpRegeneration <= 0 || xpMax <= 0 || costReduction >= 1) {
xpMax = 0;
xpRegeneration = 0;
xp = 0;
}
checkActiveMaterial();
updateName();
updateLore();
}
protected void parseSoundEffect(String effectSoundName) {
if (effectSoundName.length() > 0) {
String testName = effectSoundName.toUpperCase().replace("_", "");
try {
for (Sound testType : Sound.values()) {
String testTypeName = testType.name().replace("_", "");
if (testTypeName.equals(testName)) {
effectSound = testType;
break;
}
}
} catch (Exception ex) {
effectSound = null;
}
} else {
effectSound = null;
}
}
protected void parseParticleEffect(String effectParticleName) {
if (effectParticleName.length() > 0) {
try {
effectParticle = ParticleEffect.valueOf(effectParticleName);
} catch (Exception ex) {
effectParticle = null;
}
} else {
effectParticle = null;
}
}
public void describe(CommandSender sender) {
Object wandNode = InventoryUtils.getNode(item, "wand");
if (wandNode == null) {
sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data");
return;
}
ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED;
sender.sendMessage(wandColor + wandName);
if (description.length() > 0) {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description);
} else {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)");
}
if (owner.length() > 0) {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner);
} else {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)");
}
for (String key : PROPERTY_KEYS) {
String value = InventoryUtils.getMeta(wandNode, key);
if (value != null && value.length() > 0) {
sender.sendMessage(key + ": " + value);
}
}
}
private static String getBrushDisplayName(String materialKey) {
String materialName = MaterialBrush.getMaterialName(materialKey);
if (materialName == null) {
materialName = "none";
}
return ChatColor.GRAY + materialName;
}
private static String getSpellDisplayName(SpellTemplate spell, String materialKey) {
String name = "";
if (spell != null) {
if (materialKey != null && (spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) {
name = ChatColor.GOLD + spell.getName() + " " + getBrushDisplayName(materialKey) + ChatColor.WHITE;
} else {
name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE;
}
}
return name;
}
private String getActiveWandName(SpellTemplate spell, String materialKey) {
// Build wand name
int remaining = getRemainingUses();
ChatColor wandColor = remaining > 0 ? ChatColor.DARK_RED : isModifiable()
? (bound ? ChatColor.DARK_AQUA : ChatColor.AQUA) : ChatColor.GOLD;
String name = wandColor + getDisplayName();
if (randomize) return name;
Set<String> spells = getSpells();
// Add active spell to description
if (spell != null && (spells.size() > 1 || hasPath())) {
name = getSpellDisplayName(spell, materialKey) + " (" + name + ChatColor.WHITE + ")";
}
if (remaining > 0) {
String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief");
name = name + " (" + ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()) + ")";
}
return name;
}
private String getActiveWandName(SpellTemplate spell) {
return getActiveWandName(spell, activeMaterial);
}
private String getActiveWandName() {
SpellTemplate spell = null;
if (activeSpell != null && activeSpell.length() > 0) {
spell = controller.getSpellTemplate(activeSpell);
}
return getActiveWandName(spell);
}
protected String getDisplayName() {
return randomize ? Messages.get("wand.randomized_name") : wandName;
}
public void updateName(boolean isActive) {
CompatibilityUtils.setDisplayName(item, isActive && !isUpgrade ? getActiveWandName() : ChatColor.GOLD + getDisplayName());
// Reset Enchantment glow
if (EnableGlow) {
CompatibilityUtils.addGlow(item);
}
// Make indestructible
CompatibilityUtils.makeUnbreakable(item);
}
private void updateName() {
updateName(true);
}
protected static String convertToHTML(String line) {
int tagCount = 1;
line = "<span style=\"color:white\">" + line;
for (ChatColor c : ChatColor.values()) {
tagCount += StringUtils.countMatches(line, c.toString());
String replaceStyle = "";
if (c == ChatColor.ITALIC) {
replaceStyle = "font-style: italic";
} else if (c == ChatColor.BOLD) {
replaceStyle = "font-weight: bold";
} else if (c == ChatColor.UNDERLINE) {
replaceStyle = "text-decoration: underline";
} else {
String color = c.name().toLowerCase().replace("_", "");
if (c == ChatColor.LIGHT_PURPLE) {
color = "mediumpurple";
}
replaceStyle = "color:" + color;
}
line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">");
}
for (int i = 0; i < tagCount; i++) {
line += "</span>";
}
return line;
}
public String getHTMLDescription() {
Collection<String> rawLore = getLore();
Collection<String> lore = new ArrayList<String>();
lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>");
for (String line : rawLore) {
lore.add(convertToHTML(line));
}
return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>";
}
protected List<String> getLore() {
return getLore(getSpells().size(), getBrushes().size());
}
protected void addPropertyLore(List<String> lore)
{
if (usesMana()) {
lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp));
lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration));
}
if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cost_reduction", costReduction));
if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cooldown_reduction", cooldownReduction));
if (power > 0) lore.add(ChatColor.AQUA + getLevelString("wand.power", power));
if (speedIncrease > 0) lore.add(ChatColor.AQUA + getLevelString("wand.haste", speedIncrease));
if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection", damageReduction, WandLevel.maxDamageReduction));
if (damageReduction < 1) {
if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_physical", damageReductionPhysical, WandLevel.maxDamageReductionPhysical));
if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_projectile", damageReductionProjectiles, WandLevel.maxDamageReductionProjectiles));
if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fall", damageReductionFalling, WandLevel.maxDamageReductionFalling));
if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fire", damageReductionFire, WandLevel.maxDamageReductionFire));
if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_blast", damageReductionExplosions, WandLevel.maxDamageReductionExplosions));
}
if (healthRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.health_regeneration", healthRegeneration));
if (hungerRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.hunger_regeneration", hungerRegeneration));
}
private String getLevelString(String templateName, float amount)
{
return getLevelString(templateName, amount, 1);
}
private static String getLevelString(String templateName, float amount, float max)
{
String templateString = Messages.get(templateName);
if (templateString.contains("$roman")) {
templateString = templateString.replace("$roman", getRomanString(amount));
}
return templateString.replace("$amount", Integer.toString((int)amount));
}
private static String getRomanString(float amount) {
String roman = "";
if (amount > 1) {
roman = Messages.get("wand.enchantment_level_max");
} else if (amount > 0.8) {
roman = Messages.get("wand.enchantment_level_5");
} else if (amount > 0.6) {
roman = Messages.get("wand.enchantment_level_4");
} else if (amount > 0.4) {
roman = Messages.get("wand.enchantment_level_3");
} else if (amount > 0.2) {
roman = Messages.get("wand.enchantment_level_2");
} else {
roman = Messages.get("wand.enchantment_level_1");
}
return roman;
}
protected List<String> getLore(int spellCount, int materialCount)
{
List<String> lore = new ArrayList<String>();
if (description.length() > 0) {
if (description.contains("$")) {
String randomDescription = Messages.get("wand.randomized_lore");
if (randomDescription.length() > 0) {
lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + randomDescription);
}
} else {
lore.add(ChatColor.ITALIC + "" + ChatColor.GREEN + description);
}
}
if (randomize) {
return lore;
}
SpellTemplate spell = controller.getSpellTemplate(activeSpell);
// This is here specifically for a wand that only has
// one spell now, but may get more later. Since you
// can't open the inventory in this state, you can not
// otherwise see the spell lore.
if (spell != null && spellCount == 1 && !hasInventory && !isUpgrade && hasPath()) {
lore.add(getSpellDisplayName(spell, null));
addSpellLore(spell, lore, this);
}
if (materialCount == 1 && activeMaterial != null && activeMaterial.length() > 0)
{
lore.add(getBrushDisplayName(activeMaterial));
}
if (!isUpgrade) {
if (owner.length() > 0) {
if (bound) {
String ownerDescription = Messages.get("wand.bound_description", "$name").replace("$name", owner);
lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription);
} else {
String ownerDescription = Messages.get("wand.owner_description", "$name").replace("$name", owner);
lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + ownerDescription);
}
}
}
if (spellCount > 0) {
if (isUpgrade) {
lore.add(Messages.get("wand.upgrade_spell_count").replace("$count", ((Integer)spellCount).toString()));
} else if (spellCount > 1) {
lore.add(Messages.get("wand.spell_count").replace("$count", ((Integer)spellCount).toString()));
}
}
if (materialCount > 0) {
if (isUpgrade) {
lore.add(Messages.get("wand.upgrade_material_count").replace("$count", ((Integer)materialCount).toString()));
} else if (materialCount > 1) {
lore.add(Messages.get("wand.material_count").replace("$count", ((Integer)materialCount).toString()));
}
}
int remaining = getRemainingUses();
if (remaining > 0) {
if (isUpgrade) {
String message = (remaining == 1) ? Messages.get("wand.upgrade_uses_singular") : Messages.get("wand.upgrade_uses");
lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()));
} else {
String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief");
lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()));
}
}
addPropertyLore(lore);
if (isUpgrade) {
lore.add(ChatColor.YELLOW + Messages.get("wand.upgrade_item_description"));
}
return lore;
}
protected void updateLore() {
CompatibilityUtils.setLore(item, getLore());
if (EnableGlow) {
CompatibilityUtils.addGlow(item);
}
}
public int getRemainingUses() {
return uses;
}
public void makeEnchantable(boolean enchantable) {
if (EnchantableWandMaterial == null) return;
if (!enchantable) {
item.setType(icon.getMaterial());
item.setDurability(icon.getData());
} else {
Set<Material> enchantableMaterials = controller.getMaterialSet("enchantable");
if (!enchantableMaterials.contains(item.getType())) {
item.setType(EnchantableWandMaterial);
item.setDurability((short)0);
}
}
updateName();
}
public static boolean hasActiveWand(Player player) {
if (player == null) return false;
ItemStack activeItem = player.getInventory().getItemInHand();
return isWand(activeItem);
}
public static Wand getActiveWand(MagicController spells, Player player) {
ItemStack activeItem = player.getInventory().getItemInHand();
if (isWand(activeItem)) {
return new Wand(spells, activeItem);
}
return null;
}
public static boolean isWand(ItemStack item) {
return item != null && (CompatibilityUtils.hasMetadata(item, metadataProvider, "wand") || isLegacyWand(item));
}
public static boolean isLegacyWand(ItemStack item) {
return item != null && InventoryUtils.hasMeta(item, "wand") && !isLegacyUpgrade(item);
}
public static boolean isLegacyUpgrade(ItemStack item) {
if (item == null) return false;
Object wandNode = InventoryUtils.getNode(item, "wand");
if (wandNode == null) return false;
String upgradeData = InventoryUtils.getMeta(wandNode, "upgrade");
return upgradeData != null && upgradeData.equals("true");
}
public static boolean isUpgrade(ItemStack item) {
if (item == null) return false;
if (isLegacyUpgrade(item)) return true;
return item != null && CompatibilityUtils.hasMetadata(item, metadataProvider, "upgrade");
}
public static boolean isLegacySpell(ItemStack item) {
return item != null && InventoryUtils.hasMeta(item, "spell");
}
public static boolean isSpell(ItemStack item) {
return item != null && (CompatibilityUtils.hasMetadata(item, metadataProvider, "spell") || isLegacySpell(item));
}
public static boolean isLegacyBrush(ItemStack item) {
return item != null && InventoryUtils.hasMeta(item, "brush");
}
public static boolean isBrush(ItemStack item) {
return item != null && (CompatibilityUtils.hasMetadata(item, metadataProvider, "brush") || isLegacyBrush(item));
}
public static String getLegacySpell(ItemStack item) {
if (!isLegacySpell(item)) return null;
Object spellNode = InventoryUtils.getNode(item, "spell");
return InventoryUtils.getMeta(spellNode, "key");
}
public static String getSpell(ItemStack item) {
if (!isSpell(item)) {
if (isLegacySpell(item)) {
return getLegacySpell(item);
}
return null;
}
return CompatibilityUtils.getMetadata(item, metadataProvider, "spell");
}
public static String getLegacyBrush(ItemStack item) {
if (!isLegacyBrush(item)) return null;
Object brushNode = InventoryUtils.getNode(item, "brush");
return InventoryUtils.getMeta(brushNode, "key");
}
public static String getBrush(ItemStack item) {
if (!isBrush(item)) {
if (isLegacyBrush(item)) {
return getLegacyBrush(item);
}
return null;
}
return CompatibilityUtils.getMetadata(item, metadataProvider, "brush");
}
protected void updateInventoryName(ItemStack item, boolean activeName) {
if (isSpell(item)) {
Spell spell = mage.getSpell(getSpell(item));
if (spell != null) {
updateSpellItem(item, spell, activeName ? this : null, activeMaterial, false);
}
} else if (isBrush(item)) {
updateBrushItem(item, getBrush(item), activeName ? this : null);
}
}
public static void updateSpellItem(ItemStack itemStack, SpellTemplate spell, Wand wand, String activeMaterial, boolean isItem) {
String displayName;
if (wand != null) {
displayName = wand.getActiveWandName(spell);
} else {
displayName = getSpellDisplayName(spell, activeMaterial);
}
CompatibilityUtils.setDisplayName(itemStack, displayName);
List<String> lore = new ArrayList<String>();
addSpellLore(spell, lore, wand);
if (isItem) {
lore.add(ChatColor.YELLOW + Messages.get("wand.spell_item_description"));
}
CompatibilityUtils.setLore(itemStack, lore);
CompatibilityUtils.addGlow(itemStack);
CompatibilityUtils.setMetadata(itemStack, metadataProvider, "spell", spell.getKey());
}
public static void updateBrushItem(ItemStack itemStack, String materialKey, Wand wand) {
String displayName = null;
if (wand != null) {
displayName = wand.getActiveWandName(materialKey);
} else {
displayName = MaterialBrush.getMaterialName(materialKey);
}
CompatibilityUtils.setDisplayName(itemStack, displayName);
CompatibilityUtils.setMetadata(itemStack, metadataProvider, "brush", materialKey);
}
public void updateHotbar() {
if (mage == null) return;
if (!isInventoryOpen()) return;
Player player = mage.getPlayer();
if (player == null) return;
if (!mage.hasStoredInventory()) return;
WandMode wandMode = getMode();
if (wandMode == WandMode.INVENTORY) {
PlayerInventory inventory = player.getInventory();
updateHotbar(inventory);
player.updateInventory();
}
}
@SuppressWarnings("deprecation")
private void updateInventory() {
if (mage == null) return;
if (!isInventoryOpen()) return;
Player player = mage.getPlayer();
if (player == null) return;
WandMode wandMode = getMode();
if (wandMode == WandMode.INVENTORY) {
if (!mage.hasStoredInventory()) return;
PlayerInventory inventory = player.getInventory();
inventory.clear();
updateHotbar(inventory);
updateInventory(inventory, HOTBAR_SIZE, false);
updateName();
player.updateInventory();
} else if (wandMode == WandMode.CHEST) {
Inventory inventory = getDisplayInventory();
inventory.clear();
updateInventory(inventory, 0, true);
player.updateInventory();
}
}
private void updateHotbar(PlayerInventory playerInventory) {
// Check for an item already in the player's held slot, which
// we are about to replace with the wand.
int currentSlot = playerInventory.getHeldItemSlot();
ItemStack existingHotbar = hotbar.getItem(currentSlot);
if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) {
// Toss the item back into the wand inventory, it'll find a home somewhere.
hotbar.setItem(currentSlot, item);
addToInventory(existingHotbar);
hotbar.setItem(currentSlot, null);
}
// Put the wand in the player's active slot.
playerInventory.setItem(currentSlot, item);
// Set hotbar items from remaining list
for (int hotbarSlot = 0; hotbarSlot < HOTBAR_SIZE; hotbarSlot++) {
if (hotbarSlot != currentSlot) {
ItemStack hotbarItem = hotbar.getItem(hotbarSlot);
updateInventoryName(hotbarItem, true);
playerInventory.setItem(hotbarSlot, hotbarItem);
}
}
}
private void updateInventory(Inventory targetInventory, int startOffset, boolean addHotbar) {
// Set inventory from current page
int currentOffset = startOffset;
if (openInventoryPage < inventories.size()) {
Inventory inventory = inventories.get(openInventoryPage);
ItemStack[] contents = inventory.getContents();
for (int i = 0; i < contents.length; i++) {
ItemStack inventoryItem = contents[i];
updateInventoryName(inventoryItem, false);
targetInventory.setItem(currentOffset, inventoryItem);
currentOffset++;
}
}
if (addHotbar) {
for (int i = 0; i < HOTBAR_SIZE; i++) {
ItemStack inventoryItem = hotbar.getItem(i);
updateInventoryName(inventoryItem, false);
targetInventory.setItem(currentOffset++, inventoryItem);
}
}
}
protected static void addSpellLore(SpellTemplate spell, List<String> lore, CostReducer reducer) {
String description = spell.getDescription();
String usage = spell.getUsage();
if (description != null && description.length() > 0) {
lore.add(description);
}
if (usage != null && usage.length() > 0) {
lore.add(usage);
}
Collection<CastingCost> costs = spell.getCosts();
if (costs != null) {
for (CastingCost cost : costs) {
if (cost.hasCosts(reducer)) {
lore.add(ChatColor.YELLOW + Messages.get("wand.costs_description").replace("$description", cost.getFullDescription(reducer)));
}
}
}
Collection<CastingCost> activeCosts = spell.getActiveCosts();
if (activeCosts != null) {
for (CastingCost cost : activeCosts) {
if (cost.hasCosts(reducer)) {
lore.add(ChatColor.YELLOW + Messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(reducer)));
}
}
}
long duration = spell.getDuration();
if (duration > 0) {
long seconds = duration / 1000;
if (seconds > 60 * 60 ) {
long hours = seconds / (60 * 60);
lore.add(Messages.get("duration.lasts_hours").replace("$hours", ((Long)hours).toString()));
} else if (seconds > 60) {
long minutes = seconds / 60;
lore.add(Messages.get("duration.lasts_minutes").replace("$minutes", ((Long)minutes).toString()));
} else {
lore.add(Messages.get("duration.lasts_seconds").replace("$seconds", ((Long)seconds).toString()));
}
}
if ((spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) {
lore.add(ChatColor.GOLD + Messages.get("spell.brush"));
}
if (spell instanceof UndoableSpell && ((UndoableSpell)spell).isUndoable()) {
lore.add(ChatColor.GRAY + Messages.get("spell.undoable"));
}
}
protected Inventory getOpenInventory() {
while (openInventoryPage >= inventories.size()) {
inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand"));
}
return inventories.get(openInventoryPage);
}
public void saveInventory() {
if (mage == null) return;
if (!isInventoryOpen()) return;
if (mage.getPlayer() == null) return;
if (getMode() != WandMode.INVENTORY) return;
if (!mage.hasStoredInventory()) return;
// Fill in the hotbar
Player player = mage.getPlayer();
PlayerInventory playerInventory = player.getInventory();
for (int i = 0; i < HOTBAR_SIZE; i++) {
ItemStack playerItem = playerInventory.getItem(i);
if (isWand(playerItem)) {
playerItem = null;
}
hotbar.setItem(i, playerItem);
}
// Fill in the active inventory page
Inventory openInventory = getOpenInventory();
for (int i = 0; i < openInventory.getSize(); i++) {
openInventory.setItem(i, playerInventory.getItem(i + HOTBAR_SIZE));
}
saveState();
}
public static boolean isActive(Player player) {
ItemStack activeItem = player.getInventory().getItemInHand();
return isWand(activeItem);
}
public boolean enchant(int totalLevels) {
return randomize(totalLevels, true);
}
protected boolean randomize(int totalLevels, boolean additive) {
WandUpgradePath path = getPath();
if (path == null) return false;
int maxLevel = path.getMaxLevel();
// Just a hard-coded sanity check
totalLevels = Math.min(totalLevels, maxLevel * 50);
int addLevels = Math.min(totalLevels, maxLevel);
boolean modified = true;
while (addLevels > 0 && modified) {
WandLevel level = path.getLevel(addLevels);
modified = level.randomizeWand(this, additive);
totalLevels -= maxLevel;
addLevels = Math.min(totalLevels, maxLevel);
additive = true;
}
return modified;
}
public static ItemStack createItem(MagicController controller, String templateName) {
ItemStack item = createSpellItem(templateName, controller, null, true);
if (item == null) {
item = createBrushItem(templateName, controller, null, true);
if (item == null) {
Wand wand = createWand(controller, templateName);
if (wand != null) {
item = wand.getItem();
}
}
}
return item;
}
public static Wand createWand(MagicController controller, String templateName) {
if (controller == null) return null;
Wand wand = null;
try {
wand = new Wand(controller, templateName);
} catch (UnknownWandException ignore) {
// the Wand constructor throws an exception on an unknown template
} catch (Exception ex) {
ex.printStackTrace();
}
return wand;
}
protected void sendAddMessage(String messageKey, String nameParam) {
if (mage == null) return;
String message = Messages.get(messageKey).replace("$name", nameParam);
mage.sendMessage(message);
}
public boolean add(Wand other) {
if (!isModifiable() || !other.isModifiable()) return false;
boolean modified = false;
if (other.isForcedUpgrade() || other.costReduction > costReduction) { costReduction = other.costReduction; modified = true; if (costReduction > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.cost_reduction", costReduction)); }
if (other.isForcedUpgrade() || other.power > power) { power = other.power; modified = true; if (power > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.power", power)); }
if (other.isForcedUpgrade() || other.damageReduction > damageReduction) { damageReduction = other.damageReduction; modified = true; if (damageReduction > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection", damageReduction)); }
if (other.isForcedUpgrade() || other.damageReductionPhysical > damageReductionPhysical) { damageReductionPhysical = other.damageReductionPhysical; modified = true; if (damageReductionPhysical > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_physical", damageReductionPhysical)); }
if (other.isForcedUpgrade() || other.damageReductionProjectiles > damageReductionProjectiles) { damageReductionProjectiles = other.damageReductionProjectiles; modified = true; if (damageReductionProjectiles > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_projectile", damageReductionProjectiles)); }
if (other.isForcedUpgrade() || other.damageReductionFalling > damageReductionFalling) { damageReductionFalling = other.damageReductionFalling; modified = true; if (damageReductionFalling > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_falling", damageReductionFalling)); }
if (other.isForcedUpgrade() || other.damageReductionFire > damageReductionFire) { damageReductionFire = other.damageReductionFire; modified = true; if (damageReductionFire > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_fire", damageReductionFire)); }
if (other.isForcedUpgrade() || other.damageReductionExplosions > damageReductionExplosions) { damageReductionExplosions = other.damageReductionExplosions; modified = true; if (damageReductionExplosions > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_explosions", damageReductionExplosions)); }
if (other.isForcedUpgrade() || other.healthRegeneration > healthRegeneration) { healthRegeneration = other.healthRegeneration; modified = true; if (healthRegeneration > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.health_regeneration", healthRegeneration)); }
if (other.isForcedUpgrade() || other.hungerRegeneration > hungerRegeneration) { hungerRegeneration = other.hungerRegeneration; modified = true; if (hungerRegeneration > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.hunger_regeneration", hungerRegeneration)); }
if (other.isForcedUpgrade() || other.speedIncrease > speedIncrease) { speedIncrease = other.speedIncrease; modified = true; if (speedIncrease > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.haste", speedIncrease)); }
// Mix colors
if (other.effectColor != null) {
if (this.effectColor == null || (other.isUpgrade() && other.effectColor != null)) {
this.effectColor = other.effectColor;
} else {
this.effectColor = this.effectColor.mixColor(other.effectColor, other.effectColorMixWeight);
}
modified = true;
}
if (other.rename && other.template != null && other.template.length() > 0) {
ConfigurationSection template = wandTemplates.get(other.template);
wandName = template.getString("name", wandName);
wandName = Messages.get("wands." + other.template + ".name", wandName);
updateName();
}
modified = modified | (!keep && other.keep);
modified = modified | (!bound && other.bound);
modified = modified | (!effectBubbles && other.effectBubbles);
modified = modified | (!undroppable && other.undroppable);
modified = modified | (!indestructible && other.indestructible);
keep = keep || other.keep;
bound = bound || other.bound;
indestructible = indestructible || other.indestructible;
undroppable = undroppable || other.undroppable;
effectBubbles = effectBubbles || other.effectBubbles;
if (other.effectParticle != null && (other.isUpgrade || effectParticle == null)) {
modified = modified | (effectParticle != other.effectParticle);
effectParticle = other.effectParticle;
modified = modified | (effectParticleData != other.effectParticleData);
effectParticleData = other.effectParticleData;
modified = modified | (effectParticleCount != other.effectParticleCount);
effectParticleCount = other.effectParticleCount;
modified = modified | (effectParticleInterval != other.effectParticleInterval);
effectParticleInterval = other.effectParticleInterval;
}
if (other.effectSound != null && (other.isUpgrade || effectSound == null)) {
modified = modified | (effectSound != other.effectSound);
effectSound = other.effectSound;
modified = modified | (effectSoundInterval != other.effectSoundInterval);
effectSoundInterval = other.effectSoundInterval;
modified = modified | (effectSoundVolume != other.effectSoundVolume);
effectSoundVolume = other.effectSoundVolume;
modified = modified | (effectSoundPitch != other.effectSoundPitch);
effectSoundPitch = other.effectSoundPitch;
}
if ((template == null || template.length() == 0) && (other.template != null && other.template.length() > 0)) {
modified = true;
template = other.template;
}
if (other.isUpgrade && other.mode != null) {
modified = modified | (mode != other.mode);
setMode(other.mode);
}
// Don't need mana if cost-free
if (isCostFree()) {
xpRegeneration = 0;
xpMax = 0;
xp = 0;
} else {
if (other.isForcedUpgrade() || other.xpRegeneration > xpRegeneration) { xpRegeneration = other.xpRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration)); }
if (other.isForcedUpgrade() || other.xpMax > xpMax) { xpMax = other.xpMax; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp)); }
if (other.isForcedUpgrade() || other.xp > xp) { xp = other.xp; modified = true; }
}
// Eliminate limited-use wands
if (uses == 0 || other.uses == 0) {
modified = modified | (uses != 0);
uses = 0;
} else {
// Otherwise add them
modified = modified | (other.uses != 0);
uses = uses + other.uses;
}
// Add spells
Set<String> spells = other.getSpells();
for (String spellKey : spells) {
if (addSpell(spellKey)) {
modified = true;
String spellName = spellKey;
SpellTemplate spell = controller.getSpellTemplate(spellKey);
if (spell != null) spellName = spell.getName();
if (mage != null) mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spellName));
}
}
// Add materials
Set<String> materials = other.getBrushes();
for (String materialKey : materials) {
if (addBrush(materialKey)) {
modified = true;
if (mage != null) mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey)));
}
}
Player player = (mage == null) ? null : mage.getPlayer();
if (other.autoFill && player != null) {
this.fill(player);
modified = true;
if (mage != null) mage.sendMessage(Messages.get("wand.filled"));
}
if (other.autoOrganize && mage != null) {
this.organizeInventory(mage);
modified = true;
if (mage != null) mage.sendMessage(Messages.get("wand.reorganized"));
}
saveState();
updateName();
updateLore();
return modified;
}
public boolean isForcedUpgrade()
{
return isUpgrade && forceUpgrade;
}
public boolean keepOnDeath() {
return keep;
}
public static void loadTemplates(ConfigurationSection properties) {
wandTemplates.clear();
Set<String> wandKeys = properties.getKeys(false);
for (String key : wandKeys)
{
ConfigurationSection wandNode = properties.getConfigurationSection(key);
wandNode.set("key", key);
ConfigurationSection existing = wandTemplates.get(key);
if (existing != null) {
Set<String> overrideKeys = existing.getKeys(false);
for (String propertyKey : overrideKeys) {
existing.set(propertyKey, existing.get(key));
}
} else {
wandTemplates.put(key, wandNode);
}
if (!wandNode.getBoolean("enabled", true)) {
wandTemplates.remove(key);
}
}
}
public static Collection<String> getWandKeys() {
return wandTemplates.keySet();
}
public static Collection<ConfigurationSection> getWandTemplates() {
return wandTemplates.values();
}
public static WandMode parseWandMode(String modeString, WandMode defaultValue) {
for (WandMode testMode : WandMode.values()) {
if (testMode.name().equalsIgnoreCase(modeString)) {
return testMode;
}
}
return defaultValue;
}
private void updateActiveMaterial() {
if (mage == null) return;
if (activeMaterial == null) {
mage.clearBuildingMaterial();
} else {
com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush();
brush.update(activeMaterial);
}
}
public void toggleInventory() {
if (!hasInventory) {
if (activeSpell == null || activeSpell.length() == 0) {
Set<String> spells = getSpells();
// Sanity check, so it'll switch to inventory next time
if (spells.size() > 1) hasInventory = true;
if (spells.size() > 0) {
activeSpell = spells.iterator().next();
}
}
updateName();
return;
}
if (!isInventoryOpen()) {
openInventory();
} else {
closeInventory();
}
}
@SuppressWarnings("deprecation")
public void cycleInventory() {
if (!hasInventory) {
return;
}
if (isInventoryOpen()) {
saveInventory();
int inventoryCount = inventories.size();
openInventoryPage = inventoryCount == 0 ? 0 : (openInventoryPage + 1) % inventoryCount;
updateInventory();
if (mage != null && inventories.size() > 1) {
mage.playSound(Sound.CHEST_OPEN, 0.3f, 1.5f);
mage.getPlayer().updateInventory();
}
}
}
@SuppressWarnings("deprecation")
private void openInventory() {
if (mage == null) return;
WandMode wandMode = getMode();
if (wandMode == WandMode.CHEST) {
inventoryIsOpen = true;
mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f);
updateInventory();
mage.getPlayer().openInventory(getDisplayInventory());
} else if (wandMode == WandMode.INVENTORY) {
if (mage.hasStoredInventory()) return;
if (mage.storeInventory()) {
inventoryIsOpen = true;
mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f);
updateInventory();
mage.getPlayer().updateInventory();
}
}
}
@SuppressWarnings("deprecation")
public void closeInventory() {
if (!isInventoryOpen()) return;
saveInventory();
inventoryIsOpen = false;
if (mage != null) {
mage.playSound(Sound.CHEST_CLOSE, 0.4f, 0.2f);
if (getMode() == WandMode.INVENTORY) {
mage.restoreInventory();
Player player = mage.getPlayer();
player.setItemInHand(item);
player.updateInventory();
} else {
mage.getPlayer().closeInventory();
}
}
}
public boolean fill(Player player) {
Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates();
for (SpellTemplate spell : allSpells)
{
if (spell.hasCastPermission(player) && spell.getIcon().getMaterial() != Material.AIR)
{
addSpell(spell.getKey());
}
}
autoFill = false;
saveState();
return true;
}
public void activate(Mage mage, ItemStack wandItem) {
if (mage == null || wandItem == null) return;
if (this.isUpgrade) {
controller.getLogger().warning("Activated an upgrade item- this shouldn't happen");
return;
}
// Update held item, it may have been copied since this wand was created.
this.item = wandItem;
this.mage = mage;
// Check for spell or other special icons in the player's inventory
Player player = mage.getPlayer();
boolean modified = false;
ItemStack[] items = player.getInventory().getContents();
for (int i = 0; i < items.length; i++) {
ItemStack item = items[i];
if (addItem(item)) {
modified = true;
items[i] = null;
}
}
if (modified) {
player.getInventory().setContents(items);
}
// Check for an empty wand and auto-fill
if (!isUpgrade && (controller.fillWands() || autoFill)) {
if (getSpells().size() == 0) {
fill(mage.getPlayer());
}
}
// Check for auto-organize
if (autoOrganize && !isUpgrade) {
organizeInventory(mage);
}
// Check for auto-bind
// Don't do this for op'd players, effectively, so
// they can create and give unbound wands.
if (bound && (ownerId == null || ownerId.length() == 0) && !controller.hasPermission(player, "Magic.wand.override_bind", false)) {
// Backwards-compatibility, don't overrwrite unless the
// name matches
if (owner == null || owner.length() == 0 || owner.equals(player.getName())) {
takeOwnership(mage.getPlayer());
saveState();
}
}
// Check for randomized wands
if (randomize) {
randomize();
}
checkActiveMaterial();
mage.setActiveWand(this);
if (usesMana()) {
storedXpLevel = player.getLevel();
storedXpProgress = player.getExp();
storedXp = 0;
updateMana();
}
updateActiveMaterial();
updateName();
updateLore();
updateEffects();
}
protected void randomize() {
boolean modified = randomize;
if (description.contains("$")) {
Matcher matcher = Messages.PARAMETER_PATTERN.matcher(description);
while(matcher.find()) {
String key = matcher.group(1);
if (key != null) {
modified = true;
description = description.replace("$" + key, Messages.getRandomized(key));
updateLore();
}
}
}
if (template != null && template.length() > 0) {
ConfigurationSection wandConfig = wandTemplates.get(template);
if (wandConfig != null && wandConfig.contains("icon")) {
String iconKey = wandConfig.getString("icon");
if (iconKey.contains(",")) {
Random r = new Random();
String[] keys = StringUtils.split(iconKey, ',');
iconKey = keys[r.nextInt(keys.length)];
}
setIcon(ConfigurationUtils.toMaterialAndData(iconKey));
modified = true;
}
}
randomize = false;
if (modified) {
saveState();
}
}
protected void checkActiveMaterial() {
if (activeMaterial == null || activeMaterial.length() == 0) {
Set<String> materials = getBrushes();
if (materials.size() > 0) {
activeMaterial = materials.iterator().next();
}
}
}
public boolean addItem(ItemStack item) {
if (isUpgrade) return false;
if (isSpell(item)) {
String spellKey = getSpell(item);
Set<String> spells = getSpells();
if (!spells.contains(spellKey) && addSpell(spellKey)) {
SpellTemplate spell = controller.getSpellTemplate(spellKey);
if (spell != null) {
mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spell.getName()));
return true;
}
}
} else if (isBrush(item)) {
String materialKey = getBrush(item);
Set<String> materials = getBrushes();
if (!materials.contains(materialKey) && addBrush(materialKey)) {
mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey)));
return true;
}
} else if (isUpgrade(item)) {
Wand wand = new Wand(controller, item);
return this.add(wand);
}
return false;
}
protected void updateEffects() {
if (mage == null) return;
Player player = mage.getPlayer();
if (player == null) return;
// Update Bubble effects effects
if (effectBubbles) {
CompatibilityUtils.addPotionEffect(player, effectColor.getColor());
}
Location location = mage.getLocation();
if (effectParticle != null && location != null) {
if ((effectParticleCounter++ % effectParticleInterval) == 0) {
if (effectPlayer == null) {
effectPlayer = new EffectRing(controller.getPlugin());
effectPlayer.setParticleCount(2);
effectPlayer.setIterations(2);
effectPlayer.setRadius(2);
effectPlayer.setSize(5);
effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN));
}
effectPlayer.setParticleType(effectParticle);
effectPlayer.setParticleData(effectParticleData);
effectPlayer.setParticleCount(effectParticleCount);
effectPlayer.start(player.getEyeLocation(), null);
}
}
if (effectSound != null && location != null && controller.soundsEnabled()) {
if ((effectSoundCounter++ % effectSoundInterval) == 0) {
mage.getLocation().getWorld().playSound(location, effectSound, effectSoundVolume, effectSoundPitch);
}
}
}
protected void updateMana() {
if (mage != null && xpMax > 0 && xpRegeneration > 0) {
Player player = mage.getPlayer();
if (displayManaAsBar) {
if (!retainLevelDisplay) {
player.setLevel(0);
}
player.setExp((float)xp / (float)xpMax);
} else {
player.setLevel(xp);
player.setExp(0);
}
}
}
public boolean isInventoryOpen() {
return mage != null && inventoryIsOpen;
}
public void deactivate() {
if (mage == null) return;
Player player = mage.getPlayer();
if (effectBubbles && player != null) {
CompatibilityUtils.removePotionEffect(player);
}
// This is a tying wands together with other spells, potentially
// But with the way the mana system works, this seems like the safest route.
mage.deactivateAllSpells();
if (isInventoryOpen()) {
closeInventory();
}
// Extra just-in-case
mage.restoreInventory();
if (usesMana() && player != null) {
player.setExp(storedXpProgress);
player.setLevel(storedXpLevel);
player.giveExp(storedXp);
storedXp = 0;
storedXpProgress = 0;
storedXpLevel = 0;
}
mage.setActiveWand(null);
mage = null;
saveState();
}
public Spell getActiveSpell() {
if (mage == null || activeSpell == null || activeSpell.length() == 0) return null;
return mage.getSpell(activeSpell);
}
public String getActiveSpellKey() {
return activeSpell;
}
public String getActiveBrushKey() {
return activeMaterial;
}
public boolean cast() {
Spell spell = getActiveSpell();
if (spell != null) {
use();
if (spell.cast(castParameters)) {
Color spellColor = spell.getColor();
if (spellColor != null && this.effectColor != null) {
this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight);
// Note that we don't save this change.
// The hope is that the wand will get saved at some point later
// And we don't want to trigger NBT writes every spell cast.
// And the effect color morphing isn't all that important if a few
// casts get lost.
}
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
protected void use() {
if (mage == null) return;
if (uses > 0) {
uses
if (uses <= 0) {
Player player = mage.getPlayer();
mage.playSound(Sound.ITEM_BREAK, 1.0f, 0.8f);
PlayerInventory playerInventory = player.getInventory();
playerInventory.setItemInHand(new ItemStack(Material.AIR, 1));
player.updateInventory();
deactivate();
} else {
updateName();
updateLore();
saveState();
}
}
}
public void onPlayerExpChange(PlayerExpChangeEvent event) {
if (mage == null) return;
if (addExperience(event.getAmount())) {
event.setAmount(0);
}
}
public boolean addExperience(int xp) {
if (usesMana()) {
storedXp += xp;
return true;
}
return false;
}
public void tick() {
if (mage == null) return;
Player player = mage.getPlayer();
if (player == null) return;
if (speedIncrease > 0) {
int hasteLevel = (int)(speedIncrease * WandLevel.maxHasteLevel);
if (hasteEffect == null || hasteEffect.getAmplifier() != hasteLevel) {
hasteEffect = new PotionEffect(PotionEffectType.SPEED, 80, hasteLevel, true);
}
CompatibilityUtils.applyPotionEffect(player, hasteEffect);
}
if (healthRegeneration > 0) {
int regenLevel = (int)(healthRegeneration * WandLevel.maxHealthRegeneration);
if (healthRegenEffect == null || healthRegenEffect.getAmplifier() != regenLevel) {
healthRegenEffect = new PotionEffect(PotionEffectType.REGENERATION, 80, regenLevel, true);
}
CompatibilityUtils.applyPotionEffect(player, healthRegenEffect);
}
if (hungerRegeneration > 0) {
int regenLevel = (int)(hungerRegeneration * WandLevel.maxHungerRegeneration);
if (hungerRegenEffect == null || hungerRegenEffect.getAmplifier() != regenLevel) {
hungerRegenEffect = new PotionEffect(PotionEffectType.SATURATION, 80, regenLevel, true);
}
CompatibilityUtils.applyPotionEffect(player, hungerRegenEffect);
}
if (usesMana()) {
xp = Math.min(xpMax, xp + xpRegeneration);
updateMana();
}
if (damageReductionFire > 0 && player.getFireTicks() > 0) {
player.setFireTicks(0);
}
updateEffects();
}
public MagicController getMaster() {
return controller;
}
public void cycleSpells(ItemStack newItem) {
if (isWand(newItem)) item = newItem;
Set<String> spellsSet = getSpells();
ArrayList<String> spells = new ArrayList<String>(spellsSet);
if (spells.size() == 0) return;
if (activeSpell == null) {
activeSpell = spells.get(0).split("@")[0];
return;
}
int spellIndex = 0;
for (int i = 0; i < spells.size(); i++) {
if (spells.get(i).split("@")[0].equals(activeSpell)) {
spellIndex = i;
break;
}
}
spellIndex = (spellIndex + 1) % spells.size();
setActiveSpell(spells.get(spellIndex).split("@")[0]);
}
public void cycleMaterials(ItemStack newItem) {
if (isWand(newItem)) item = newItem;
Set<String> materialsSet = getBrushes();
ArrayList<String> materials = new ArrayList<String>(materialsSet);
if (materials.size() == 0) return;
if (activeMaterial == null) {
activeMaterial = materials.get(0).split("@")[0];
return;
}
int materialIndex = 0;
for (int i = 0; i < materials.size(); i++) {
if (materials.get(i).split("@")[0].equals(activeMaterial)) {
materialIndex = i;
break;
}
}
materialIndex = (materialIndex + 1) % materials.size();
activateBrush(materials.get(materialIndex).split("@")[0]);
}
public boolean hasExperience() {
return xpRegeneration > 0;
}
public Mage getActivePlayer() {
return mage;
}
protected void clearInventories() {
inventories.clear();
hotbar.clear();
}
public Color getEffectColor() {
return effectColor == null ? null : effectColor.getColor();
}
public Inventory getHotbar() {
return hotbar;
}
public WandMode getMode() {
return mode != null ? mode : controller.getDefaultWandMode();
}
public void setMode(WandMode mode) {
this.mode = mode;
}
public boolean showCastMessages() {
return quietLevel == 0;
}
public boolean showMessages() {
return quietLevel < 2;
}
/*
* Public API Implementation
*/
@Override
public boolean isLost()
{
return this.id != null;
}
@Override
public boolean isLost(com.elmakers.mine.bukkit.api.wand.LostWand lostWand) {
return this.id != null && this.id.equals(lostWand.getId());
}
@Override
public LostWand makeLost(Location location)
{
if (id == null || id.length() == 0) {
id = UUID.randomUUID().toString();
saveState();
}
return new LostWand(this, location);
}
@Override
public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) {
Player player = mage.getPlayer();
if (!Wand.hasActiveWand(player)) {
controller.getLogger().warning("Wand activated without holding a wand!");
try {
throw new Exception("Wand activated without holding a wand!");
} catch (Exception ex) {
ex.printStackTrace();
}
return;
}
if (!canUse(player)) {
mage.sendMessage(Messages.get("wand.bound").replace("$name", owner));
player.setItemInHand(null);
Location location = player.getLocation();
location.setY(location.getY() + 1);
controller.addLostWand(makeLost(location));
saveState();
Item droppedItem = player.getWorld().dropItemNaturally(location, item);
Vector velocity = droppedItem.getVelocity();
velocity.setY(velocity.getY() * 2 + 1);
droppedItem.setVelocity(velocity);
return;
}
id = null;
if (mage instanceof Mage) {
activate((Mage)mage, player.getItemInHand());
}
}
@Override
public void organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) {
WandOrganizer organizer = new WandOrganizer(this, mage);
organizer.organize();
openInventoryPage = 0;
autoOrganize = false;
saveState();
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand duplicate() {
ItemStack newItem = InventoryUtils.getCopy(item);
Wand newWand = new Wand(controller, newItem);
newWand.saveState();
return newWand;
}
@Override
public boolean configure(Map<String, Object> properties) {
Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties);
loadProperties(ConfigurationUtils.toNodeList(convertedProperties), false);
saveState();
return true;
}
@Override
public boolean upgrade(Map<String, Object> properties) {
Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties);
loadProperties(ConfigurationUtils.toNodeList(convertedProperties), true);
saveState();
return true;
}
@Override
public boolean isLocked() {
return this.locked;
}
@Override
public void unlock() {
locked = false;
}
@Override
public boolean canUse(Player player) {
if (!bound || owner == null || owner.length() == 0) return true;
if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true;
// Backwards-compatibility
if (ownerId == null || ownerId.length() == 0) {
return owner.equalsIgnoreCase(player.getName());
}
return ownerId.equalsIgnoreCase(player.getUniqueId().toString());
}
public boolean addSpell(String spellName) {
if (!isModifiable()) return false;
if (hasSpell(spellName)) return false;
if (isInventoryOpen()) {
saveInventory();
}
SpellTemplate template = controller.getSpellTemplate(spellName);
if (template == null) {
controller.getLogger().warning("Tried to add unknown spell to wand: " + spellName);
return false;
}
if (hasSpell(template.getKey())) return false;
ItemStack spellItem = createSpellIcon(template);
if (spellItem == null) {
return false;
}
spells.add(template.getKey());
addToInventory(spellItem);
updateInventory();
hasInventory = getSpells().size() + getBrushes().size() > 1;
updateLore();
saveState();
return true;
}
@Override
public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) {
if (other instanceof Wand) {
return add((Wand)other);
}
return false;
}
@Override
public boolean hasBrush(String materialKey) {
return getBrushes().contains(materialKey);
}
@Override
public boolean hasSpell(String spellName) {
return getSpells().contains(spellName);
}
@Override
public boolean addBrush(String materialKey) {
if (!isModifiable()) return false;
if (hasBrush(materialKey)) return false;
if (isInventoryOpen()) {
saveInventory();
}
ItemStack itemStack = createBrushIcon(materialKey);
if (itemStack == null) return false;
brushes.add(materialKey);
addToInventory(itemStack);
if (activeMaterial == null || activeMaterial.length() == 0) {
setActiveBrush(materialKey);
} else {
updateInventory();
}
updateLore();
hasInventory = getSpells().size() + getBrushes().size() > 1;
saveState();
return true;
}
@Override
public void setActiveBrush(String materialKey) {
this.activeMaterial = materialKey;
updateName();
updateActiveMaterial();
updateHotbar();
saveState();
}
@Override
public void setActiveSpell(String activeSpell) {
this.activeSpell = activeSpell;
updateName();
saveState();
}
@Override
public boolean removeBrush(String materialKey) {
if (!isModifiable() || materialKey == null) return false;
if (isInventoryOpen()) {
saveInventory();
}
if (materialKey.equals(activeMaterial)) {
activeMaterial = null;
}
brushes.remove(materialKey);
List<Inventory> allInventories = getAllInventories();
boolean found = false;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int index = 0; index < items.length; index++) {
ItemStack itemStack = items[index];
if (itemStack != null && isBrush(itemStack)) {
String itemKey = getBrush(itemStack);
if (itemKey.equals(materialKey)) {
found = true;
inventory.setItem(index, null);
} else if (activeMaterial == null) {
activeMaterial = materialKey;
}
if (found && activeMaterial != null) {
break;
}
}
}
}
updateActiveMaterial();
updateInventory();
updateName();
updateLore();
saveState();
if (isInventoryOpen()) {
updateInventory();
}
return found;
}
@Override
public boolean removeSpell(String spellName) {
if (!isModifiable()) return false;
if (isInventoryOpen()) {
saveInventory();
}
if (spellName.equals(activeSpell)) {
activeSpell = null;
}
spells.remove(spellName);
List<Inventory> allInventories = getAllInventories();
boolean found = false;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int index = 0; index < items.length; index++) {
ItemStack itemStack = items[index];
if (itemStack != null && itemStack.getType() != Material.AIR && isSpell(itemStack)) {
if (getSpell(itemStack).equals(spellName)) {
found = true;
inventory.setItem(index, null);
} else if (activeSpell == null) {
activeSpell = getSpell(itemStack);
}
if (found && activeSpell != null) {
break;
}
}
}
}
updateName();
updateLore();
saveState();
updateInventory();
return found;
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc322.FRCTeam0322JavaCBR2015;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.RobotDrive.MotorType;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import java.util.Vector;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
public static SpeedController chassisFrontLeftMotor;
public static SpeedController chassisRearLeftMotor;
public static SpeedController chassisFrontRightMotor;
public static SpeedController chassisRearRightMotor;
public static RobotDrive chassisRobotDrive41;
public static DigitalOutput chassisFrontLeftBrake;
public static DigitalOutput chassisRearLeftBrake;
public static DigitalOutput chassisFrontRightBrake;
public static DigitalOutput chassisRearRightBrake;
public static Gyro chassisSensorsGyro1;
public static BuiltInAccelerometer chassisSensorsAccel1;
public static Encoder chassisSensorsFrontLeftEncoder;
public static Encoder chassisSensorsRearLeftEncoder;
public static Encoder chassisSensorsFrontRightEncoder;
public static Encoder chassisSensorsRearRightEncoder;
public static SpeedController leftArmRotator;
public static SpeedController rightArmRotator;
public static SpeedController leftArmWheel;
public static SpeedController rightArmWheel;
public static SpeedController liftLiftMotor;
public static CameraServer cameraServer;
public static int DRIVENUMAXIS = 4;
public static int DRIVENUMBUTTONS = 16;
public static int MANIPULATORNUMAXIS = 5;
public static int MANIPULATORNUMBUTTONS = 12;
public static void init() {
chassisFrontLeftMotor = new Talon(0);
LiveWindow.addActuator("Chassis", "FrontLeftMotor", (Talon) chassisFrontLeftMotor);
chassisRearLeftMotor = new Talon(1);
LiveWindow.addActuator("Chassis", "RearLeftMotor", (Talon) chassisRearLeftMotor);
chassisFrontRightMotor = new Talon(2);
LiveWindow.addActuator("Chassis", "FrontRightMotor", (Talon) chassisFrontRightMotor);
chassisRearRightMotor = new Talon(3);
LiveWindow.addActuator("Chassis", "RearRightMotor", (Talon) chassisRearRightMotor);
chassisRobotDrive41 = new RobotDrive(chassisFrontLeftMotor, chassisRearLeftMotor,
chassisFrontRightMotor, chassisRearRightMotor);
chassisRobotDrive41.setSafetyEnabled(true);
chassisRobotDrive41.setExpiration(0.1);
chassisRobotDrive41.setSensitivity(0.5);
chassisRobotDrive41.setMaxOutput(1.0);
chassisRobotDrive41.setInvertedMotor(MotorType.kRearLeft, false);
chassisRobotDrive41.setInvertedMotor(MotorType.kFrontLeft, false);
chassisRobotDrive41.setInvertedMotor(MotorType.kRearRight, true);
chassisRobotDrive41.setInvertedMotor(MotorType.kFrontRight, true);
chassisFrontLeftBrake = new DigitalOutput(0);
chassisRearLeftBrake = new DigitalOutput(1);
chassisFrontRightBrake = new DigitalOutput(2);
chassisRearRightBrake = new DigitalOutput(3);
chassisSensorsGyro1 = new Gyro(0);
LiveWindow.addSensor("Chassis Sensors", "Gyro 1", chassisSensorsGyro1);
chassisSensorsGyro1.setSensitivity(0.007);
chassisSensorsAccel1 = new BuiltInAccelerometer();
LiveWindow.addSensor("Chassis Sensors", "Accel 1", chassisSensorsAccel1);
chassisSensorsFrontLeftEncoder = new Encoder(4, 5, false);
LiveWindow.addSensor("Chassis Sensors", "Front Left Encoder", chassisSensorsFrontLeftEncoder);
chassisSensorsRearLeftEncoder = new Encoder(6, 7, false);
LiveWindow.addSensor("Chassis Sensors", "Rear Left Encoder", chassisSensorsRearLeftEncoder);
chassisSensorsFrontRightEncoder = new Encoder(8, 9, true);
LiveWindow.addSensor("Chassis Sensors", "Front Right Encoder", chassisSensorsFrontRightEncoder);
chassisSensorsRearRightEncoder = new Encoder(10, 11, true);
LiveWindow.addSensor("Chassis Sensors", "Rear Right Encoder", chassisSensorsRearRightEncoder);
leftArmRotator = new Talon(4);
LiveWindow.addActuator("LeftArm", "LeftArmRotator", (Talon) leftArmRotator);
rightArmRotator = new Talon(5);
LiveWindow.addActuator("RightArm", "RightArmRotator", (Talon) rightArmRotator);
leftArmWheel = new Talon(6);
LiveWindow.addActuator("LeftArmWheel", "LeftArmWheel", (Talon) leftArmWheel);
rightArmWheel = new Talon(7);
LiveWindow.addActuator("RightArmWheel", "RightArmWheel", (Talon) rightArmWheel);
liftLiftMotor = new Victor(8);
LiveWindow.addActuator("Lift", "LiftMotor", (Victor) liftLiftMotor);
cameraServer = CameraServer.getInstance();
cameraServer.setQuality(50);
cameraServer.startAutomaticCapture("cam0");
}
} |
package com.facebook.litho;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.LongSparseArray;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import com.facebook.R;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.reference.Reference;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.view.View.MeasureSpec.makeMeasureSpec;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentHostUtils.maybeInvalidateAccessibilityState;
import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState;
import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS;
import static com.facebook.litho.ComponentsLogger.EVENT_MOUNT;
import static com.facebook.litho.ComponentsLogger.EVENT_PREPARE_MOUNT;
import static com.facebook.litho.ComponentsLogger.EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH;
import static com.facebook.litho.ComponentsLogger.PARAM_IS_DIRTY;
import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG;
import static com.facebook.litho.ComponentsLogger.PARAM_MOUNTED_COUNT;
import static com.facebook.litho.ComponentsLogger.PARAM_MOVED_COUNT;
import static com.facebook.litho.ComponentsLogger.PARAM_NO_OP_COUNT;
import static com.facebook.litho.ComponentsLogger.PARAM_UNCHANGED_COUNT;
import static com.facebook.litho.ComponentsLogger.PARAM_UNMOUNTED_COUNT;
import static com.facebook.litho.ComponentsLogger.PARAM_UPDATED_COUNT;
import static com.facebook.litho.ThreadUtils.assertMainThread;
/**
* Encapsulates the mounted state of a {@link Component}. Provides APIs to update state
* by recycling existing UI elements e.g. {@link Drawable}s.
*
* @see #mount(LayoutState, Rect)
* @see ComponentView
* @see LayoutState
*/
class MountState {
static final int ROOT_HOST_ID = 0;
// Holds the current list of mounted items.
// Should always be used within a draw lock.
private final LongSparseArray<MountItem> mIndexToItemMap;
// Holds a list with information about the components linked to the VisibilityOutputs that are
// stored in LayoutState. An item is inserted in this map if its corresponding component is
// visible. When the component exits the viewport, the item associated with it is removed from the
// map.
private final LongSparseArray<VisibilityItem> mVisibilityIdToItemMap;
// Holds a list of MountItems that are currently mounted which can mount incrementally.
private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems;
// A map from test key to a list of one or more `TestItem`s which is only allocated
// and populated during test runs.
private final Map<String, Deque<TestItem>> mTestItemMap;
private long[] mLayoutOutputsIds;
// True if we are receiving a new LayoutState and we need to completely
// refresh the content of the HostComponent. Always set from the main thread.
private boolean mIsDirty;
// Holds the list of known component hosts during a mount pass.
private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>();
private static final Rect sTempRect = new Rect();
private final ComponentContext mContext;
private final ComponentView mComponentView;
private final Rect mPreviousLocalVisibleRect = new Rect();
private final PrepareMountStats mPrepareMountStats = new PrepareMountStats();
private final MountStats mMountStats = new MountStats();
private TransitionManager mTransitionManager;
private int mPreviousTopsIndex;
private int mPreviousBottomsIndex;
private int mLastMountedComponentTreeId;
private final MountItem mRootHostMountItem;
public MountState(ComponentView view) {
mIndexToItemMap = new LongSparseArray<>();
mVisibilityIdToItemMap = new LongSparseArray<>();
mCanMountIncrementallyMountItems = new LongSparseArray<>();
mContext = (ComponentContext) view.getContext();
mComponentView = view;
mIsDirty = true;
mTestItemMap = ComponentsConfiguration.isEndToEndTestRun
? new HashMap<String, Deque<TestItem>>()
: null;
// The mount item representing the top-level ComponentView which
// is always automatically mounted.
mRootHostMountItem = ComponentsPools.acquireRootHostMountItem(
HostComponent.create(),
mComponentView,
mComponentView);
}
/**
* To be called whenever the components needs to start the mount process from scratch
* e.g. when the component's props or layout change or when the components
* gets attached to a host.
*/
void setDirty() {
assertMainThread();
mIsDirty = true;
mPreviousLocalVisibleRect.setEmpty();
}
boolean isDirty() {
assertMainThread();
return mIsDirty;
}
/**
* Mount the layoutState on the pre-set HostView.
* @param layoutState
* @param localVisibleRect If this variable is null, then mount everything, since incremental
* mount is not enabled.
* Otherwise mount only what the rect (in local coordinates) contains
*/
void mount(LayoutState layoutState, Rect localVisibleRect) {
assertMainThread();
ComponentsSystrace.beginSection("mount");
final ComponentTree componentTree = mComponentView.getComponent();
final ComponentsLogger logger = componentTree.getContext().getLogger();
if (logger != null) {
logger.eventStart(EVENT_MOUNT, componentTree);
}
prepareTransitionManager(layoutState);
if (mTransitionManager != null) {
if (mIsDirty) {
mTransitionManager.onNewTransitionContext(layoutState.getTransitionContext());
}
mTransitionManager.onMountStart();
recordMountedItemsWithTransitionKeys(
mTransitionManager,
mIndexToItemMap,
true /* isPreMount */);
}
if (mIsDirty) {
suppressInvalidationsOnHosts(true);
// Prepare the data structure for the new LayoutState and removes mountItems
// that are not present anymore if isUpdateMountInPlace is enabled.
prepareMount(layoutState);
}
mMountStats.reset();
final int componentTreeId = layoutState.getComponentTreeId();
final boolean isIncrementalMountEnabled = localVisibleRect != null;
if (!isIncrementalMountEnabled ||
!performIncrementalMount(layoutState, localVisibleRect)) {
for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(i);
final Component component = layoutOutput.getComponent();
ComponentsSystrace.beginSection(component.getSimpleName());
final MountItem currentMountItem = getItemAt(i);
final boolean isMounted = currentMountItem != null;
final boolean isMountable =
!isIncrementalMountEnabled ||
isMountedHostWithChildContent(currentMountItem) ||
Rect.intersects(localVisibleRect, layoutOutput.getBounds());
if (isMountable && !isMounted) {
mountLayoutOutput(i, layoutOutput, layoutState);
} else if (!isMountable && isMounted) {
unmountItem(mContext, i, mHostsByMarker);
} else if (isMounted) {
if (isIncrementalMountEnabled && canMountIncrementally(component)) {
mountItemIncrementally(currentMountItem, layoutOutput.getBounds(), localVisibleRect);
}
if (mIsDirty) {
final boolean useUpdateValueFromLayoutOutput =
(componentTreeId >= 0) && (componentTreeId == mLastMountedComponentTreeId);
final boolean itemUpdated = updateMountItemIfNeeded(
layoutOutput,
currentMountItem,
useUpdateValueFromLayoutOutput,
logger);
if (itemUpdated) {
mMountStats.updatedCount++;
} else {
mMountStats.noOpCount++;
}
}
}
ComponentsSystrace.endSection();
}
if (isIncrementalMountEnabled) {
setupPreviousMountableOutputData(layoutState, localVisibleRect);
}
}
mIsDirty = false;
if (localVisibleRect != null) {
mPreviousLocalVisibleRect.set(localVisibleRect);
}
processVisibilityOutputs(layoutState, localVisibleRect);
if (mTransitionManager != null) {
recordMountedItemsWithTransitionKeys(
mTransitionManager,
mIndexToItemMap,
false /* isPreMount */);
mTransitionManager.processTransitions();
}
processTestOutputs(layoutState);
suppressInvalidationsOnHosts(false);
mLastMountedComponentTreeId = componentTreeId;
if (logger != null) {
final String logTag = componentTree.getContext().getLogTag();
logMountEnd(logger, logTag, componentTree, mMountStats);
}
ComponentsSystrace.endSection();
}
private void processVisibilityOutputs(LayoutState layoutState, Rect localVisibleRect) {
if (localVisibleRect == null) {
return;
}
for (int j = 0, size = layoutState.getVisibilityOutputCount(); j < size; j++) {
final VisibilityOutput visibilityOutput = layoutState.getVisibilityOutputAt(j);
final EventHandler visibleHandler = visibilityOutput.getVisibleEventHandler();
final EventHandler focusedHandler = visibilityOutput.getFocusedEventHandler();
final EventHandler fullImpressionHandler = visibilityOutput.getFullImpressionEventHandler();
final EventHandler invisibleHandler = visibilityOutput.getInvisibleEventHandler();
final long visibilityOutputId = visibilityOutput.getId();
final Rect visibilityOutputBounds = visibilityOutput.getBounds();
sTempRect.set(visibilityOutputBounds);
final boolean isCurrentlyVisible = sTempRect.intersect(localVisibleRect);
VisibilityItem visibilityItem = mVisibilityIdToItemMap.get(visibilityOutputId);
if (isCurrentlyVisible) {
// The component is visible now, but used to be outside the viewport.
if (visibilityItem == null) {
visibilityItem = ComponentsPools.acquireVisibilityItem(invisibleHandler);
mVisibilityIdToItemMap.put(visibilityOutputId, visibilityItem);
if (visibleHandler != null) {
EventDispatcherUtils.dispatchOnVisible(visibleHandler);
}
}
// Check if the component has entered the focused range.
if (focusedHandler != null && !visibilityItem.isInFocusedRange()) {
final View parent = (View) mComponentView.getParent();
if (hasEnteredFocusedRange(
parent.getWidth(),
parent.getHeight(),
visibilityOutputBounds,
sTempRect)) {
visibilityItem.setIsInFocusedRange();
EventDispatcherUtils.dispatchOnFocused(focusedHandler);
}
}
// If the component has not entered the full impression range yet, make sure to update the
// information about the visible edges.
if (fullImpressionHandler != null && !visibilityItem.isInFullImpressionRange()) {
visibilityItem.setVisibleEdges(visibilityOutputBounds, sTempRect);
if (visibilityItem.isInFullImpressionRange()) {
EventDispatcherUtils.dispatchOnFullImpression(fullImpressionHandler);
}
}
} else if (visibilityItem != null) {
// The component is invisible now, but used to be visible.
if (invisibleHandler != null) {
EventDispatcherUtils.dispatchOnInvisible(invisibleHandler);
}
mVisibilityIdToItemMap.remove(visibilityOutputId);
ComponentsPools.release(visibilityItem);
}
}
}
/**
* Clears and re-populates the test item map if we are in e2e test mode.
*/
private void processTestOutputs(LayoutState layoutState) {
if (mTestItemMap == null) {
return;
}
for (Collection<TestItem> items : mTestItemMap.values()) {
for (TestItem item : items) {
ComponentsPools.release(item);
}
}
mTestItemMap.clear();
for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) {
final TestOutput testOutput = layoutState.getTestOutputAt(i);
final long hostMarker = testOutput.getHostMarker();
final long layoutOutputId = testOutput.getLayoutOutputId();
final MountItem mountItem =
layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId);
final TestItem testItem = ComponentsPools.acquireTestItem();
testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker));
testItem.setBounds(testOutput.getBounds());
testItem.setTestKey(testOutput.getTestKey());
testItem.setContent(mountItem == null ? null : mountItem.getContent());
final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey());
final Deque<TestItem> updatedItems =
items == null ? new LinkedList<TestItem>() : items;
updatedItems.add(testItem);
mTestItemMap.put(testOutput.getTestKey(), updatedItems);
}
}
private boolean isMountedHostWithChildContent(MountItem mountItem) {
if (mountItem == null) {
return false;
}
final Object content = mountItem.getContent();
if (!(content instanceof ComponentHost)) {
return false;
}
final ComponentHost host = (ComponentHost) content;
return host.getMountItemCount() > 0;
}
private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) {
if (localVisibleRect.isEmpty()) {
return;
}
final ArrayList<LayoutOutput> layoutOutputTops = layoutState.getMountableOutputTops();
final ArrayList<LayoutOutput> layoutOutputBottoms = layoutState.getMountableOutputBottoms();
final int mountableOutputCount = layoutState.getMountableOutputCount();
mPreviousTopsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) {
mPreviousTopsIndex = i;
break;
}
}
mPreviousBottomsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) {
mPreviousBottomsIndex = i;
break;
}
}
}
private void clearVisibilityItems() {
for (int i = mVisibilityIdToItemMap.size() - 1; i >= 0; i
final VisibilityItem visibilityItem = mVisibilityIdToItemMap.valueAt(i);
final EventHandler invisibleHandler = visibilityItem.getInvisibleHandler();
if (invisibleHandler != null) {
EventDispatcherUtils.dispatchOnInvisible(invisibleHandler);
}
mVisibilityIdToItemMap.removeAt(i);
ComponentsPools.release(visibilityItem);
}
}
private void registerHost(long id, ComponentHost host) {
host.suppressInvalidations(true);
mHostsByMarker.put(id, host);
}
/**
* Returns true if the component has entered the focused visible range.
*/
static boolean hasEnteredFocusedRange(
int viewportWidth,
int viewportHeight,
Rect componentBounds,
Rect componentVisibleBounds) {
final int halfViewportArea = viewportWidth * viewportHeight / 2;
final int totalComponentArea = computeRectArea(componentBounds);
final int visibleComponentArea = computeRectArea(componentVisibleBounds);
// The component has entered the focused range either if it is larger than half of the viewport
// and it occupies at least half of the viewport or if it is smaller than half of the viewport
// and it is fully visible.
return (totalComponentArea >= halfViewportArea)
? (visibleComponentArea >= halfViewportArea)
: componentBounds.equals(componentVisibleBounds);
}
private static int computeRectArea(Rect rect) {
return rect.isEmpty() ? 0 : (rect.width() * rect.height());
}
private void suppressInvalidationsOnHosts(boolean suppressInvalidations) {
for (int i = mHostsByMarker.size() - 1; i >= 0; i
mHostsByMarker.valueAt(i).suppressInvalidations(suppressInvalidations);
}
}
private boolean updateMountItemIfNeeded(
LayoutOutput layoutOutput,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput,
ComponentsLogger logger) {
final Component layoutOutputComponent = layoutOutput.getComponent();
final Component itemComponent = currentMountItem.getComponent();
// 1. Check if the mount item generated from the old component should be updated.
final boolean shouldUpdate = shouldUpdateMountItem(
layoutOutput,
currentMountItem,
useUpdateValueFromLayoutOutput,
mIndexToItemMap,
mLayoutOutputsIds,
logger);
// 2. Reset all the properties like click handler, content description and tags related to
// this item if it needs to be updated. the update mount item will re-set the new ones.
if (shouldUpdate) {
unsetViewAttributes(currentMountItem);
}
// 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound.
if (currentMountItem.isBound()) {
itemComponent.getLifecycle().onUnbind(
itemComponent.getScopedContext(),
currentMountItem.getContent(),
itemComponent);
currentMountItem.setIsBound(false);
}
// 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput
currentMountItem.init(layoutOutput.getComponent(), currentMountItem, layoutOutput);
// 5. If the mount item is not valid for this component update its content and view attributes.
if (shouldUpdate) {
updateMountedContent(currentMountItem, layoutOutput, itemComponent);
setViewAttributes(currentMountItem);
}
final Object currentContent = currentMountItem.getContent();
// 6. Set the mounted content on the Component and call the bind callback.
layoutOutputComponent.getLifecycle().bind(
layoutOutputComponent.getScopedContext(),
currentContent,
layoutOutputComponent);
currentMountItem.setIsBound(true);
// 7. Update the bounds of the mounted content. This needs to be done regardless of whether
// the component has been updated or not since the mounted item might might have the same
// size and content but a different position.
updateBoundsForMountedLayoutOutput(layoutOutput, currentMountItem);
maybeInvalidateAccessibilityState(currentMountItem);
if (currentMountItem.getContent() instanceof Drawable) {
maybeSetDrawableState(
currentMountItem.getHost(),
(Drawable) currentMountItem.getContent(),
currentMountItem.getFlags(),
currentMountItem.getNodeInfo());
}
if (currentMountItem.getDisplayListDrawable() != null) {
currentMountItem.getDisplayListDrawable().suppressInvalidations(false);
}
return shouldUpdate;
}
private static boolean shouldUpdateMountItem(
LayoutOutput layoutOutput,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput,
LongSparseArray<MountItem> indexToItemMap,
long[] layoutOutputsIds,
ComponentsLogger logger) {
final @LayoutOutput.UpdateState int updateState = layoutOutput.getUpdateState();
final Component currentComponent = currentMountItem.getComponent();
final ComponentLifecycle currentLifecycle = currentComponent.getLifecycle();
final Component nextComponent = layoutOutput.getComponent();
final ComponentLifecycle nextLifecycle = nextComponent.getLifecycle();
// If the two components have different sizes and the mounted content depends on the size we
// just return true immediately.
if (!sameSize(layoutOutput, currentMountItem) && nextLifecycle.isMountSizeDependent()) {
return true;
}
if (useUpdateValueFromLayoutOutput) {
if (updateState == LayoutOutput.STATE_UPDATED) {
// Check for incompatible ReferenceLifecycle.
if (currentLifecycle instanceof DrawableComponent
&& nextLifecycle instanceof DrawableComponent
&& currentLifecycle.shouldComponentUpdate(currentComponent, nextComponent)) {
if (logger != null) {
ComponentsLogger.LayoutOutputLog logObj = new ComponentsLogger.LayoutOutputLog();
logObj.currentId = indexToItemMap.keyAt(
indexToItemMap.indexOfValue(currentMountItem));
logObj.currentLifecycle = currentLifecycle.toString();
logObj.nextId = layoutOutput.getId();
logObj.nextLifecycle = nextLifecycle.toString();
for (int i = 0; i < layoutOutputsIds.length; i++) {
if (layoutOutputsIds[i] == logObj.currentId) {
if (logObj.currentIndex == -1) {
logObj.currentIndex = i;
}
logObj.currentLastDuplicatedIdIndex = i;
}
}
if (logObj.nextId == logObj.currentId) {
logObj.nextIndex = logObj.currentIndex;
logObj.nextLastDuplicatedIdIndex = logObj.currentLastDuplicatedIdIndex;
} else {
for (int i = 0; i < layoutOutputsIds.length; i++) {
if (layoutOutputsIds[i] == logObj.nextId) {
if (logObj.nextIndex == -1) {
logObj.nextIndex = i;
}
logObj.nextLastDuplicatedIdIndex = i;
}
}
}
logger.eventStart(EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH, logObj);
logger
.eventEnd(EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH, logObj, ACTION_SUCCESS);
}
return true;
}
return false;
} else if (updateState == LayoutOutput.STATE_DIRTY) {
return true;
}
}
if (!currentLifecycle.callsShouldUpdateOnMount()) {
return true;
}
return currentLifecycle.shouldComponentUpdate(
currentComponent,
nextComponent);
}
private static boolean sameSize(LayoutOutput layoutOutput, MountItem item) {
final Rect layoutOutputBounds = layoutOutput.getBounds();
final Object mountedContent = item.getContent();
return layoutOutputBounds.width() == getWidthForMountedContent(mountedContent) &&
layoutOutputBounds.height() == getHeightForMountedContent(mountedContent);
}
private static int getWidthForMountedContent(Object content) {
return content instanceof Drawable ?
((Drawable) content).getBounds().width() :
((View) content).getWidth();
}
private static int getHeightForMountedContent(Object content) {
return content instanceof Drawable ?
((Drawable) content).getBounds().height() :
((View) content).getHeight();
}
private void updateBoundsForMountedLayoutOutput(LayoutOutput layoutOutput, MountItem item) {
// MountState should never update the bounds of the top-level host as this
// should be done by the ViewGroup containing the ComponentView.
if (layoutOutput.getId() == ROOT_HOST_ID) {
return;
}
layoutOutput.getMountBounds(sTempRect);
final boolean forceTraversal = Component.isMountViewSpec(layoutOutput.getComponent())
&& ((View) item.getContent()).isLayoutRequested();
applyBoundsToMountContent(
item.getContent(),
sTempRect.left,
sTempRect.top,
sTempRect.right,
sTempRect.bottom,
forceTraversal /* force */);
}
/**
* Prepare the {@link MountState} to mount a new {@link LayoutState}.
*/
@SuppressWarnings("unchecked")
private void prepareMount(LayoutState layoutState) {
final ComponentTree component = mComponentView.getComponent();
final ComponentsLogger logger = component.getContext().getLogger();
final String logTag = component.getContext().getLogTag();
if (logger != null) {
logger.eventStart(EVENT_PREPARE_MOUNT, component);
}
PrepareMountStats stats = unmountOrMoveOldItems(layoutState);
if (logger != null) {
logPrepareMountParams(logger, logTag, component, stats);
}
if (mHostsByMarker.get(ROOT_HOST_ID) == null) {
// Mounting always starts with the root host.
registerHost(ROOT_HOST_ID, mComponentView);
// Root host is implicitly marked as mounted.
mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem);
}
int outputCount = layoutState.getMountableOutputCount();
if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) {
mLayoutOutputsIds = new long[layoutState.getMountableOutputCount()];
}
for (int i = 0; i < outputCount; i++) {
mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getId();
}
if (logger != null) {
logger.eventEnd(EVENT_PREPARE_MOUNT, component, ACTION_SUCCESS);
}
}
/**
* Determine whether to apply disappear animation to the given {@link MountItem}
*/
private static boolean isItemDisappearing(
MountItem mountItem,
TransitionContext transitionContext) {
if (mountItem == null
|| mountItem.getViewNodeInfo() == null
|| transitionContext == null) {
return false;
}
return transitionContext.isDisappearingKey(mountItem.getViewNodeInfo().getTransitionKey());
}
/**
* Go over all the mounted items from the leaves to the root and unmount only the items that are
* not present in the new LayoutOutputs.
* If an item is still present but in a new position move the item inside its host.
* The condition where an item changed host doesn't need any special treatment here since we
* mark them as removed and re-added when calculating the new LayoutOutputs
*/
private PrepareMountStats unmountOrMoveOldItems(LayoutState newLayoutState) {
mPrepareMountStats.reset();
if (mLayoutOutputsIds == null) {
return mPrepareMountStats;
}
// Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there
// but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively
// all its mounted children.
for (int i = 0; i < mLayoutOutputsIds.length; i++) {
final int newPosition = newLayoutState.getLayoutOutputPositionForId(mLayoutOutputsIds[i]);
final MountItem oldItem = getItemAt(i);
if (isItemDisappearing(oldItem, newLayoutState.getTransitionContext())) {
startUnmountDisappearingItem(i, oldItem.getViewNodeInfo().getTransitionKey());
final int lastDescendantOfItem = findLastDescendantOfItem(i, oldItem);
// Disassociate disappearing items from current mounted items. The layout tree will not
// contain disappearing items anymore, however they are kept separately in their hosts.
removeDisappearingItemMappings(i, lastDescendantOfItem);
// Skip this disappearing item and all its descendants. Do not unmount or move them yet.
// We will unmount them after animation is completed.
i = lastDescendantOfItem;
continue;
}
if (newPosition == -1) {
unmountItem(mContext, i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else {
final long newHostMarker = newLayoutState.getMountableOutputAt(newPosition).getHostMarker();
if (oldItem == null) {
// This was previously unmounted.
mPrepareMountStats.unmountedCount++;
} else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) {
// If the id is the same but the parent host is different we simply unmount the item and
// re-mount it later. If the item to unmount is a ComponentHost, all the children will be
// recursively unmounted.
unmountItem(mContext, i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else if (newPosition != i) {
// If a MountItem for this id exists and the hostMarker has not changed but its position
// in the outputs array has changed we need to update the position in the Host to ensure
// the z-ordering.
oldItem.getHost().moveItem(oldItem, i, newPosition);
mPrepareMountStats.movedCount++;
} else {
mPrepareMountStats.unchangedCount++;
}
}
}
return mPrepareMountStats;
}
private void removeDisappearingItemMappings(int fromIndex, int toIndex) {
for (int i = fromIndex; i <= toIndex; i++) {
final MountItem item = getItemAt(i);
// We do not need this mapping for disappearing items.
mIndexToItemMap.remove(mLayoutOutputsIds[i]);
// Likewise we no longer need host mapping for disappearing items.
if (isHostSpec(item.getComponent())) {
mHostsByMarker
.removeAt(mHostsByMarker.indexOfValue((ComponentHost) item.getContent()));
}
}
}
/**
* Find the index of last descendant of given {@link MountItem}
*/
private int findLastDescendantOfItem(int disappearingItemIndex, MountItem item) {
for (int i = disappearingItemIndex + 1; i < mLayoutOutputsIds.length; i++) {
if (!ComponentHostUtils.hasAncestorHost(
getItemAt(i).getHost(),
(ComponentHost) item.getContent())) {
// No need to go further as the items that have common ancestor hosts are co-located.
// This is the first non-descendant of given MountItem, therefore last descendant is the
// item before.
return i - 1;
}
}
return mLayoutOutputsIds.length - 1;
}
private void updateMountedContent(
MountItem item,
LayoutOutput layoutOutput,
Component previousComponent) {
final Component<?> component = layoutOutput.getComponent();
if (isHostSpec(component)) {
return;
}
final Object previousContent = item.getContent();
final ComponentLifecycle lifecycle = component.getLifecycle();
// Call unmount and mount in sequence to make sure all the the resources are correctly
// de-allocated. It's possible for previousContent to equal null - when the root is
// interactive we create a LayoutOutput without content in order to set up click handling.
lifecycle.unmount(previousComponent.getScopedContext(), previousContent, previousComponent);
lifecycle.mount(component.getScopedContext(), previousContent, component);
}
private void mountLayoutOutput(int index, LayoutOutput layoutOutput, LayoutState layoutState) {
// 1. Resolve the correct host to mount our content to.
ComponentHost host = resolveComponentHost(layoutOutput, mHostsByMarker);
if (host == null) {
// Host has not yet been mounted - mount it now.
for (int hostMountIndex = 0, size = mLayoutOutputsIds.length;
hostMountIndex < size;
hostMountIndex++) {
if (mLayoutOutputsIds[hostMountIndex] == layoutOutput.getHostMarker()) {
final LayoutOutput hostLayoutOutput = layoutState.getMountableOutputAt(hostMountIndex);
mountLayoutOutput(hostMountIndex, hostLayoutOutput, layoutState);
break;
}
}
host = resolveComponentHost(layoutOutput, mHostsByMarker);
}
final Component<?> component = layoutOutput.getComponent();
final ComponentLifecycle lifecycle = component.getLifecycle();
// 2. Generate the component's mount state (this might also be a ComponentHost View).
Object content = acquireMountContent(component, host);
if (content == null) {
content = lifecycle.createMountContent(mContext);
}
lifecycle.mount(
component.getScopedContext(),
content,
component);
// 3. If it's a ComponentHost, add the mounted View to the list of Hosts.
if (isHostSpec(component)) {
ComponentHost componentHost = (ComponentHost) content;
componentHost.setParentHostMarker(layoutOutput.getHostMarker());
registerHost(layoutOutput.getId(), componentHost);
}
// 4. Mount the content into the selected host.
final MountItem item = mountContent(index, component, content, host, layoutOutput);
// 5. Notify the component that mounting has completed
lifecycle.bind(component.getScopedContext(), content, component);
item.setIsBound(true);
// 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling
// bind might have triggered a layout request within a View.
layoutOutput.getMountBounds(sTempRect);
applyBoundsToMountContent(
content,
sTempRect.left,
sTempRect.top,
sTempRect.right,
sTempRect.bottom,
true /* force */);
if (item.getDisplayListDrawable() != null) {
item.getDisplayListDrawable().suppressInvalidations(false);
}
// 6. Update the mount stats
mMountStats.mountedCount++;
}
// The content might be null because it's the LayoutSpec for the root host
// (the very first LayoutOutput).
private MountItem mountContent(
int index,
Component<?> component,
Object content,
ComponentHost host,
LayoutOutput layoutOutput) {
final MountItem item = ComponentsPools.acquireMountItem(
component,
host,
content,
layoutOutput);
// Create and keep a MountItem even for the layoutSpec with null content
// that sets the root host interactions.
mIndexToItemMap.put(mLayoutOutputsIds[index], item);
if (component.getLifecycle().canMountIncrementally()) {
mCanMountIncrementallyMountItems.put(index, item);
}
layoutOutput.getMountBounds(sTempRect);
host.mount(index, item, sTempRect);
setViewAttributes(item);
return item;
}
private Object acquireMountContent(Component<?> component, ComponentHost host) {
final ComponentLifecycle lifecycle = component.getLifecycle();
if (isHostSpec(component)) {
return host.recycleHost();
}
return ComponentsPools.acquireMountContent(mContext, lifecycle.getId());
}
private static void applyBoundsToMountContent(
Object content,
int left,
int top,
int right,
int bottom,
boolean force) {
assertMainThread();
if (content instanceof View) {
View view = (View) content;
int width = right - left;
int height = bottom - top;
if (force || view.getMeasuredHeight() != height || view.getMeasuredWidth() != width) {
view.measure(
makeMeasureSpec(right - left, MeasureSpec.EXACTLY),
makeMeasureSpec(bottom - top, MeasureSpec.EXACTLY));
}
if (force ||
view.getLeft() != left ||
view.getTop() != top ||
view.getRight() != right ||
view.getBottom() != bottom) {
view.layout(left, top, right, bottom);
}
} else if (content instanceof Drawable) {
((Drawable) content).setBounds(left, top, right, bottom);
} else {
throw new IllegalStateException("Unsupported mounted content " + content);
}
}
private static boolean canMountIncrementally(Component<?> component) {
return component.getLifecycle().canMountIncrementally();
}
/**
* Resolves the component host that will be used for the given layout output
* being mounted.
*/
private static ComponentHost resolveComponentHost(
LayoutOutput layoutOutput,
LongSparseArray<ComponentHost> hostsByMarker) {
final long hostMarker = layoutOutput.getHostMarker();
return hostsByMarker.get(hostMarker);
}
private static void setViewAttributes(MountItem item) {
final Component<?> component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
final View view = (View) item.getContent();
final NodeInfo nodeInfo = item.getNodeInfo();
if (nodeInfo != null) {
// 1. Setup click handler for the component, if applicable.
setClickHandler(nodeInfo.getClickHandler(), view);
// 2. Setup long click handler for the component, if applicable.
setLongClickHandler(nodeInfo.getLongClickHandler(), view);
// 3. Setup click handler for the component, if applicable.
setTouchHandler(nodeInfo.getTouchHandler(), view);
// 4. Set listeners for AccessibilityDelegate methods
setAccessibilityDelegate(view, nodeInfo);
// 5. Setup view tags for the component, if applicable.
setViewTag(view, nodeInfo.getViewTag());
setViewTags(view, nodeInfo.getViewTags());
// 6. Set content description.
setContentDescription(view, nodeInfo.getContentDescription());
// 7. Set setFocusable flag.
setFocusable(view, nodeInfo.getFocusState());
}
// 8. Set important for accessibility flag
setImportantForAccessibility(view, item.getImportantForAccessibility());
final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo();
if (viewNodeInfo != null && !isHostSpec(component)) {
// 9. Set view background, if applicable. Do this before padding
// as it otherwise overrides the padding.
setViewBackground(view, viewNodeInfo);
// 10. Set view padding, if applicable.
setViewPadding(view, viewNodeInfo);
// 11. Set view foreground, if applicable.
setViewForeground(view, viewNodeInfo);
// 12. Set view layout direction, if applicable.
setViewLayoutDirection(view, viewNodeInfo);
}
}
private static void unsetViewAttributes(MountItem item) {
final Component<?> component = item.getComponent();
if (!isMountViewSpec(component)) {
return;
}
final View view = (View) item.getContent();
final NodeInfo nodeInfo = item.getNodeInfo();
if (nodeInfo != null) {
// Reset the click handler.
if (nodeInfo.getClickHandler() != null) {
unsetClickHandler(view);
}
// Reset the click handler.
if (nodeInfo.getLongClickHandler() != null) {
unsetLongClickHandler(view);
}
// Reset the touch handler.
if (nodeInfo.getTouchHandler() != null) {
unsetTouchHandler(view);
}
// Reset the view tags.
unsetViewTag(view);
unsetViewTags(view, nodeInfo.getViewTags());
// Reset content description.
if (!TextUtils.isEmpty(nodeInfo.getContentDescription())) {
unsetContentDescription(view);
}
}
// Reset isClickable flag.
view.setClickable(MountItem.isViewClickable(item.getFlags()));
// Reset isLongClickable flag.
view.setLongClickable(MountItem.isViewLongClickable(item.getFlags()));
// Reset setFocusable flag.
unsetFocusable(view, item);
if (item.getImportantForAccessibility() != IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
unsetImportantForAccessibility(view);
}
unsetAccessibilityDelegate(view);
final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo();
if (viewNodeInfo != null && !isHostSpec(component)) {
unsetViewPadding(view, viewNodeInfo);
unsetViewBackground(view, viewNodeInfo);
unsetViewForeground(view, viewNodeInfo);
unsetViewLayoutDirection(view, viewNodeInfo);
}
}
/**
* Store a {@link ComponentAccessibilityDelegate} as a tag in {@code view}. {@link ComponentView}
* contains the logic for setting/unsetting it whenever accessibility is enabled/disabled
*
* For non {@link ComponentHost}s
* this is only done if any {@link EventHandler}s for accessibility events have been implemented,
* we want to preserve the original behaviour since {@code view} might have had
* a default delegate.
*/
private static void setAccessibilityDelegate(View view, NodeInfo nodeInfo) {
if (!(view instanceof ComponentHost) && !nodeInfo.hasAccessibilityHandlers()) {
return;
}
view.setTag(
R.id.component_node_info,
nodeInfo);
}
private static void unsetAccessibilityDelegate(View view) {
if (!(view instanceof ComponentHost)
&& view.getTag(R.id.component_node_info) == null) {
return;
}
view.setTag(R.id.component_node_info, null);
if (!(view instanceof ComponentHost)) {
ViewCompat.setAccessibilityDelegate(view, null);
}
}
/**
* Installs the click listeners that will dispatch the click handler
* defined in the component's props. Unconditionally set the clickable
* flag on the view.
*/
private static void setClickHandler(EventHandler clickHandler, View view) {
if (clickHandler == null) {
return;
}
ComponentClickListener listener = getComponentClickListener(view);
if (listener == null) {
listener = new ComponentClickListener();
setComponentClickListener(view, listener);
}
listener.setEventHandler(clickHandler);
view.setClickable(true);
} |
package com.game30.javagl.buffers;
import java.nio.Buffer;
import org.lwjgl.opengl.GL15;
import com.game30.javagl.GLDeletable;
import com.game30.javagl.GLIndexed;
import com.game30.javagl.GLObject;
/**
* An GLBuffer represents an OpenGL buffer. This is how data is passed back and forth to OpenGL from memory. All
* rendering data needs to be contained within a buffer before OpenGL can render it. Any calculations OpenGL does for
* the program will be output into a buffer. So to render graphics, or to get the results of a calculation, an OpenGL
* buffer needs to exist.
*
* <p />This interface provides some simple usage of an OpenGL buffer. Since a buffer is an OpenGL object, it can be
* bound and unbound from the current context. Each buffer has a specific {@link GLBufferTarget} that it is bound to.
* Only one buffer can be bound to a specific usage at a time. A buffer must be bound for data to be read or written to
* it.
*
* <p />OpenGL buffers also have an expected usage pattern. This describes to OpenGL how the buffer will be used.
* Buffers can be read-only, write-only, or have no access by the processor. The buffer can be considered static,
* dynamic or stream which describes how often the buffer might be accessed. See {@link GLBufferUsageAccess} for
* details on buffer access and {@link GLBufferUsageFrequency} for details on buffer access frequency. These two
* different details combine into the usage pattern of the buffer which is detailed by {@link GLBufferUsage}.
*
* @author Brian Norman
* @version 1.0.0-SNAPSHOT
* @since 1.0.0
*/
public interface GLBuffer extends GLObject {
@Override
default boolean exists() {
return GL15.glIsBuffer(getIndex());
}
@Override
default void delete() {
GL15.glDeleteBuffers(getIndex());
}
@Override
default void bind() {
GLDeletable.requireExists(this);
GL15.glBindBuffer(getTarget().glInt(), getIndex());
}
@Override
default void unbind() {
GLDeletable.requireExists(this);
GL15.glBindBuffer(getTarget().glInt(), GLIndexed.NULL_INDEX);
}
/**
* Returns the primitive type which the buffer object stores.
*
* @return buffer primitive type.
*/
GLBufferType getType();
/**
* Returns the target to which the buffer object is bound.
*
* @return buffer bind target.
*/
GLBufferTarget getTarget();
/**
* Returns the expected usage pattern of the buffer.
*
* @return buffer usage.
*/
GLBufferUsage getUsage();
/**
* Reads data from the OpenGL buffer and returns it as a {@link Buffer}.
*
* @return data from buffer.
*/
default Buffer read() {
if (GLBufferUsageAccess.Read != getUsage().getAccess()) {
throw new GLBufferException("Cannot read data to a [" + getUsage() + "] buffer.");
}
bind();
int size = getType().fromByteSize(GL15.glGetBufferParameteri(getTarget().glInt(), GL15.GL_BUFFER_SIZE));
Buffer buffer = getType().readFromBuffer(getTarget(), 0, size);
unbind();
return buffer;
}
/**
* Reads data from the OpenGL buffer at the specific offset for the specific length and returns it as a {@link
* Buffer}.
*
* @param offset the offset to start the read.
* @param length the length of the read.
* @return data from buffer range.
*/
default Buffer read(int offset, int length) {
if (GLBufferUsageAccess.Read != getUsage().getAccess()) {
throw new GLBufferException("Cannot read data to a [" + getUsage() + "] buffer.");
}
bind();
Buffer buffer = getType().readFromBuffer(getTarget(), offset, length);
unbind();
return buffer;
}
/**
* Writes data to the OpenGL buffer.
*
* @param data data to write.
*/
default void write(Buffer data) {
if (GLBufferUsageAccess.Write != getUsage().getAccess()) {
throw new GLBufferException("Cannot write data to a [" + getUsage() + "] buffer.");
}
bind();
getType().writeToBuffer(getTarget(), data, getUsage());
unbind();
}
} |
package com.github.tkurz.sesame.vocab;
import java.io.BufferedReader;
import java.io.Console;
import java.io.InputStreamReader;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.Rio;
public class Main {
public static void main(String [] args) throws Exception {
try {
String file = "ldp.ttl"; //"src/main/resources/ldp.ttl";
RDFFormat type = RDFFormat.RDFXML;
Console reader = System.console();
System.out.println("*** RDF Namespace Constants Constructor ***");
if(args.length > 0 && args[0] != null) {
file = args[0];
System.out.println("filepath : "+file);
} else {
System.out.println("insert filepath [" + file + "] : ");
String _file = reader.readLine();if(!_file.equals(""))file=_file;
}
if(args.length > 1 && args[1] != null) {
type = Rio.getParserFormatForMIMEType(args[1], type);
System.out.println("mimetype : "+type);
} else {
if(file.contains(".")) type = Rio.getParserFormatForFileName(file, type);
System.out.println("insert file mimetype [" + type.getDefaultMIMEType() + "] : ");
String _type=reader.readLine();if(!_type.equals(""))type=Rio.getParserFormatForFileName(_type, type);
}
//parse data and get url prefix
VocabBuilder e = new VocabBuilder(file,type);
System.out.println("insert url-prefix [" + e.prefix + "] : ");
String _prefix=reader.readLine();if(!_prefix.equals(""))e.prefix=_prefix;
System.out.println("insert class name [" + e.name + "] : ");
String _name=reader.readLine();if(!_name.equals(""))e.name=_name;
System.out.println("insert package name ["+e.packageName+"] : ");
String _pname=reader.readLine();if(!_pname.equals(""))e.packageName=_pname;
System.out.println("insert output folder ["+e.outputFolder+"] : ");
String _outputFolder=reader.readLine();if(!_outputFolder.equals(""))e.outputFolder=_outputFolder;
e.run();
System.out.println("*** file created: '"+e.outputFolder+"/"+e.name+".java' ***");
} catch(Exception e) {
e.printStackTrace();
throw e;
}
}
} |
package com.googlecode.objectify.impl;
import com.googlecode.objectify.util.LangUtils;
/**
* Path represents the individual steps from the root object to the current property.
*
* @author Jeff Schnitzer <jeff@infohazard.org>
*/
public class Path
{
/**
* Unfortunately, we made a mistake in the original definition of the ^null property for embedded
* collections. Instead of thing.^null we defined it as thing^null, which requires special casing.
* So we are fixing this now - we read thing^null as thing.^null, and always save as thing.^null.
* Some day in the far future we can remove this hack.
*/
public static final String NULL_INDEXES = "^null";
private static final Path ROOT = new Path("", null);
public static Path root() {
return ROOT;
}
/** This path segment. */
private final String segment;
/** The previous step in the path, null only for the special {@link #ROOT} element. */
private final Path previous;
private Path(String name, Path path) {
segment = name;
previous = path;
}
/** Convert an x.y.z path string back into a Path */
public static Path of(String pathString) {
if (pathString.length() == 0)
return ROOT;
else
return ofImpl(ROOT, pathString, 0);
}
/** Recursive implementation of of() */
private static Path ofImpl(Path here, String pathString, int begin) {
int end = pathString.indexOf('.', begin);
if (end < 0) {
String part = pathString.substring(begin);
// HACK HERE, see javadoc for NULL_INDEX
if (part.length() > NULL_INDEXES.length() && part.endsWith(NULL_INDEXES)) {
String base = part.substring(0, part.length()-NULL_INDEXES.length());
return here.extend(base).extend(NULL_INDEXES);
} else {
return here.extend(part);
}
} else {
String part = pathString.substring(begin, end);
return ofImpl(here.extend(part), pathString, end+1);
}
}
/** Create the full x.y.z string */
public String toPathString() {
if (this == ROOT) {
return "";
} else {
StringBuilder builder = new StringBuilder();
toPathString(builder);
return builder.toString();
}
}
private void toPathString(StringBuilder builder) {
if (previous != ROOT) {
previous.toPathString(builder);
builder.append('.');
}
builder.append(segment);
}
public Path extend(String name) {
return new Path(name, this);
}
/** Get this segment of the path. For root this will be null. */
public String getSegment() {
return segment;
}
/** Get the previous path; for root this will be null */
public Path getPrevious() {
return previous;
}
@Override
public String toString() {
return toPathString();
}
/** Compares on complete path */
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != this.getClass())
return false;
Path other = (Path)obj;
if (!this.segment.equals(other.segment))
return false;
else
return LangUtils.objectsEqual(this.previous, other.previous);
}
/** Generates hash code for complete path */
@Override
public int hashCode() {
int hash = segment.hashCode();
if (previous == null)
return hash;
else
return hash ^ previous.hashCode();
}
/** Convenient way to include path location in the exception message. Never returns. */
public Object throwIllegalState(String message) {
throw new IllegalStateException("At path '" + this + "': " + message);
}
/** Convenient way to include path location in the exception message. Never returns. */
public Object throwIllegalState(String message, Throwable cause) {
throw new IllegalStateException("At path '" + this + "': " + message, cause);
}
} |
package com.igumnov.common.orm;
import com.igumnov.common.Log;
import com.igumnov.common.Reflection;
import com.igumnov.common.reflection.ReflectionException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;
public class Transaction {
private Connection connection;
public Transaction(Connection c) throws SQLException {
connection = c;
c.setAutoCommit(false);
}
public void commit() throws SQLException {
try {
connection.commit();
} finally {
try {
connection.setAutoCommit(false);
} finally {
connection.close();
}
}
}
public void rollback() throws SQLException {
try {
connection.rollback();
} finally {
try {
connection.setAutoCommit(false);
} finally {
connection.close();
}
}
}
public Object update(Object obj) throws IllegalAccessException, SQLException {
LinkedHashMap<String, Object> fields = new LinkedHashMap<String, Object>();
String pkField = null;
Object pkFieldValue = null;
for (Field field : obj.getClass().getDeclaredFields()) {
boolean noAnnotation = true;
for (Annotation annotation : field.getDeclaredAnnotations())
if (annotation.annotationType().equals(Id.class)) {
noAnnotation = false;
pkField = field.getName();
field.setAccessible(true);
pkFieldValue = field.get(obj);
}
if (noAnnotation) {
field.setAccessible(true);
fields.put(field.getName(), field.get(obj));
}
}
String names = "";
Set<String> fieldsSet = fields.keySet();
// TODO Replace to StringBuffer
for ( String aFieldsSet : fieldsSet ) {
if ( names.length() != 0 ) {
names = names + ",";
}
names = names + aFieldsSet + "=?";
}
String sql = "update " + obj.getClass().getSimpleName() + " set " + names + " where " + pkField + "=?";
// System.out.println(sql);
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
Iterator<String> it = fieldsSet.iterator();
int i = 1;
while (it.hasNext()) {
Object value = fields.get(it.next());
preparedStatement.setObject(i, value);
// System.out.println(value);
++i;
}
preparedStatement.setObject(i, pkFieldValue);
// System.out.println(pkFieldValue);
Log.debug(sql);
preparedStatement.executeUpdate();
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception e) {
}
}
return obj;
}
public Object insert(Object obj) throws IllegalAccessException, SQLException, ReflectionException {
LinkedHashMap<String, Object> fields = new LinkedHashMap<String, Object>();
boolean autoGenerated = false;
String autoGeneratedField = null;
for (Field field : obj.getClass().getDeclaredFields()) {
boolean noAnnotation = true;
for (Annotation annotation : field.getDeclaredAnnotations())
if (annotation.annotationType().equals(Id.class)) {
Boolean autoIncremental = ((Id) annotation).autoIncremental();
if (autoIncremental) {
noAnnotation = false;
autoGenerated = true;
autoGeneratedField = field.getName();
}
}
if (noAnnotation) {
field.setAccessible(true);
fields.put(field.getName(), field.get(obj));
}
}
String names = "";
String values = "";
Set<String> fieldsSet = fields.keySet();
// TODO Replace to StringBuffer
for ( String aFieldsSet : fieldsSet ) {
if ( names.length() != 0 ) {
names = names + ",";
}
names = names + aFieldsSet;
if ( values.length() != 0 ) {
values = values + ",";
}
values = values + "?";
}
String sql = "insert into " + obj.getClass().getSimpleName() + "(" + names + ") values (" + values + ")";
PreparedStatement preparedStatement = null;
try {
if (!autoGenerated) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
Iterator<String> it = fieldsSet.iterator();
int i = 1;
while (it.hasNext()) {
preparedStatement.setObject(i, fields.get(it.next()));
++i;
}
Log.debug(sql);
preparedStatement.executeUpdate();
if (autoGenerated) {
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
Object autoGeneratedID = tableKeys.getObject(1);
Reflection.setField(obj, autoGeneratedField, autoGeneratedID);
}
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception e) {
}
}
return obj;
}
public ArrayList<Object> findBy(String where, Class classObject, Object... params) throws SQLException, IllegalAccessException, InstantiationException, ReflectionException {
ArrayList<Object> ret = new ArrayList<Object>();
String names = "";
for (Field field : classObject.getDeclaredFields()) {
field.setAccessible(true);
if (names.length() > 0) {
names = names + ",";
}
names = names + field.getName();
}
String sql;
if (where == null) {
sql = "select " + names + " from " + classObject.getSimpleName();
} else {
sql = "select " + names + " from " + classObject.getSimpleName() + " where " + where;
}
//System.out.println(sql);
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
int i = 1;
for (Object param : params) {
preparedStatement.setObject(i, param);
++i;
}
Log.debug(sql);
ResultSet r = preparedStatement.executeQuery();
while (r.next()) {
Object row = classObject.newInstance();
for (Field field : classObject.getDeclaredFields()) {
field.setAccessible(true);
Reflection.setField(row, field.getName(), r.getObject(field.getName()));
}
ret.add(row);
}
r.close();
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception e) {
}
}
return ret;
}
public Object findOne(Class className, Object primaryKey) throws SQLException, ReflectionException, InstantiationException, IllegalAccessException {
String pkName = null;
for (Field field : className.getDeclaredFields()) {
for (Annotation annotation : field.getDeclaredAnnotations())
if (annotation.annotationType().equals(Id.class)) {
pkName = field.getName();
}
}
return findBy(pkName + "=?",className, primaryKey).get(0);
}
public int deleteBy(String where, Class classObject, Object... params) throws SQLException {
String sql = "delete from " + classObject.getSimpleName() + " where " + where;
// System.out.println(sql);
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
int i = 1;
for (Object param : params) {
preparedStatement.setObject(i, param);
++i;
}
Log.debug(sql);
return preparedStatement.executeUpdate();
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception e) {
}
}
}
public int delete(Object obj) throws IllegalAccessException, SQLException {
String pkName = null;
Object pkValue = null;
for (Field field : obj.getClass().getDeclaredFields()) {
for (Annotation annotation : field.getDeclaredAnnotations())
if (annotation.annotationType().equals(Id.class)) {
pkName = field.getName();
field.setAccessible(true);
pkValue = field.get(obj);
}
}
return deleteBy(pkName+"=?", obj.getClass(), pkValue);
}
public ArrayList<Object> findAll(Class classObject) throws SQLException, ReflectionException, InstantiationException, IllegalAccessException {
return findBy(null, classObject);
}
} |
package de.is24.util.monitoring;
import de.is24.util.monitoring.jmx.InApplicationMonitorJMXConnector;
import de.is24.util.monitoring.jmx.JmxAppMon4JNamingStrategy;
import de.is24.util.monitoring.keyhandler.KeyHandler;
import de.is24.util.monitoring.keyhandler.TransparentKeyHandler;
import de.is24.util.monitoring.tools.VirtualMachineMetrics;
import org.apache.log4j.Logger;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* This plugin represents the former core functionality of InApplicationMonitor, on a way to a more
* flexible implementation by plugins, to simplify testing and the first step on the way fo a more
* dependency injection friendly implementation.
*
* This plugin will take over some functionality that only makes sense in the context of a plugin that stores
* data locally in the JVM. Other plugins (namely the statsd plugin) move data aggregation out of the JVM.
* And thus it makes no sense to let them implement some of the patterns like reportableObserver etc.
*/
public class CorePlugin extends AbstractMonitorPlugin {
private static Logger LOGGER = Logger.getLogger(CorePlugin.class);
protected volatile boolean monitorActive = true;
private volatile int maxHistoryEntriesToKeep = 5;
private final CopyOnWriteArrayList<ReportableObserver> reportableObservers =
new CopyOnWriteArrayList<ReportableObserver>();
private final Monitors<Counter> countersTimers = new Monitors<Counter>(reportableObservers);
private final Monitors<StateValueProvider> stateValues = new Monitors<StateValueProvider>(reportableObservers);
private final Monitors<Version> versions = new Monitors<Version>(reportableObservers);
private final Monitors<HistorizableList> historizableLists = new Monitors<HistorizableList>(reportableObservers);
private volatile InApplicationMonitorJMXConnector inApplicationMonitorJMXConnector;
private KeyHandler keyHandler;
private static final String semaphore = "CorePluginSemaphore";
public CorePlugin(JmxAppMon4JNamingStrategy jmxAppMon4JNamingStrategy, KeyHandler keyHandler) {
synchronized (semaphore) {
if (keyHandler != null) {
this.keyHandler = keyHandler;
} else {
this.keyHandler = new TransparentKeyHandler();
}
if (jmxAppMon4JNamingStrategy != null) {
inApplicationMonitorJMXConnector = new InApplicationMonitorJMXConnector(this,
jmxAppMon4JNamingStrategy);
}
initDefaultStateValues();
}
}
public void initDefaultStateValues() {
registerStateValue(new StateValueProvider() {
@Override
public String getName() {
return Runtime.class.getName() + ".totalMem";
}
@Override
public long getValue() {
return Runtime.getRuntime().totalMemory();
}
});
registerStateValue(new StateValueProvider() {
@Override
public String getName() {
return Runtime.class.getName() + ".freeMem";
}
@Override
public long getValue() {
return Runtime.getRuntime().freeMemory();
}
});
registerVersion(new Version(this.getClass().getName(),
"$Id$"));
VirtualMachineMetrics.registerVMStates(this);
}
@Override
public void afterRemovalNotification() {
destroy();
}
public synchronized void destroy() {
synchronized (semaphore) {
if (isJMXInitialized()) {
inApplicationMonitorJMXConnector.shutdown();
inApplicationMonitorJMXConnector = null;
}
}
}
@Override
public String getUniqueName() {
return "CorePlugin";
}
private boolean isJMXInitialized() {
return inApplicationMonitorJMXConnector != null;
}
/**
* @return Number of entries to keep for each Historizable list.
*/
public int getMaxHistoryEntriesToKeep() {
return maxHistoryEntriesToKeep;
}
/**
* Set the Number of entries to keep for each Historizable list.
* Default is 5.
*
* @param aMaxHistoryEntriesToKeep Number of entries to keep
*/
public void setMaxHistoryEntriesToKeep(int aMaxHistoryEntriesToKeep) {
maxHistoryEntriesToKeep = aMaxHistoryEntriesToKeep;
}
/**
* adds a new ReportableObserver that wants to be notified about new Reportables that are
* registered on the InApplicationMonitor
* @param reportableObserver the class that wants to be notified
*/
public void addReportableObserver(final ReportableObserver reportableObserver) {
reportableObservers.add(reportableObserver);
LOGGER.info("registering new ReportableObserver (" + reportableObserver.getClass().getName() + ")");
// iterate over all reportables that are registered already and call the observer for each one of them
reportInto(new ReportVisitor() {
public void notifyReportableObserver(Reportable reportable) {
reportableObserver.addNewReportable(reportable);
}
@Override
public void reportCounter(Counter counter) {
notifyReportableObserver(counter);
}
@Override
public void reportTimer(Timer timer) {
notifyReportableObserver(timer);
}
@Override
public void reportStateValue(StateValueProvider stateValueProvider) {
notifyReportableObserver(stateValueProvider);
}
@Override
public void reportHistorizableList(HistorizableList historizableList) {
notifyReportableObserver(historizableList);
}
@Override
public void reportVersion(Version version) {
notifyReportableObserver(version);
}
});
}
private void notifyReportableObservers(Reportable reportable) {
for (ReportableObserver reportableObserver : reportableObservers) {
reportableObserver.addNewReportable(reportable);
}
}
/**
* Allow disconnection of observers, mainly for testing
*
* @param reportableObserver
*/
public void removeReportableObserver(final ReportableObserver reportableObserver) {
reportableObservers.remove(reportableObserver);
}
/**
* Implements the {@link de.is24.util.monitoring.InApplicationMonitor} side of the Visitor pattern.
* Iterates through all registered {@link de.is24.util.monitoring.Reportable} instances and calls
* the corresponding method on the {@link de.is24.util.monitoring.ReportVisitor} implementation.
* @param reportVisitor The {@link de.is24.util.monitoring.ReportVisitor} instance that shall be visited
* by all regieteres {@link de.is24.util.monitoring.Reportable} instances.
*/
public void reportInto(ReportVisitor reportVisitor) {
countersTimers.accept(reportVisitor);
stateValues.accept(reportVisitor);
versions.accept(reportVisitor);
historizableLists.accept(reportVisitor);
}
/**
* <p>Increase the specified counter by a variable amount.</p>
*
* @param name
* the name of the {@code Counter} to increase
* @param increment
* the added to add
*/
public void incrementCounter(String name, int increment) {
incrementInternalCounter(increment, name);
}
@Override
public void incrementHighRateCounter(String name, int increment) {
incrementInternalCounter(increment, name);
}
private void incrementInternalCounter(int increment, String name) {
getCounter(name).increment(increment);
}
/**
* Initialization of a counter.
* @param name the name of the counter to be initialized
*/
public void initializeCounter(String name) {
getCounter(name).initialize();
}
/**
* Add a timer measurement for the given name.
* {@link de.is24.util.monitoring.Timer}s allow adding timer measurements, implicitly incrementing the count
* Timers count and measure timed events.
* The application decides which unit to use for timing.
* Miliseconds are suggested and some {@link de.is24.util.monitoring.ReportVisitor} implementations
* may imply this.
*
* @param name name of the {@link de.is24.util.monitoring.Timer}
* @param timing number of elapsed time units for a single measurement
*/
public void addTimerMeasurement(String name, long timing) {
getTimer(name).addMeasurement(timing);
}
/**
* Add a timer measurement for a rarely occuring event with given name.
* This allows Plugins to to react on the estimated rate of the event.
* Namely the statsd plugin will not sent these , as the requires storage
* is in no relation to the value of the data.
* {@link de.is24.util.monitoring.Timer}s allow adding timer measurements, implicitly incrementing the count
* Timers count and measure timed events.
* The application decides which unit to use for timing.
* Miliseconds are suggested and some {@link de.is24.util.monitoring.ReportVisitor} implementations
* may imply this.
*
* @param name name of the {@link de.is24.util.monitoring.Timer}
* @param timing number of elapsed time units for a single measurement
*/
public void addSingleEventTimerMeasurement(String name, long timing) {
addTimerMeasurement(name, timing);
}
/**
* Add a timer measurement for a rarely occuring event with given name.
* This allows Plugins to to react on the estimated rate of the event.
* Namely the statsd plugin will not sent these , as the requires storage
* is in no relation to the value of the data.
* {@link de.is24.util.monitoring.Timer}s allow adding timer measurements, implicitly incrementing the count
* Timers count and measure timed events.
* The application decides which unit to use for timing.
* Miliseconds are suggested and some {@link de.is24.util.monitoring.ReportVisitor} implementations
* may imply this.
*
* @param name name of the {@link de.is24.util.monitoring.Timer}
* @param timing number of elapsed time units for a single measurement
*/
public void addHighRateTimerMeasurement(String name, long timing) {
addTimerMeasurement(name, timing);
}
/**
* Initialization of a TimerMeasurement
* @param name the name of the timer to be initialized
*/
public void initializeTimerMeasurement(String name) {
getTimer(name).initializeMeasurement();
}
/**
* Add a state value provider to this appmon4j instance.
* {@link de.is24.util.monitoring.StateValueProvider} instances allow access to a numeric
* value (long), that is already available in the application.
*
* @param stateValueProvider the StateValueProvider instance to add
*/
public void registerStateValue(StateValueProvider stateValueProvider) {
String name = keyHandler.handle(stateValueProvider.getName());
StateValueProvider oldProvider = stateValues.put(name, stateValueProvider);
if (oldProvider != null) {
LOGGER.warn("StateValueProvider [" + oldProvider + "] @" + stateValueProvider.getName() +
" has been replaced by [" + stateValueProvider + "]!");
}
notifyReportableObservers(stateValueProvider);
}
/**
* This method was intended to register module names with their
* current version identifier.
* This could / should actually be generalized into an non numeric
* state value
*
* @param versionToAdd The Version Object to add
*/
public void registerVersion(Version versionToAdd) {
String versionName = keyHandler.handle(versionToAdd.getName());
versions.put(versionName, versionToAdd);
notifyReportableObservers(versionToAdd);
}
/**
* add a {@link de.is24.util.monitoring.Historizable} instance to the list identified by historizable.getName()
*
* @param historizable the historizable to add
*/
public void addHistorizable(String name, Historizable historizable) {
HistorizableList listToAddTo = getHistorizableList(name);
listToAddTo.add(historizable);
}
/**
* @param name the name of the StatsValueProvider
* @return the StatsValueProvider
*/
StateValueProvider getStateValue(String name) {
return stateValues.get(name);
}
/**
* internally used method to retrieve or create and register a named {@link de.is24.util.monitoring.Counter}.
* @param name of the required {@link de.is24.util.monitoring.Counter}
* @return {@link de.is24.util.monitoring.Counter} instance registered for the given name
*/
Counter getCounter(final String name) {
return countersTimers.get("counter." + name, new Monitors.Factory<Counter>() {
@Override
public Counter createMonitor() {
return new Counter(name);
}
});
}
/**
* internaly used method to retrieve or create and register a named {@link de.is24.util.monitoring.Timer}.
* @param name of the required {@link de.is24.util.monitoring.Timer}
* @return {@link de.is24.util.monitoring.Timer} instance registered for the given name
*/
Timer getTimer(final String name) {
return (Timer) countersTimers.get("timer." + name, new Monitors.Factory<Counter>() {
@Override
public Counter createMonitor() {
return new Timer(name);
}
});
}
/**
* internally used method to retrieve or create and register a named HistorizableList.
* @param name of the required {@link de.is24.util.monitoring.HistorizableList}
* @return {@link de.is24.util.monitoring.HistorizableList} instance registered for the given name
*/
HistorizableList getHistorizableList(final String name) {
return historizableLists.get(name, new Monitors.Factory<HistorizableList>() {
@Override
public HistorizableList createMonitor() {
return new HistorizableList(name, maxHistoryEntriesToKeep);
}
});
}
} |
package de.onyxbits.raccoon.gui;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import de.onyxbits.raccoon.Messages;
import de.onyxbits.raccoon.io.Archive;
/**
* A container for putting search results in.
*
* @author patrick
*
*/
public class SearchView extends JPanel implements ActionListener, ChangeListener, Runnable {
private static final long serialVersionUID = 1L;
protected Archive archive;
private static final String CARDRESULTS = "results"; //$NON-NLS-1$
private static final String CARDPROGRESS = "progress"; //$NON-NLS-1$
private static final String CARDMESSAGE = "message"; //$NON-NLS-1$
private JTextField query;
private JSpinner page;
private JScrollPane results;
private JProgressBar progress;
private JLabel message;
private JPanel main;
private CardLayout cardLayout;
private MainActivity mainActivity;
private SearchView(MainActivity mainActivity, Archive archive) {
this.archive = archive;
this.mainActivity = mainActivity;
setLayout(new BorderLayout());
query = new JTextField();
query.setToolTipText(Messages.getString("SearchView.3")); //$NON-NLS-1$
page = new JSpinner(new SpinnerNumberModel(1, 1, 10000, 1));
page.setToolTipText(Messages.getString("SearchView.4")); //$NON-NLS-1$
results = new JScrollPane();
cardLayout = new CardLayout();
message = new JLabel();
progress = new JProgressBar();
progress.setIndeterminate(true);
progress.setString(Messages.getString("SearchView.5")); //$NON-NLS-1$
progress.setStringPainted(true);
GridBagConstraints center = new GridBagConstraints();
center.anchor = GridBagConstraints.CENTER;
center.fill = GridBagConstraints.NONE;
main = new JPanel();
main.setLayout(cardLayout);
JPanel container = new JPanel();
container.setOpaque(false);
container.setLayout(new GridBagLayout());
container.add(message, center);
JScrollPane scroller = new JScrollPane(container);
main.add(scroller, CARDMESSAGE);
main.add(results, CARDRESULTS);
container = new JPanel();
container.setOpaque(false);
container.setLayout(new GridBagLayout());
container.add(progress, center);
scroller = new JScrollPane(container);
main.add(scroller, CARDPROGRESS);
container = new JPanel();
container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
container.add(query);
container.add(page);
add(container, BorderLayout.NORTH);
add(main, BorderLayout.CENTER);
}
public static SearchView create(MainActivity mainActivity, Archive archive) {
SearchView ret = new SearchView(mainActivity, archive);
ret.query.addActionListener(ret);
ret.page.addChangeListener(ret);
return ret;
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == query) {
page.setValue(1);
doSearch();
}
}
public void stateChanged(ChangeEvent event) {
if (event.getSource() == page) {
doSearch();
}
// Slightly ugly: a searchview is meant to sit in a JTabbedPane and
// registered as it's ChangeListener, so the query can get focus whenever
// the user switches to this view. In fact, we consider the query field to
// be so important that we always focus it, no matter what.
query.requestFocusInWindow();
}
/**
* After adding this view to a JTabbedPane, post it to the EDT via
* SwingUtils.invokeLater() to ensure the query gets the inputfocus.
*/
public void run() {
query.requestFocusInWindow();
}
protected void doSearch() {
if (query.getText().length() == 0) {
doMessage(Messages.getString("SearchView.6")); //$NON-NLS-1$
}
else {
query.setEnabled(false);
page.setEnabled(false);
cardLayout.show(main, CARDPROGRESS);
int offset = (Integer) page.getValue();
offset = (offset - 1) * 10;
new SearchWorker(archive, query.getText(), this).withOffset(offset).withLimit(10).execute();
}
}
protected void doMessage(String status) {
query.setEnabled(true);
page.setEnabled(true);
cardLayout.show(main, CARDMESSAGE);
message.setText(status);
}
protected void doResultList(JPanel listing) {
query.setEnabled(true);
page.setEnabled(true);
cardLayout.show(main, CARDRESULTS);
results.setViewportView(listing);
}
public void doUpdateSearch() {
query.setEnabled(false);
page.setEnabled(false);
cardLayout.show(main, CARDPROGRESS);
new SearchWorker(archive, null, this).execute();
}
protected void doDownload(DownloadView d) {
if (d.isDownloaded()) {
int result = JOptionPane.showConfirmDialog(getRootPane(), Messages.getString("SearchView.7"), Messages.getString("SearchView.8"), //$NON-NLS-1$ //$NON-NLS-2$
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
mainActivity.doDownload(d);
}
}
else {
mainActivity.doDownload(d);
}
}
public Archive getArchive() {
return archive;
}
} |
package edu.hm.hafner.analysis;
import java.io.Serializable;
import java.util.stream.Stream;
/**
* Parses a file and returns the issues reported in this file.
*
* @author Ullrich Hafner
*/
public abstract class IssueParser implements Serializable {
private static final long serialVersionUID = 200992696185460268L;
/**
* Parses the specified file for issues.
*
* @param readerFactory
* provides a reader to the reports
*
* @return the issues
* @throws ParsingException
* Signals that during parsing a non recoverable error has been occurred
* @throws ParsingCanceledException
* Signals that the parsing has been aborted by the user
*/
public abstract Report parse(ReaderFactory readerFactory)
throws ParsingException, ParsingCanceledException;
/**
* Parses the specified file for issues. Invokes the parser using {@link #parse(ReaderFactory)} and sets the file
* name of the report.
*
* @param readerFactory
* provides a reader to the reports
*
* @return the issues
* @throws ParsingException
* Signals that during parsing a non recoverable error has been occurred
* @throws ParsingCanceledException
* Signals that the parsing has been aborted by the user
*/
public Report parseFile(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException {
Report report = parse(readerFactory);
report.addFileName(readerFactory.getFileName());
return report;
}
/**
* Returns whether this parser accepts the specified file as valid input. Parsers may reject a file if it is in the
* wrong format to avoid exceptions during parsing.
*
* @param readerFactory
* provides a reader to the reports
*
* @return {@code true} if this parser accepts this file as valid input, or {@code false} if the file could not be
* parsed by this parser
*/
public boolean accepts(final ReaderFactory readerFactory) {
return true;
}
/**
* Returns whether the specified file is an XML file. This method just checks if the first 10 lines contain the XML
* tag rather than parsing the whole document.
*
* @param readerFactory
* the file to check
*
* @return {@code true} if the file is an XML file, {@code false} otherwise
*/
protected boolean isXmlFile(final ReaderFactory readerFactory) {
try (Stream<String> lines = readerFactory.readStream()) {
return lines.limit(10).anyMatch(line -> line.contains("<?xml"));
}
catch (ParsingException ignored) {
return false;
}
}
} |
package edu.jhu.gm.maxent;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import edu.jhu.gm.feat.FeatureVector;
import edu.jhu.gm.inf.BeliefPropagation.FgInferencerFactory;
import edu.jhu.gm.inf.BruteForceInferencer.BruteForceInferencerPrm;
import edu.jhu.gm.model.FgModel;
import edu.jhu.gm.train.CrfObjective;
import edu.jhu.gm.train.CrfObjective.CrfObjectivePrm;
import edu.jhu.gm.train.CrfObjectiveTest;
import edu.jhu.prim.arrays.DoubleArrays;
import edu.jhu.util.JUnitUtils;
public class LogLinearEDsTest {
// The following 4 tests require support for features of x and y.
@Test
public void testLogLinearModelShapesLogProbs() {
// Test with inference in the log-domain.
boolean logDomain = true;
testLogLinearModelShapesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesProbs() {
// Test with inference in the prob-domain.
boolean logDomain = false;
testLogLinearModelShapesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesTwoExamplesLogProbs() {
boolean logDomain = true;
testLogLinearModelShapesTwoExamplesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesTwoExamplesProbs() {
boolean logDomain = false;
testLogLinearModelShapesTwoExamplesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesOneExampleLogProbs() {
boolean logDomain = true;
testLogLinearModelShapesOneExampleHelper(logDomain);
}
@Test
public void testLogLinearModelShapesOneExampleProbs() {
boolean logDomain = false;
testLogLinearModelShapesOneExampleHelper(logDomain);
}
private void testLogLinearModelShapesHelper(boolean logDomain) {
LogLinearEDs exs = new LogLinearEDs();
exs.addEx(30, "circle", "solid");
exs.addEx(15, "circle");
exs.addEx(10, "solid");
exs.addEx(5);
double[] params = new double[]{3.0, 2.0};
FgModel model = new FgModel(2);
model.updateModelFromDoubles(params);
// Test log-likelihood.
CrfObjective obj = new CrfObjective(new CrfObjectivePrm(), model, exs.getData(), CrfObjectiveTest.getInfFactory(logDomain));
obj.setPoint(params);
// Test average log-likelihood.
double ll = obj.getValue();
System.out.println(ll);
assertEquals(-95.531 / (30.+15.+10.+5.), ll, 1e-3);
// Test observed feature counts.
FeatureVector obsFeats = obj.getObservedFeatureCounts(params);
assertEquals(45, obsFeats.get(0), 1e-13);
assertEquals(40, obsFeats.get(1), 1e-13);
// Test expected feature counts.
FeatureVector expFeats = obj.getExpectedFeatureCounts(params);
assertEquals(57.15444760934599, expFeats.get(0), 1e-3);
assertEquals(52.84782467867294, expFeats.get(1), 1e-3);
// Test gradient.
double[] gradient = new double[params.length];
obj.getGradient(gradient);
double[] expectedGradient = new double[]{-12.154447609345993, -12.847824678672943};
DoubleArrays.scale(expectedGradient, 1.0 / (30.+15.+10.+5.));
JUnitUtils.assertArrayEquals(expectedGradient, gradient, 1e-3);
}
private void testLogLinearModelShapesTwoExamplesHelper(boolean logDomain) {
LogLinearEDs exs = new LogLinearEDs();
exs.addEx(1, "circle");
exs.addEx(1, "solid");
double[] params = new double[]{3.0, 2.0};
FgModel model = new FgModel(2);
model.updateModelFromDoubles(params);
FgInferencerFactory infFactory = new BruteForceInferencerPrm(logDomain);
infFactory = CrfObjectiveTest.getInfFactory(logDomain);
CrfObjective obj = new CrfObjective(new CrfObjectivePrm(), model, exs.getData(), infFactory);
obj.setPoint(params);
assertEquals(2, exs.getAlphabet().size());
// Test average log-likelihood.
double ll = obj.getValue();
System.out.println(ll + " " + Math.exp(ll));
assertEquals(((3*1 + 2*1) - 2*Math.log((Math.exp(3*1) + Math.exp(2*1)))) / 2.0, ll, 1e-2);
// Test observed feature counts.
FeatureVector obsFeats = obj.getObservedFeatureCounts(params);
assertEquals(1, obsFeats.get(0), 1e-13);
assertEquals(1, obsFeats.get(1), 1e-13);
// Test expected feature counts.
FeatureVector expFeats = obj.getExpectedFeatureCounts(params);
assertEquals(1.4621, expFeats.get(0), 1e-3);
assertEquals(0.5378, expFeats.get(1), 1e-3);
// Test gradient.
double[] gradient = new double[params.length];
obj.getGradient(gradient);
double[] expectedGradient = new double[]{1.0 - 1.4621, 1.0 - 0.5378};
DoubleArrays.scale(expectedGradient, 1.0/2.0);
JUnitUtils.assertArrayEquals(expectedGradient, gradient, 1e-3);
}
private void testLogLinearModelShapesOneExampleHelper(boolean logDomain) {
LogLinearEDs exs = new LogLinearEDs();
exs.addEx(1, "circle");
exs.addEx(0, "solid");
double[] params = new double[]{3.0, 2.0};
FgModel model = new FgModel(2);
model.updateModelFromDoubles(params);
FgInferencerFactory infFactory = new BruteForceInferencerPrm(logDomain);
infFactory = CrfObjectiveTest.getInfFactory(logDomain);
CrfObjective obj = new CrfObjective(new CrfObjectivePrm(), model, exs.getData(), infFactory);
obj.setPoint(params);
assertEquals(2, exs.getAlphabet().size());
// Test log-likelihood.
double ll = obj.getValue();
System.out.println(ll);
assertEquals(3*1 - Math.log(Math.exp(3*1) + Math.exp(2*1)), ll, 1e-2);
// Test observed feature counts.
FeatureVector obsFeats = obj.getObservedFeatureCounts(params);
assertEquals(1, obsFeats.get(0), 1e-13);
assertEquals(0, obsFeats.get(1), 1e-13);
// Test expected feature counts.
FeatureVector expFeats = obj.getExpectedFeatureCounts(params);
assertEquals(0.7310, expFeats.get(0), 1e-3);
assertEquals(0.2689, expFeats.get(1), 1e-3);
// Test gradient.
double[] gradient = new double[params.length];
obj.getGradient(gradient);
JUnitUtils.assertArrayEquals(new double[]{0.2689, -0.2689}, gradient, 1e-3);
}
} |
package edu.mines.jtk.dsp;
import edu.mines.jtk.opt.BrentMinFinder;
import static edu.mines.jtk.util.ArrayMath.*;
import edu.mines.jtk.util.Check;
/**
* A sinc interpolator for bandlimited uniformly-sampled functions y(x).
* Interpolators can be designed for any two of three parameters: maximum
* error (emax), maximum frequency (fmax) and maximum length (lmax). The
* parameter not specified is computed when an interpolator is designed.
* <p>
* Below the specified (or computed) maximum frequency fmax, the maximum
* interpolation error should be less than the specified (or computed)
* maximum error emax. For frequencies above fmax, interpolation error
* may be much greater. Therefore, sequences to be interpolated should
* be bandlimited to frequencies less than fmax.
* <p>
* The maximum length lmax of an interpolator is an even positive integer.
* It is the number of uniform samples required to interpolate a single
* value y(x). Ideally, the weights applied to each uniform sample are
* values of a sinc function. Although the ideal sinc function yields zero
* interpolation error for all frequencies up to the Nyquist frequency
* (0.5 cycles/sample), it has infinite length.
* <p>
* With recursive filtering, infinite-length approximations to the sinc
* function are feasible and, in some applications, most efficient. When
* the number of interpolated values is large relative to the number of
* uniform samples, the cost of recursive filtering is amortized over those
* many interpolated values, and can be negligible. However, this cost
* becomes significant when only a few values are interpolated for each
* sequence of uniform samples.
* <p>
* This interpolator is based on a <em>finite-length</em> approximation
* to the sinc function. The efficiency of finite-length interpolators
* like this one does not depend on the number of samples interpolated.
* Also, this interpolator is robust in the presence of noise spikes,
* which affect only nearby samples.
* <p>
* Finite-length interpolators present a tradeoff between cost and accuracy.
* Interpolators with small maximum lengths are most efficient, and those
* with high maximum frequencies and small maximum errors are most accurate.
* <p>
* When interpolating multiple uniformly sampled functions y(x) that share
* a common sampling of x, some redundant computations can be eliminated by
* specifying the sampling only once before interpolating multiple times.
* The resulting performance increase may be especially significant when
* only a few (perhaps only one) values are interpolated for each sequence
* of uniform samples.
* <p>
* For efficiency, interpolation coefficients (sinc approximations) are
* tabulated when an interpolator is constructed. The cost of building
* the table can easily exceed that of interpolating one sequence of
* samples, depending on the number of uniform samples. Therefore, one
* typically constructs an interpolator and uses it more than once.
* @author Dave Hale, Colorado School of Mines; Bill Harlan, Landmark Graphics
* @version 2005.08.07
*/
public class SincInterpolator {
/**
* The method used to extrapolate samples when interpolating.
* Sampled functions are defined implicitly by extrapolation outside the
* domain for which samples are specified explicitly, with either zero or
* constant values. If constant, the extrapolated values are the first and
* last uniform sample values. The default is extrapolation with zeros.
*/
public enum Extrapolation {
ZERO,
CONSTANT,
}
/**
* Returns a sinc interpolator with specified maximum error and length.
* Computes the maximum frequency fmax. Note that for some parameters
* emax and lmax, the maximum freuency fmax may be zero. In this case,
* the returned interpolator is useless.
* @param emax the maximum error for frequencies less than fmax; e.g.,
* 0.01 for 1% percent error. 0.0 < emax <= 0.1 is required.
* @param lmax the maximum interpolator length, in samples.
* Must be an even integer not less than 8.
* @return the sinc interpolator.
*/
public static SincInterpolator fromErrorAndLength(
double emax, int lmax)
{
return new SincInterpolator(emax,0.0,lmax);
}
/**
* Returns a sinc interpolator with specified maximum error and frequency.
* Computes the maximum length lmax.
* @param emax the maximum error for frequencies less than fmax; e.g.,
* 0.01 for 1% percent error. Must be greater than 0.0 and less than 1.0.
* @param fmax the maximum frequency, in cycles per sample.
* Must be greater than 0.0 and less than 0.5.
* @return the sinc interpolator.
*/
public static SincInterpolator fromErrorAndFrequency(
double emax, double fmax)
{
return new SincInterpolator(emax,fmax,0);
}
/**
* Returns a sinc interpolator with specified maximum frequency and length.
* Computes the maximum error emax.
* <p>
* The product (1-2*fmax)*lmax must be greater than one. For when this
* product is less than one, a useful upper bound on interpolation error
* cannot be computed.
* @param fmax the maximum frequency, in cycles per sample.
* Must be greater than 0.0 and less than 0.5*(1.0-1.0/lmax).
* @param lmax the maximum interpolator length, in samples.
* Must be an even integer not less than 8 and greater than
* 1.0/(1.0-2.0*fmax).
* @return the sinc interpolator.
*/
public static SincInterpolator fromFrequencyAndLength(
double fmax, int lmax)
{
return new SincInterpolator(0.0,fmax,lmax);
}
/**
* Returns a sinc interpolator using Ken Larner's least-squares method.
* This interpolator is based on a Technical Memorandum written in 1980
* by Ken Larner while at Western Geophysical. It is included here only
* for historical and testing purposes. It is less flexible and yields
* more interpolation error than other interpolators constructed by this
* class.
* @param lmax the maximum interpolator length, in samples.
* Must be an even integer between 8 and 16, inclusive.
* @return the sinc interpolator.
*/
public static SincInterpolator fromKenLarner(int lmax) {
return new SincInterpolator(lmax);
}
private SincInterpolator(int lmax) {
Check.argument(lmax%2==0,"lmax is even");
Check.argument(lmax>=8,"lmax>=8");
Check.argument(lmax<=16,"lmax<=16");
_emax = 0.01;
_fmax = 0.033+0.132*log(lmax); // Ken's empirical relationship
_lmax = lmax;
_nsinc = 2049;
_dsinc = 1.0/(_nsinc-1);
_lsinc = lmax;
makeTableKenLarner();
}
/**
* Constructs a default sinc interpolator. The default design parameters
* are fmax = 0.3 cycles/sample (60% of Nyquist) and lmax = 8 samples.
* For these parameters, the computed maximum error is less than 0.007
* (0.7%). In testing, observed maximum error is less than 0.005 (0.5%).
*/
public SincInterpolator() {
this(0.0,0.3,8);
}
/**
* Gets the maximum error for this interpolator.
* @return the maximum error.
*/
public double getMaximumError() {
return _emax;
}
/**
* Gets the maximum frequency for this interpolator.
* @return the maximum frequency.
*/
public double getMaximumFrequency() {
return _fmax;
}
/**
* Gets the maximum length for this interpolator.
* @return the maximum length.
*/
public int getMaximumLength() {
return _lmax;
}
/**
* Gets the number of bytes consumed by the table of interpolators.
* The use of interpolators with small emax and large lmax may require
* the computation of large tables. This method can be used to determine
* how much memory is consumed by the table of an interpolator, before
* that is computed (when the interpolator is used for the first time).
* @return the number of bytes.
*/
public long getTableBytes() {
long nbytes = 4L;
nbytes *= _lsinc;
nbytes *= _nsinc;
return nbytes;
}
/**
* Gets the extrapolation method for this interpolator.
* @return the extrapolation method.
*/
public Extrapolation getExtrapolation() {
return _extrap;
}
/**
* Sets the extrapolation method for this interpolator.
* The default extrapolation method is extrapolation with zeros.
* @param extrap the extrapolation method.
*/
public void setExtrapolation(Extrapolation extrap) {
_extrap = extrap;
}
/**
* Sets the current sampling for a uniformly-sampled function y(x).
* In some applications, this sampling never changes, and this method
* may be called only once for this interpolator.
* @param nxu the number of uniform samples.
* @param dxu the uniform sampling interval.
* @param fxu the value x corresponding to the first uniform sample yu[0].
*/
public void setUniformSampling(int nxu, double dxu, double fxu) {
if (_asinc==null)
makeTable();
_nxu = nxu;
_dxu = dxu;
_fxu = fxu;
_xf = fxu;
_xs = 1.0/dxu;
_xb = _lsinc-_xf*_xs;
_nxum = nxu-_lsinc;
}
/**
* Sets the current samples for a uniformly-sampled function y(x).
* If sample values are complex numbers, real and imaginary parts are
* packed in the array as real, imaginary, real, imaginary, and so on.
* <p>
* Sample values are passed by reference, not by copy. Changes to sample
* values in the specified array will yield changes in interpolated values.
* @param yu array[nxu] of uniform samples of y(x);
* by reference, not by copy.
*/
public void setUniformSamples(float[] yu) {
_yu = yu;
}
/**
* Sets the current sampling and samples for a function y(x).
* This method simply calls the two methods
* {@link #setUniformSampling(int,double,double)} and
* {@link #setUniformSamples(float[])}
* with the specified parameters.
* @param nxu the number of uniform samples.
* @param dxu the uniform sampling interval.
* @param fxu the value x corresponding to the first uniform sample yu[0].
* @param yu array[nxu] of uniform samples of y(x);
* by reference, not by copy.
*/
public void setUniform(int nxu, double dxu, double fxu, float[] yu) {
setUniformSampling(nxu,dxu,fxu);
setUniformSamples(yu);
}
/**
* Interpolates the current uniform samples as real numbers.
* @param x the value x at which to interpolate y(x).
* @return the interpolated y(x).
*/
public float interpolate(double x) {
// Which uniform samples?
double xn = _xb+x*_xs;
int ixn = (int)xn;
int kyu = _ib+ixn;
// Which sinc approximation?
double frac = xn-ixn;
if (frac<0.0)
frac += 1.0;
int ksinc = (int)(frac*_nsincm1+0.5);
float[] asinc = _asinc[ksinc];
// If no extrapolation is necessary, use a fast loop.
// Otherwise, extrapolate uniform samples, as necessary.
float yr = 0.0f;
if (kyu>=0 && kyu<=_nxum) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu)
yr += _yu[kyu]*asinc[isinc];
} else if (_extrap==Extrapolation.ZERO) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu) {
if (0<=kyu && kyu<_nxu)
yr += _yu[kyu]*asinc[isinc];
}
} else if (_extrap==Extrapolation.CONSTANT) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu) {
int jyu = (kyu<0)?0:(_nxu<=kyu)?_nxu-1:kyu;
yr += _yu[jyu]*asinc[isinc];
}
}
return yr;
}
/**
* Interpolates the current uniform samples as real numbers.
* @param nx the number of output samples.
* @param x array[nx] of values x at which to interpolate y(x).
* @param y array[nx] of interpolated output y(x).
*/
public void interpolate(int nx, float[] x, float[] y) {
for (int ix=0; ix<nx; ++ix)
y[ix] = interpolate(x[ix]);
}
/**
* Interpolates the current uniform samples as real numbers.
* <p>
* This method does not perform any anti-alias filtering, which may or
* may not be necessary to avoid aliasing when the specified output
* sampling interval exceeds the current uniform sampling interval.
* @param nx the number of output samples.
* @param dx the output sampling interval.
* @param fx the value x corresponding to the first output sample y[0].
* @param y array[nx] of interpolated output y(x).
*/
public void interpolate(int nx, double dx, double fx, float[] y) {
if (dx==_dxu) {
shift(nx,fx,y);
} else {
for (int ix=0; ix<nx; ++ix)
y[ix] = interpolate(fx+ix*dx);
}
}
/**
* Interpolates the current uniform samples as complex numbers.
* Complex output samples are packed in the specified output array as
* real, imaginary, real, imaginary, and so on.
* @param nx the number of output samples.
* @param x array[nx] of values x at which to interpolate y(x).
* @param y array[2*nx] of interpolated output y(x).
*/
public void interpolateComplex(int nx, float[] x, float[] y) {
for (int ix=0; ix<nx; ++ix)
interpolateComplex(ix,x[ix],y);
}
/**
* Interpolates the current uniform samples as complex numbers.
* Complex output samples are packed in the specified output array as
* real, imaginary, real, imaginary, and so on.
* @param nx the number of output samples.
* @param dx the output sampling interval.
* @param fx the value x corresponding to the first output sample (y[0],y[1]).
* @param y array[2*nx] of interpolated output y(x).
*/
public void interpolateComplex(
int nx, double dx, double fx, float[] y)
{
for (int ix=0; ix<nx; ++ix)
interpolateComplex(ix,fx+ix*dx,y);
}
/**
* Finds a local maximum of the function y(x) near the specified value x.
* The search for the maximum is restricted to an interval centered at the
* specified x and having width equal to the current uniform sampling
* interval.
* <p>
* Typically, the specified x corresponds to an uniform sample for which
* the value y(x) of that sample is not less than the values of the two
* nearest neighboring samples.
* @param x the center of the interval in which y(x) is a maximum.
* @return the value xmax for which y(xmax) is a local maximum.
*/
public double findMax(double x) {
return findMax(x,1.0);
}
/**
* Finds a local minimum or maximum of the function y(x) near the
* specified value x. The type type of extremum is determined by
* the second argument: Any positive value means find the maximum,
* otherwise find the minimum. For simplicity and readibility,
* use 1 for maximum, -1 for minimum. The search for the extremum
* is restricted to an interval centered at the specified x and having
* width equal to the current uniform sampling interval.
* <p>
* Typically, the specified x corresponds to an uniform sample for which
* the value y(x) of that sample is not less than the values of the two
* nearest neighboring samples.
* @param x the center of the interval in which y(x) is an extremum.
* @param type the type of extremum; 1 for maximum, -1 for minimum.
* @return the value xmax for which y(xmax) is a local minimum or maximum.
*/
public double findMax(double x, double type) {
double a = x-0.5*_dxu;
double b = x+0.5*_dxu;
double tol = _dsinc*_dxu;
final double sign = type > 0 ? -1 : 1;
BrentMinFinder finder = new BrentMinFinder(
new BrentMinFinder.Function(){
public double evaluate(double x) {
return sign*interpolate(x);
}
});
return finder.findMin(a,b,tol);
}
/**
* Sets the current sampling for a uniformly-sampled function y(x1,x2).
* In some applications, this sampling never changes, and this method
* may be called only once for this interpolator.
* @param nx1u the number of uniform samples in 1st dimension.
* @param dx1u the uniform sampling interval in 1st dimension.
* @param fx1u the value x1 correponding to the first sample yu[0][0].
* @param nx2u the number of uniform samples in 2nd dimension.
* @param dx2u the uniform sampling interval in 2nd dimension.
* @param fx2u the value x2 correponding to the first sample yu[0][0].
*/
public void setUniformSampling(
int nx1u, double dx1u, double fx1u,
int nx2u, double dx2u, double fx2u) {
if (_asinc==null)
makeTable();
_nx1u = nx1u;
//_dx1u = dx1u;
//_fx1u = fx1u;
_x1f = fx1u;
_x1s = 1.0/dx1u;
_x1b = _lsinc-_x1f*_x1s;
_nx1um = nx1u-_lsinc;
_nx2u = nx2u;
//_dx2u = dx2u;
//_fx2u = fx2u;
_x2f = fx2u;
_x2s = 1.0/dx2u;
_x2b = _lsinc-_x2f*_x2s;
_nx2um = nx2u-_lsinc;
}
/**
* Sets the current samples for a uniformly-sampled function y(x1,x2).
* If sample values are complex numbers, real and imaginary parts are
* packed in the array as real, imaginary, real, imaginary, and so on.
* <p>
* Sample values are passed by reference, not by copy. Changes to sample
* values in the specified array will yield changes in interpolated values.
* @param yu array[nx2u][nx1u] of samples of y(x1,x2);
* by reference, not by copy.
*/
public void setUniformSamples(float[][] yu) {
_yyu = yu;
}
/**
* Sets the current sampling and samples for a function y(x1,x2).
* This method simply calls the two methods
* {@link #setUniformSampling(int,double,double,int,double,double)} and
* {@link #setUniformSamples(float[][])}
* with the specified parameters.
* @param nx1u the number of uniform samples in 1st dimension.
* @param dx1u the uniform sampling interval in 1st dimension.
* @param fx1u the value x1 correponding to the first sample yu[0][0].
* @param nx2u the number of uniform samples in 2nd dimension.
* @param dx2u the uniform sampling interval in 2nd dimension.
* @param fx2u the value x2 correponding to the first sample yu[0][0].
* @param yu array[nx2u][nx1u] of samples of y(x1,x2);
* by reference, not by copy.
*/
public void setUniform(
int nx1u, double dx1u, double fx1u,
int nx2u, double dx2u, double fx2u,
float[][] yu) {
setUniformSampling(nx1u,dx1u,fx1u,nx2u,dx2u,fx2u);
setUniformSamples(yu);
}
/**
* Interpolates the current uniform samples as real numbers.
* @param x1 the value x1 at which to interpolate y(x1,x2).
* @param x2 the value x2 at which to interpolate y(x1,x2).
* @return the interpolated y(x1,x2).
*/
public float interpolate(double x1, double x2) {
// Which uniform samples?
double x1n = _x1b+x1*_x1s;
double x2n = _x2b+x2*_x2s;
int ix1n = (int)x1n;
int ix2n = (int)x2n;
int ky1u = _ib+ix1n;
int ky2u = _ib+ix2n;
// Which sinc approximations?
double frac1 = x1n-ix1n;
double frac2 = x2n-ix2n;
if (frac1<0.0)
frac1 += 1.0;
if (frac2<0.0)
frac2 += 1.0;
int ksinc1 = (int)(frac1*_nsincm1+0.5);
int ksinc2 = (int)(frac2*_nsincm1+0.5);
float[] asinc1 = _asinc[ksinc1];
float[] asinc2 = _asinc[ksinc2];
// If no extrapolation is necessary, use a fast loop.
// Otherwise, extrapolate uniform samples, as necessary.
float yr = 0.0f;
if (ky1u>=0 && ky1u<=_nx1um && ky2u>=0 && ky2u<=_nx2um) {
for (int i2sinc=0; i2sinc<_lsinc; ++i2sinc,++ky2u) {
float asinc22 = asinc2[i2sinc];
float[] yyuk2 = _yyu[ky2u];
float yr2 = 0.0f;
for (int i1sinc=0,my1u=ky1u; i1sinc<_lsinc; ++i1sinc,++my1u)
yr2 += yyuk2[my1u]*asinc1[i1sinc];
yr += asinc22*yr2;
}
} else if (_extrap==Extrapolation.ZERO) {
for (int i2sinc=0; i2sinc<_lsinc; ++i2sinc,++ky2u) {
if (0<=ky2u && ky2u<_nx2u) {
for (int i1sinc=0,my1u=ky1u; i1sinc<_lsinc; ++i1sinc,++my1u) {
if (0<=my1u && my1u<_nx1u)
yr += _yyu[ky2u][my1u]*asinc2[i2sinc]*asinc1[i1sinc];
}
}
}
} else if (_extrap==Extrapolation.CONSTANT) {
for (int i2sinc=0; i2sinc<_lsinc; ++i2sinc,++ky2u) {
int jy2u = (ky2u<0)?0:(_nx2u<=ky2u)?_nx2u-2:ky2u;
for (int i1sinc=0,my1u=ky1u; i1sinc<_lsinc; ++i1sinc,++my1u) {
int jy1u = (my1u<0)?0:(_nx1u<=my1u)?_nx1u-1:my1u;
yr += _yyu[jy2u][jy1u]*asinc2[i2sinc]*asinc1[i1sinc];
}
}
}
return yr;
}
/**
* Sets the current sampling for a uniformly-sampled function y(x1,x2,x3).
* In some applications, this sampling never changes, and this method
* may be called only once for this interpolator.
* @param nx1u the number of uniform samples in 1st dimension.
* @param dx1u the uniform sampling interval in 1st dimension.
* @param fx1u the value x1 correponding to the first sample yu[0][0][0].
* @param nx2u the number of uniform samples in 2nd dimension.
* @param dx2u the uniform sampling interval in 2nd dimension.
* @param fx2u the value x2 correponding to the first sample yu[0][0][0].
* @param nx3u the number of uniform samples in 3rd dimension.
* @param dx3u the uniform sampling interval in 3rd dimension.
* @param fx3u the value x3 correponding to the first sample yu[0][0][0].
*/
public void setUniformSampling(
int nx1u, double dx1u, double fx1u,
int nx2u, double dx2u, double fx2u,
int nx3u, double dx3u, double fx3u)
{
if (_asinc==null)
makeTable();
_nx1u = nx1u;
//_dx1u = dx1u;
//_fx1u = fx1u;
_x1f = fx1u;
_x1s = 1.0/dx1u;
_x1b = _lsinc-_x1f*_x1s;
_nx1um = nx1u-_lsinc;
_nx2u = nx2u;
//_dx2u = dx2u;
//_fx2u = fx2u;
_x2f = fx2u;
_x2s = 1.0/dx2u;
_x2b = _lsinc-_x2f*_x2s;
_nx2um = nx2u-_lsinc;
_nx3u = nx3u;
//_dx3u = dx3u;
//_fx3u = fx3u;
_x3f = fx3u;
_x3s = 1.0/dx3u;
_x3b = _lsinc-_x3f*_x3s;
_nx3um = nx3u-_lsinc;
}
/**
* Sets the current samples for a uniformly-sampled function y(x1,x2,x3).
* If sample values are complex numbers, real and imaginary parts are
* packed in the array as real, imaginary, real, imaginary, and so on.
* <p>
* Sample values are passed by reference, not by copy. Changes to sample
* values in the specified array will yield changes in interpolated values.
* @param yu array[nx3u][nx2u][nx1u] of samples of y(x1,x2,x3);
* by reference, not by copy.
*/
public void setUniformSamples(float[][][] yu) {
_yyyu = yu;
}
/**
* Sets the current sampling and samples for a function y(x1,x2,x3).
* This method simply calls the two methods
* {@link #setUniformSampling(
* int,double,double,int,double,double,int,double,double)} and
* {@link #setUniformSamples(float[][][])}
* with the specified parameters.
* @param nx1u the number of uniform samples in 1st dimension.
* @param dx1u the uniform sampling interval in 1st dimension.
* @param fx1u the value x1 correponding to the first sample yu[0][0][0].
* @param nx2u the number of uniform samples in 2nd dimension.
* @param dx2u the uniform sampling interval in 2nd dimension.
* @param fx2u the value x2 correponding to the first sample yu[0][0][0].
* @param nx3u the number of uniform samples in 3rd dimension.
* @param dx3u the uniform sampling interval in 3rd dimension.
* @param fx3u the value x3 correponding to the first sample yu[0][0][0].
* @param yu array[nx3u][nx2u][nx1u] of samples of y(x1,x2,x3);
* by reference, not by copy.
*/
public void setUniform(
int nx1u, double dx1u, double fx1u,
int nx2u, double dx2u, double fx2u,
int nx3u, double dx3u, double fx3u,
float[][][] yu)
{
setUniformSampling(nx1u,dx1u,fx1u,nx2u,dx2u,fx2u,nx3u,dx3u,fx3u);
setUniformSamples(yu);
}
/**
* Interpolates the current uniform samples as real numbers.
* @param x1 the value x1 at which to interpolate y(x1,x2,x3).
* @param x2 the value x2 at which to interpolate y(x1,x2,x3).
* @param x3 the value x3 at which to interpolate y(x1,x2,x3).
* @return the interpolated y(x1,x2,x3).
*/
public float interpolate(double x1, double x2, double x3) {
// Which uniform samples?
double x1n = _x1b+x1*_x1s;
double x2n = _x2b+x2*_x2s;
double x3n = _x3b+x3*_x3s;
int ix1n = (int)x1n;
int ix2n = (int)x2n;
int ix3n = (int)x3n;
int ky1u = _ib+ix1n;
int ky2u = _ib+ix2n;
int ky3u = _ib+ix3n;
// Which sinc approximations?
double frac1 = x1n-ix1n;
double frac2 = x2n-ix2n;
double frac3 = x3n-ix3n;
if (frac1<0.0)
frac1 += 1.0;
if (frac2<0.0)
frac2 += 1.0;
if (frac3<0.0)
frac3 += 1.0;
int ksinc1 = (int)(frac1*_nsincm1+0.5);
int ksinc2 = (int)(frac2*_nsincm1+0.5);
int ksinc3 = (int)(frac3*_nsincm1+0.5);
float[] asinc1 = _asinc[ksinc1];
float[] asinc2 = _asinc[ksinc2];
float[] asinc3 = _asinc[ksinc3];
// If no extrapolation is necessary, use a fast loop.
// Otherwise, extrapolate uniform samples, as necessary.
float yr = 0.0f;
if (ky1u>=0 && ky1u<=_nx1um &&
ky2u>=0 && ky2u<=_nx2um &&
ky3u>=0 && ky3u<=_nx3um) {
for (int i3sinc=0; i3sinc<_lsinc; ++i3sinc,++ky3u) {
float asinc33 = asinc3[i3sinc];
float[][] yyy3 = _yyyu[ky3u];
float yr2 = 0.0f;
for (int i2sinc=0,my2u=ky2u; i2sinc<_lsinc; ++i2sinc,++my2u) {
float asinc22 = asinc2[i2sinc];
float[] yyy32 = yyy3[my2u];
float yr1 = 0.0f;
for (int i1sinc=0,my1u=ky1u; i1sinc<_lsinc; ++i1sinc,++my1u)
yr1 += yyy32[my1u]*asinc1[i1sinc];
yr2 += asinc22*yr1;
}
yr += asinc33*yr2;
}
} else if (_extrap==Extrapolation.ZERO) {
for (int i3sinc=0; i3sinc<_lsinc; ++i3sinc,++ky3u) {
if (0<=ky3u && ky3u<_nx3u) {
for (int i2sinc=0,my2u=ky2u; i2sinc<_lsinc; ++i2sinc,++my2u) {
if (0<=my2u && my2u<_nx2u) {
for (int i1sinc=0,my1u=ky1u; i1sinc<_lsinc; ++i1sinc,++my1u) {
if (0<=my1u && my1u<_nx1u)
yr += _yyyu[ky3u][my2u][my1u] *
asinc3[i3sinc] *
asinc2[i2sinc] *
asinc1[i1sinc];
}
}
}
}
}
} else if (_extrap==Extrapolation.CONSTANT) {
for (int i3sinc=0; i3sinc<_lsinc; ++i3sinc,++ky3u) {
int jy3u = (ky3u<0)?0:(_nx3u<=ky3u)?_nx3u-2:ky3u;
for (int i2sinc=0,my2u=ky2u; i2sinc<_lsinc; ++i2sinc,++my2u) {
int jy2u = (my2u<0)?0:(_nx2u<=my2u)?_nx2u-2:my2u;
for (int i1sinc=0,my1u=ky1u; i1sinc<_lsinc; ++i1sinc,++my1u) {
int jy1u = (my1u<0)?0:(_nx1u<=my1u)?_nx1u-1:my1u;
yr += _yyyu[jy3u][jy2u][jy1u] *
asinc3[i3sinc] *
asinc2[i2sinc] *
asinc1[i1sinc];
}
}
}
}
return yr;
}
/**
* Accumulates a specified real value y(x) into the current samples.
* Accumulation is like the transpose (not the inverse) of interpolation.
* This method modifies the current uniform sample values yu.
* @param x the value x at which to accumulate y(x).
* @param y the value y(x) to accumulate.
*/
public void accumulate(double x, float y) {
// Which uniform samples?
double xn = _xb+x*_xs;
int ixn = (int)xn;
int kyu = _ib+ixn;
// Which sinc approximation?
double frac = xn-ixn;
if (frac<0.0)
frac += 1.0;
int ksinc = (int)(frac*_nsincm1+0.5);
float[] asinc = _asinc[ksinc];
// If no extrapolation is necessary, use a fast loop.
// Otherwise, extrapolate uniform samples, as necessary.
if (kyu>=0 && kyu<=_nxum) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu)
_yu[kyu] += y*asinc[isinc];
} else if (_extrap==Extrapolation.ZERO) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu) {
if (0<=kyu && kyu<_nxu)
_yu[kyu] += y*asinc[isinc];
}
} else if (_extrap==Extrapolation.CONSTANT) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu) {
int jyu = (kyu<0)?0:(_nxu<=kyu)?_nxu-1:kyu;
_yu[jyu] += y*asinc[isinc];
}
}
}
/**
* Accumulates an array of real values y(x) into the current samples.
* Accumulation is like the transpose (not the inverse) of interpolation.
* This method modifies the current uniform sample values yu.
* @param nx the number of values to accumulate.
* @param x array[nx] of values x at which to accumulate y(x).
* @param y array[nx] of values y(x) to accumulate.
*/
public void accumulate(int nx, float[] x, float[] y) {
for (int ix=0; ix<nx; ++ix)
accumulate(x[ix],y[ix]);
}
// private
// Fraction of error due to windowing; remainder is due to table lookup.
private static final double EWIN_FRAC = 0.9;
// Maximum table size, when maximum error and frequency are specified.
private static final int NTAB_MAX = 16385;
// Design parameters.
private double _emax;
private double _fmax;
private int _lmax;
// Kaiser window used in design.
private KaiserWindow _kwin;
// Extrapolation method.
private Extrapolation _extrap = Extrapolation.ZERO;
// Current uniform sampling.
private int _nxu;
private double _dxu;
private double _fxu;
private double _xf;
private double _xs;
private double _xb;
private int _nxum;
// Current uniform samples.
private float[] _yu; // real or complex samples
// Current 2-D or 3-D uniform sampling.
private int _nx1u,_nx2u,_nx3u;
//private double _dx1u,_dx2u,_dx3u;
//private double _fx1u,_fx2u,_fx3u;
private double _x1f,_x2f,_x3f;
private double _x1s,_x2s,_x3s;
private double _x1b,_x2b,_x3b;
private int _nx1um,_nx2um,_nx3um;
// Current 2-D or 3-D uniform samples.
private float[][] _yyu;
private float[][][] _yyyu;
// Table of sinc interpolation coefficients.
private int _lsinc; // length of sinc approximations
private int _nsinc; // number of sinc approximations
private double _dsinc; // sampling interval in table
private float[][] _asinc; // array[nsinc][lsinc] of sinc approximations
private double _nsincm1; // nsinc-1
private int _ib; // -lsinc-lsinc/2+1
/**
* Constructs a sinc interpolator with specified parameters.
* Exactly one of the parameters must be zero, and is computed here.
*/
private SincInterpolator(double emax, double fmax, int lmax) {
Check.argument(emax==0.0 && fmax!=0.0 && lmax!=0 ||
emax!=0.0 && fmax==0.0 && lmax!=0 ||
emax!=0.0 && fmax!=0.0 && lmax==0,
"exactly one of emax, fmax, and lmax is zero");
if (emax==0.0) {
Check.argument(fmax<0.5,"fmax<0.5");
Check.argument(lmax>=8,"lmax>=8");
Check.argument(lmax%2==0,"lmax is even");
Check.argument((1.0-2.0*fmax)*lmax>1.0,"(1.0-2.0*fmax)*lmax>1.0");
} else if (fmax==0.0) {
Check.argument(emax<=0.1,"emax<=0.1");
Check.argument(lmax>=8,"lmax>=8");
Check.argument(lmax%2==0,"lmax is even");
} else if (lmax==0) {
Check.argument(emax<=0.1,"emax<=0.1");
Check.argument(fmax<0.5,"fmax<0.5");
}
// The Kaiser window transition width is twice the difference
// between the Nyquist frequency 0.5 and the maximum frequency.
double wwin = 2.0*(0.5-fmax);
// The Kaiser window accounts for a hard-wired fraction of the maximum
// interpolation error. The other error will be due to table lookup.
double ewin = emax*EWIN_FRAC;
KaiserWindow kwin;
// If maximum frequency and length are specified, compute the error
// due to windowing. That windowing error is three times the error
// reported by the Kaiser window, because the conventional Kaiser
// window stopband error is aliased multiple times with the passband
// error. (A factor of at least two is necessary to handle the first
// aliasing, but experiments showed this factor to be inadequate. The
// factor three was found in testing to be sufficient for a wide range
// of design parameters.) Also, apply a lower bound to the error, so
// that the table of sinc approximations does not become too large.
if (emax==0.0) {
kwin = KaiserWindow.fromWidthAndLength(wwin,lmax);
ewin = 3.0*kwin.getError();
emax = ewin/EWIN_FRAC;
double etabMin = 1.1*PI*fmax/(NTAB_MAX-1);
double emaxMin = etabMin/(1.0-EWIN_FRAC);
if (emax<emaxMin) {
emax = emaxMin;
ewin = emax*EWIN_FRAC;
}
}
// Else if maximum error and length are specified, compute the
// maximum frequency. That maximum frequency is the difference
// between the Nyquist frequency 0.5 and half the transition width
// reported by the Kaiser window. However, the maximum frequency
// cannot be less than zero. It will be zero when the specified
// maximum error and/or length are too small for a practical
// interpolator.
else if (fmax==0.0) {
kwin = KaiserWindow.fromErrorAndLength(ewin/3.0,lmax);
fmax = max(0.0,0.5-0.5*kwin.getWidth());
}
// Else if maximum error and width are specified, first compute a
// lower bound on the maximum length, and then round that up to the
// nearest even integer not less than 8. Finally, reconstruct a Kaiser
// window with that maximum length, ignoring the maximum frequency,
// which may be exceeded.
else {
kwin = KaiserWindow.fromErrorAndWidth(ewin/3.0,wwin);
double lwin = kwin.getLength();
lmax = (int)(lwin);
while (lmax<lwin || lmax<8 || lmax%2==1)
++lmax;
kwin = KaiserWindow.fromErrorAndLength(ewin/3.0,lmax);
}
// The number of interpolators in the table depends on the error
// in table lookup - more interpolators corresponds to less error.
// The error in table lookup is whatever is left of the maximum
// error, after accounting for the error due to windowing the sinc.
// The number of interpolators is a power of two plus 1, so that table
// lookup error is zero when interpolating halfway between samples.
double etab = emax-ewin;
_dsinc = (fmax>0.0)?etab/(PI*fmax):1.0;
int nsincMin = 1+(int)ceil(1.0/_dsinc);
_nsinc = 2;
while (_nsinc<nsincMin)
_nsinc *= 2;
++_nsinc;
_dsinc = 1.0/(_nsinc-1);
_lsinc = lmax;
// Save design parameters and Kaiser window, so we can build the table.
_emax = emax;
_fmax = fmax;
_lmax = lmax;
_kwin = kwin;
}
/**
* Builds the table of interpolators. This may be costly, so we do it
* only when an interpolator is used, not when it is constructed. Users`
* may construct more than one interpolator, perhaps in a search for
* optimal design parameters, without actually using all of them.
*/
private void makeTable() {
_asinc = new float[_nsinc][_lsinc];
_nsincm1 = _nsinc-1;
_ib = -_lsinc-_lsinc/2+1;
// The first and last interpolators are shifted unit impulses.
// Handle these two cases exactly, with no rounding errors.
for (int j=0; j<_lsinc; ++j) {
_asinc[ 0][j] = 0.0f;
_asinc[_nsinc-1][j] = 0.0f;
}
_asinc[ 0][_lsinc/2-1] = 1.0f;
_asinc[_nsinc-1][_lsinc/2 ] = 1.0f;
// Other interpolators are sampled Kaiser-windowed sinc functions.
for (int isinc=1; isinc<_nsinc-1; ++isinc) {
double x = -_lsinc/2+1-_dsinc*isinc;
for (int i=0; i<_lsinc; ++i,x+=1.0) {
_asinc[isinc][i] = (float)(sinc(x)*_kwin.evaluate(x));
}
}
}
/**
* Get a copy of the interpolation table. Returns a copy of this
* interpolator's table of sinc interpolation coefficients.
* @return A copy of the table.
*/
public float[][] getTable() {
if (_asinc==null)
makeTable();
assert _asinc != null;
return copy(_asinc);
}
private static double sinc(double x) {
return (x!=0.0)?sin(PI*x)/(PI*x):1.0;
}
private void interpolateComplex(int ix, double x, float[] y) {
// Which uniform samples?
double xn = _xb+x*_xs;
int ixn = (int)xn;
int kyu = _ib+ixn;
// Which sinc approximation?
double frac = xn-ixn;
if (frac<0.0)
frac += 1.0;
int ksinc = (int)(frac*_nsincm1+0.5);
float[] asinc = _asinc[ksinc];
// If no extrapolation is necessary, use a fast loop.
// Otherwise, extrapolate uniform samples, as necessary.
float yr = 0.0f;
float yi = 0.0f;
if (kyu>=0 && kyu<=_nxum) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu) {
int jyu = 2*kyu;
float asinci = asinc[isinc];
yr += _yu[jyu ]*asinci;
yi += _yu[jyu+1]*asinci;
}
} else if (_extrap==Extrapolation.ZERO) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu) {
if (0<=kyu && kyu<_nxu) {
int jyu = 2*kyu;
float asinci = asinc[isinc];
yr += _yu[jyu ]*asinci;
yi += _yu[jyu+1]*asinci;
}
}
} else if (_extrap==Extrapolation.CONSTANT) {
for (int isinc=0; isinc<_lsinc; ++isinc,++kyu) {
int jyu = (kyu<0)?0:(_nxu<=kyu)?2*_nxu-2:2*kyu;
float asinci = asinc[isinc];
yr += _yu[jyu ]*asinci;
yi += _yu[jyu+1]*asinci;
}
}
int jx = 2*ix;
y[jx ] = yr;
y[jx+1] = yi;
}
private void shift(int nx, double fx, float[] y) {
// Uniform sampling.
int nxu = _nxu;
double dxu = _dxu;
double fxu = _fxu;
double lxu = fxu+(nxu-1)*dxu;
// Which output samples are near beginning and end of uniform sequence?
double dx = dxu;
double x1 = fxu+dxu*_lsinc/2;
double x2 = lxu-dxu*_lsinc/2;
double x1n = (x1-fx)/dx;
double x2n = (x2-fx)/dx;
int ix1 = max(0,min(nx,(int)x1n)+1);
int ix2 = max(0,min(nx,(int)x2n)-1);
// Interpolate output samples near beginning of uniform sequence.
for (int ix=0; ix<ix1; ++ix) {
double x = fx+ix*dx;
y[ix] = interpolate(x);
}
// Interpolate output samples near end of uniform sequence.
for (int ix=ix2; ix<nx; ++ix) {
double x = fx+ix*dx;
y[ix] = interpolate(x);
}
// Now we ignore the ends, and use a single sinc approximation.
// Which uniform samples?
double xn = _xb+(fx+ix1*dx)*_xs;
int ixn = (int)xn;
int kyu = _ib+ixn;
// Which sinc approximation?
double frac = xn-ixn;
if (frac<0.0)
frac += 1.0;
int ksinc = (int)(frac*_nsincm1+0.5);
float[] asinc = _asinc[ksinc];
// Interpolate for output indices ix1 <= ix <= ix2.
for (int ix=ix1; ix<ix2; ++ix,++kyu) {
float yr = 0.0f;
for (int isinc=0,jyu=kyu; isinc<_lsinc; ++isinc,++jyu)
yr += _yu[jyu]*asinc[isinc];
y[ix] = yr;
}
}
/**
* Builds the table of interpolators using Ken Larner's old method.
* This method exists for comparison with the Kaiser window method.
* Ken's method is the one that has been in SU and ProMAX for years.
*/
private void makeTableKenLarner() {
_asinc = new float[_nsinc][_lsinc];
_nsincm1 = _nsinc-1;
_ib = -_lsinc-_lsinc/2+1;
// The first and last interpolators are shifted unit impulses.
// Handle these two cases exactly, with no rounding errors.
for (int j=0; j<_lsinc; ++j) {
_asinc[ 0][j] = 0.0f;
_asinc[_nsinc-1][j] = 0.0f;
}
_asinc[ 0][_lsinc/2-1] = 1.0f;
_asinc[_nsinc-1][_lsinc/2 ] = 1.0f;
// Other interpolators are least-squares approximations to sincs.
for (int isinc=1; isinc<_nsinc-1; ++isinc) {
double frac = (double)isinc/(double)(_nsinc-1);
mksinc(frac,_lsinc,_asinc[isinc]);
}
}
private static void mksinc(double d, int lsinc, float[] sinc) {
double[] s = new double[lsinc];
double[] a = new double[lsinc];
double[] c = new double[lsinc];
double[] w = new double[lsinc];
double fmax = 0.033+0.132*log(lsinc);
if (fmax>0.5)
fmax = 0.5;
for (int j=0; j<lsinc; ++j) {
a[j] = sinc(2.0*fmax*j);
c[j] = sinc(2.0*fmax*(lsinc/2-j-1+d));
}
stoepd(lsinc,a,c,s,w);
for (int j=0; j<lsinc; ++j)
sinc[j] = (float)s[j];
}
private static void stoepd (
int n, double[] r, double[] g, double[] f, double[] a)
{
if (r[0]==0.0)
return;
a[0] = 1.0;
double v = r[0];
f[0] = g[0]/r[0];
for (int j=1; j<n; j++) {
a[j] = 0.0;
f[j] = 0.0;
double e = 0.0;
for (int i=0; i<j; i++)
e += a[i]*r[j-i];
double c = e/v;
v -= c*e;
for (int i=0; i<=j/2; i++) {
double bot = a[j-i]-c*a[i];
a[i] -= c*a[j-i];
a[j-i] = bot;
}
double w = 0.0;
for (int i=0; i<j; i++)
w += f[i]*r[j-i];
c = (w-g[j])/v;
for (int i=0; i<=j; i++)
f[i] -= c*a[j-i];
}
}
} |
package frc.team4215.stronghold;
import edu.wpi.first.wpilibj.Timer;
/**
* The class for Autonomous.
*
* @author James
*/
public class Autonomous {
private static Thread threadPing;
/**
* Measured in inches.
*/
private static double distanceTraveled;
public static Timer time = new Timer();
private static double accelerometerKp;
private static double accelerometerKi;
// private static double lastTime;
private static double input;
private static double setpoint;
private static double errSum;
private static double lastTime;
/**
* Length of Autonomous period, seconds
*/
private static final double AUTOTIME = 15;
/**
* Sample rate, times/second.
*/
private static final double SAMPLINGRATE = 20;
// private Victor armMotor, intake;
private DriveTrain dT;
private Arm arm;
private Intake intake;
private Winch winch;
private Interface choiceAuto;
public Autonomous(DriveTrain dT_) throws RobotException {
dT = dT_;
arm = new Arm();
intake = new Intake();
winch = new Winch();
}
/*
* Actually, I highly doubt if this would work or not. If this
* won't work I know how to fix it. - James
*/
public void chooseAuto(int num) {
if (num == 1) choiceAuto = () -> autoLowBar();
else if (num == 2) choiceAuto = () -> autoSpyBotLowGoal();
else if (num == 3) choiceAuto = () -> autoChevalDeFrise();
// else if (num == 4) choiceAuto = () -> autoPortcullis();
else choiceAuto = null;
}
public void autoChoice() throws RobotException {
if (null != choiceAuto)
throw new RobotException("There is not a method chosen.");
choiceAuto.runAuto();
}
/* working variables */
/*
* private static double lastTime; private static double
* Input,Output; private static double Setpoint; private static
* double errSum,lastErr;
*/
// private double kp, ki, kd;
/*
* Example PID controller
* @author Jack Rausch
*/
/*
* public double errorCompute() { // How long since we last
* calculated double now = time.get(); double timeChange = now -
* lastTime; // Compute all the working error variables double
* error = Setpoint - Input; errSum += (error * timeChange);
* double dErr = (error - lastErr) / timeChange; // Compute PID
* Output Output = kp * error + ki * errSum + kd * dErr; //
* Remember some variables for next time lastErr = error; lastTime
* = now; return Output; } void SetTunings(double Kp, double Ki,
* double Kd) { kp = Kp; ki = Ki; kd = Kd; } // DO NOT DELETE THIS
* CODE EVER!!!!!
*/
/**
* PID controller implementation for accelerometer Waweru and I
* have decided that the derivative part for the controller is
* unnecessary. Derivative function taken out. I moved this code
* directly into the I2CDistanceTraveled section.
*
* @author Joey
*/
public static double accelerometerPID() {
// Time since last calculation
double now = time.get();
double timeChange = now - lastTime;
// Calculate error variables
double error = setpoint - input;
errSum += error * timeChange;
// Sum errors
double accelerometerError =
accelerometerKp * error + accelerometerKi * errSum;
// Reset time variable
lastTime = now;
return accelerometerError;
}
/**
* PID controller implementation for gyroscope
*
* @param gyroKp
* @param gyroKi
* @author Joey
*/
public double gyroPID(double gyroKp, double gyroKi) {
// Time since last calculation
double now = time.get();
double timeChange = now - lastTime;
// Calculate error variables
double error = setpoint - input;
errSum += error * timeChange;
// Sum errors
double gyroOutput = gyroKp * error + gyroKi * errSum;
// Reset time variable
lastTime = now;
return gyroOutput;
}
/**
* Method called to set the Setpoint so the PID controller has the
* capability to calculate errors and correct them.
*
* @param defSetpoint
* double value
* @author Jack Rausch
*/
public static void setSetpoint(double defSetpoint) {
setpoint = defSetpoint;
}
/**
* Timer method integrating the Timer class from wpilibj. USE THIS
* TIMER UNIVERSALLY!!!!!
*
* @author Jack Rausch
*/
public static void startTimer() {
time.start();
}
/**
* All constants.
*
* @author James
*/
private static final class Constant {
/**
* Constant shared.
*
* @author James
*/
public static final class Shared {
public static final double armMoveMaxTime = 2d;
public static final double armDown = -1d, armStop = 0d;
public static final double intakeDelay = 1d;
}
/**
* Constant for autoLowBar.
*
* @author James
*/
private static final class LowBar {
public static final double driveThroughDistance = 500d;
}
/**
* Constant for autoSpyBotLowGoal.
*
* @author James
*/
private static final class SpyBotLowGoal {
public static final double driveToDistance = 500d;
}
/**
* Constant for autoChevalDeFrise.
*
* @author James
*/
private static final class ChevalDeFrise {
public static final double driveToDistance = 500d;
public static final double driveThroughDistance = 500d;
}
/**
* Constant for autoPortcullis.
*
* @author James
*/
@SuppressWarnings("unused")
@Deprecated
public static final class Portcullis {
// public static final double driveToDistance = 500d;
// public static final double driveThroughDistance = 500d;
}
}
/**
* The interface for programs outside to run the chosen autonomous
* function.
*
* @author James
*/
public interface Interface {
public void runAuto();
}
/**
* to lower arm. Need more info.
*
* @author James
*/
private void armLowerBottom() {
arm.set(Constant.Shared.armDown);
Timer.delay(Constant.Shared.armMoveMaxTime);
arm.set(Constant.Shared.armStop);
}
/**
* to lift arm. Need more info
*
* @author James
*/
@SuppressWarnings("unused")
@Deprecated
private void armLifterTop() {
return;
// arm.set(Constant.Shared.armUp);
// Timer.delay(Constant.Shared.armMoveMaxTime);
// arm.set(Constant.Shared.armStop);
}
/**
* To drive straight.
*
* @author James
* @param moveDistance
* Meters of required distance.
*/
private void driveStraight(double moveDistance) {
while (distanceTraveled < moveDistance) {
dT.drive(Const.Motor.Run.Forward);
I2CDistanceTraveled();
}
dT.drive(Const.Motor.Run.Stop);
}
/**
* throw ball out. Yet tested.
*
* @author James
*/
private void throwBall() {
intake.set(Const.Motor.Run.Forward);
Timer.delay(Constant.Shared.intakeDelay);
intake.set(Const.Motor.Run.Stop);
}
private void winchInit() {
winch.set(Const.Motor.Run.WinchPartialSpeed);
Timer.delay(Const.Motor.Run.WinchPartialTime);
winch.set(Const.Motor.Run.Stop);
}
/**
* Autonomous function No.1
*
* @author James
*/
public void autoLowBar() {
winchInit();
armLowerBottom();
driveStraight(Constant.LowBar.driveThroughDistance);
}
/**
* Autonomous function No.2
*
* @author James
*/
public void autoSpyBotLowGoal() {
winchInit();
armLowerBottom();
driveStraight(Constant.SpyBotLowGoal.driveToDistance);
throwBall();
}
/**
* Autonomous function No.3
*
* @author James
*/
public void autoChevalDeFrise() {
winchInit();
driveStraight(Constant.ChevalDeFrise.driveToDistance);
armLowerBottom();
driveStraight(Constant.ChevalDeFrise.driveThroughDistance);
}
/**
* Autonomous function No.4, not used.
*
* @author James
*/
@Deprecated
public void autoPortcullis() {
throw null;
// armLowerBottom();
// driveStraight(Constant.Portcullis.driveToDistance);
// armLifterTop();
// driveStraight(Constant.Portcullis.driveThroughDistance);
}
/**
* Should be equivalent to a method called getAccel of another
* class I2CAccelerometer which isn't here yet.
*
* @author James
* @return Accelerations, double[] with length of 3
*/
private static double[] I2CAccel_getAccel() {
return I2CAccel.getAccel();
}
/**
* Calculates distance traveled based on information from the
* accelerometer. The distanceTraveled is measured in inches.
*
* @author Joey
*/
private static void I2CDistanceTraveled() {
double time1 = time.get();
for (int count =
0; count < (AUTOTIME * SAMPLINGRATE); count++) {
Timer.delay(1 / SAMPLINGRATE);
double time2 = time.get();
double timeChange = time2 - time1;
time1 = time.get();
double[] acceleration = I2CAccel_getAccel();
distanceTraveled +=
.5 * acceleration[0] * Math.pow(timeChange, 2);
}
}
public static void pingerStart() {
Runnable pinger = () -> {
while (true)
I2CAccel_getAccel();
};
threadPing = new Thread(pinger);
threadPing.start();
}
/**
* Should be equivalent to a method called getAngles of another
* class I2CGyro which isn't here yet.
*
* @author James
* @return Angles, double[] with length of 3
* @see main.java.frc.team4215.stronghold.I2CGyro.getAngles()
*/
private static double[] I2CGyro_getAngles() {
return I2CGyro.getAngles();
}
} |
package fredboat.command.music;
import fredboat.audio.GuildPlayer;
import fredboat.audio.PlayerRegistry;
import fredboat.audio.VideoSelection;
import fredboat.commandmeta.abs.Command;
import fredboat.commandmeta.abs.IMusicCommand;
import fredboat.util.YoutubeAPI;
import fredboat.util.YoutubeVideo;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.dv8tion.jda.MessageBuilder;
import net.dv8tion.jda.entities.Guild;
import net.dv8tion.jda.entities.Message;
import net.dv8tion.jda.entities.SelfInfo;
import net.dv8tion.jda.entities.TextChannel;
import net.dv8tion.jda.entities.User;
public class PlayCommand extends Command implements IMusicCommand {
@Override
public void onInvoke(Guild guild, TextChannel channel, User invoker, Message message, String[] args) {
if (args.length < 2) {
//channel.sendMessage("Proper syntax: ;;play <url-or-search-terms>");
handleNoArguments(guild, channel, invoker, message);
return;
}
//Search youtube for videos and let the user select a video
if (!args[1].startsWith("http")) {
searchForVideos(guild, channel, invoker, message, args);
return;
}
GuildPlayer player = PlayerRegistry.get(guild.getId());
player.currentTC = channel;
player.queue(args[1], channel, invoker);
try {
message.deleteMessage();
} catch (Exception ex) {
}
}
private void handleNoArguments(Guild guild, TextChannel channel, User invoker, Message message) {
GuildPlayer player = PlayerRegistry.get(guild.getId());
if (player.getPlayingTrack() == null) {
channel.sendMessage("The player is not currently playing anything. Use the following syntax to add a song:\n;;play <url-or-search-terms>");
} else if (player.isPlaying()) {
channel.sendMessage("The player is already playing.");
} else if (player.getUsersInVC().isEmpty()) {
channel.sendMessage("There are no users in the voice chat.");
} else {
player.play();
channel.sendMessage("The player will now play.");
}
}
private void searchForVideos(Guild guild, TextChannel channel, User invoker, Message message, String[] args) {
Matcher m = Pattern.compile("\\S+\\s+(.*)").matcher(message.getStrippedContent());
m.find();
String query = m.group(1);
Message outMsg = channel.sendMessage("Searching YouTube for `{q}`...".replace("{q}", query));
ArrayList<YoutubeVideo> vids = YoutubeAPI.searchForVideos(query);
if (vids.isEmpty()) {
outMsg.updateMessage("No results for `{q}`".replace("{q}", query));
} else {
MessageBuilder builder = new MessageBuilder();
builder.appendString("**Please select a video with the `;;select n` command:**");
int i = 1;
for (YoutubeVideo vid : vids) {
builder.appendString("\n**")
.appendString(String.valueOf(i))
.appendString(":** ")
.appendString(vid.name)
.appendString(" (")
.appendString(vid.getDurationFormatted())
.appendString(")");
i++;
}
outMsg.updateMessage(builder.build().getRawContent());
GuildPlayer player = PlayerRegistry.get(guild.getId());
player.currentTC = channel;
player.selections.put(invoker.getId(), new VideoSelection(vids, outMsg));
}
}
} |
package in.twizmwaz.cardinal.util;
import org.bukkit.Bukkit;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
public class DomUtils {
public static Document parse(File file) throws JDOMException, IOException {
SAXBuilder saxBuilder = new SAXBuilder();
Document original = saxBuilder.build(file);
for (Element include : original.getRootElement().getChildren("include")) {
boolean found = false;
File path = file.getParentFile();
String source = include.getAttributeValue("src");
File including = new File(path, source);
if (including.exists()) {
found = true;
try {
for (Element element : parse(including).getRootElement().getChildren()) {
original.getRootElement().addContent(element.clone().detach());
}
} catch (JDOMException | IOException ignored) {}
} else {
while (source.startsWith("../")) {
source = source.replace("../", "");
}
including = new File(path, source);
if (including.exists()) {
found = true;
try {
for (Element element : parse(including).getRootElement().getChildren()) {
original.getRootElement().addContent(element.clone().detach());
}
} catch (JDOMException | IOException ignored) {
}
}
including = new File(path.getParentFile(), source);
if (including.exists()) {
found = true;
try {
for (Element element : parse(including).getRootElement().getChildren()) {
original.getRootElement().addContent(element.clone().detach());
}
} catch (JDOMException | IOException ignored) {
}
}
}
if (!found) Bukkit.getLogger().log(Level.WARNING, "File '" + including.getName() + "' was not found nor included!");
}
return original;
}
} |
package io.mycat.config.model;
import java.io.File;
import java.io.IOException;
import io.mycat.config.Isolations;
/**
*
*
* @author mycat
*/
public final class SystemConfig {
public static final String SYS_HOME = "MYCAT_HOME";
private static final int DEFAULT_PORT = 8066;
private static final int DEFAULT_MANAGER_PORT = 9066;
private static final String DEFAULT_CHARSET = "utf8";
private static final String DEFAULT_SQL_PARSER = "druidparser";// fdbparser, druidparser
private static final short DEFAULT_BUFFER_CHUNK_SIZE = 4096;
private static final int DEFAULT_BUFFER_POOL_PAGE_SIZE = 512*1024*4;
private static final short DEFAULT_BUFFER_POOL_PAGE_NUMBER = 64;
private int processorBufferLocalPercent;
private static final int DEFAULT_PROCESSORS = Runtime.getRuntime().availableProcessors();
private int frontSocketSoRcvbuf = 1024 * 1024;
private int frontSocketSoSndbuf = 4 * 1024 * 1024;
private int backSocketSoRcvbuf = 4 * 1024 * 1024;// mysql 5.6
// net_buffer_length
// defaut 4M
private int backSocketSoSndbuf = 1024 * 1024;
private int frontSocketNoDelay = 1; // 0=false
private int backSocketNoDelay = 1; // 1=true
public static final int DEFAULT_POOL_SIZE = 128;
public static final long DEFAULT_IDLE_TIMEOUT = 30 * 60 * 1000L;
private static final long DEFAULT_PROCESSOR_CHECK_PERIOD = 1 * 1000L;
private static final long DEFAULT_DATANODE_IDLE_CHECK_PERIOD = 5 * 60 * 1000L;
private static final long DEFAULT_DATANODE_HEARTBEAT_PERIOD = 10 * 1000L;
private static final long DEFAULT_CLUSTER_HEARTBEAT_PERIOD = 5 * 1000L;
private static final long DEFAULT_CLUSTER_HEARTBEAT_TIMEOUT = 10 * 1000L;
private static final int DEFAULT_CLUSTER_HEARTBEAT_RETRY = 10;
private static final int DEFAULT_MAX_LIMIT = 100;
private static final String DEFAULT_CLUSTER_HEARTBEAT_USER = "_HEARTBEAT_USER_";
private static final String DEFAULT_CLUSTER_HEARTBEAT_PASS = "_HEARTBEAT_PASS_";
private static final int DEFAULT_PARSER_COMMENT_VERSION = 50148;
private static final int DEFAULT_SQL_RECORD_COUNT = 10;
private int maxStringLiteralLength = 65535;
private int frontWriteQueueSize = 2048;
private String bindIp = "0.0.0.0";
private int serverPort;
private int managerPort;
private String charset;
private int processors;
private int processorExecutor;
private int timerExecutor;
private int managerExecutor;
private long idleTimeout;
private int catletClassCheckSeconds = 60;
// sql execute timeout (second)
private long sqlExecuteTimeout = 300;
private long processorCheckPeriod;
private long dataNodeIdleCheckPeriod;
private long dataNodeHeartbeatPeriod;
private String clusterHeartbeatUser;
private String clusterHeartbeatPass;
private long clusterHeartbeatPeriod;
private long clusterHeartbeatTimeout;
private int clusterHeartbeatRetry;
private int txIsolation;
private int parserCommentVersion;
private int sqlRecordCount;
// a page size
private int bufferPoolPageSize;
//minimum allocation unit
private short bufferPoolChunkSize;
// buffer pool page number
private short bufferPoolPageNumber;
private int defaultMaxLimit = DEFAULT_MAX_LIMIT;
public static final int SEQUENCEHANDLER_LOCALFILE = 0;
public static final int SEQUENCEHANDLER_MYSQLDB = 1;
public static final int SEQUENCEHANDLER_LOCAL_TIME = 2;
public static final int SEQUENCEHANDLER_ZK_DISTRIBUTED = 3;
public static final int SEQUENCEHANDLER_ZK_GLOBAL_INCREMENT = 4;
private int sequnceHandlerType = SEQUENCEHANDLER_LOCALFILE;
private String sqlInterceptor = "io.mycat.server.interceptor.impl.DefaultSqlInterceptor";
private String sqlInterceptorType = "select";
private String sqlInterceptorFile = System.getProperty("user.dir")+"/logs/sql.txt";
public static final int MUTINODELIMIT_SMALL_DATA = 0;
public static final int MUTINODELIMIT_LAR_DATA = 1;
private int mutiNodeLimitType = MUTINODELIMIT_SMALL_DATA;
public static final int MUTINODELIMIT_PATCH_SIZE = 100;
private int mutiNodePatchSize = MUTINODELIMIT_PATCH_SIZE;
private String defaultSqlParser = DEFAULT_SQL_PARSER;
private int usingAIO = 0;
private int packetHeaderSize = 4;
private int maxPacketSize = 16 * 1024 * 1024;
private int mycatNodeId=1;
private int useCompression =0;
private int useSqlStat = 1;
private boolean enableDistributedTransactions = true;
private int checkTableConsistency = 0;
private long checkTableConsistencyPeriod = CHECKTABLECONSISTENCYPERIOD;
private final static long CHECKTABLECONSISTENCYPERIOD = 1 * 60 * 1000;
private int processorBufferPoolType = 0;
public boolean isEnableDistributedTransactions() {
return enableDistributedTransactions;
}
public void setEnableDistributedTransactions(boolean enableDistributedTransactions) {
this.enableDistributedTransactions = enableDistributedTransactions;
}
public String getDefaultSqlParser() {
return defaultSqlParser;
}
public void setDefaultSqlParser(String defaultSqlParser) {
this.defaultSqlParser = defaultSqlParser;
}
public SystemConfig() {
this.serverPort = DEFAULT_PORT;
this.managerPort = DEFAULT_MANAGER_PORT;
this.charset = DEFAULT_CHARSET;
this.processors = DEFAULT_PROCESSORS;
this.bufferPoolPageSize = DEFAULT_BUFFER_POOL_PAGE_SIZE;
this.bufferPoolChunkSize = DEFAULT_BUFFER_CHUNK_SIZE;
this.bufferPoolPageNumber = (short) (DEFAULT_PROCESSORS*2);
this.processorExecutor = (DEFAULT_PROCESSORS != 1) ? DEFAULT_PROCESSORS * 2 : 4;
this.managerExecutor = 2;
this.processorBufferLocalPercent = 100;
this.timerExecutor = 2;
this.idleTimeout = DEFAULT_IDLE_TIMEOUT;
this.processorCheckPeriod = DEFAULT_PROCESSOR_CHECK_PERIOD;
this.dataNodeIdleCheckPeriod = DEFAULT_DATANODE_IDLE_CHECK_PERIOD;
this.dataNodeHeartbeatPeriod = DEFAULT_DATANODE_HEARTBEAT_PERIOD;
this.clusterHeartbeatUser = DEFAULT_CLUSTER_HEARTBEAT_USER;
this.clusterHeartbeatPass = DEFAULT_CLUSTER_HEARTBEAT_PASS;
this.clusterHeartbeatPeriod = DEFAULT_CLUSTER_HEARTBEAT_PERIOD;
this.clusterHeartbeatTimeout = DEFAULT_CLUSTER_HEARTBEAT_TIMEOUT;
this.clusterHeartbeatRetry = DEFAULT_CLUSTER_HEARTBEAT_RETRY;
this.txIsolation = Isolations.REPEATED_READ;
this.parserCommentVersion = DEFAULT_PARSER_COMMENT_VERSION;
this.sqlRecordCount = DEFAULT_SQL_RECORD_COUNT;
}
public String getSqlInterceptor() {
return sqlInterceptor;
}
public void setSqlInterceptor(String sqlInterceptor) {
this.sqlInterceptor = sqlInterceptor;
}
public int getSequnceHandlerType() {
return sequnceHandlerType;
}
public void setSequnceHandlerType(int sequnceHandlerType) {
this.sequnceHandlerType = sequnceHandlerType;
}
public int getPacketHeaderSize() {
return packetHeaderSize;
}
public void setPacketHeaderSize(int packetHeaderSize) {
this.packetHeaderSize = packetHeaderSize;
}
public int getMaxPacketSize() {
return maxPacketSize;
}
public int getCatletClassCheckSeconds() {
return catletClassCheckSeconds;
}
public void setCatletClassCheckSeconds(int catletClassCheckSeconds) {
this.catletClassCheckSeconds = catletClassCheckSeconds;
}
public void setMaxPacketSize(int maxPacketSize) {
this.maxPacketSize = maxPacketSize;
}
public int getFrontWriteQueueSize() {
return frontWriteQueueSize;
}
public void setFrontWriteQueueSize(int frontWriteQueueSize) {
this.frontWriteQueueSize = frontWriteQueueSize;
}
public String getBindIp() {
return bindIp;
}
public void setBindIp(String bindIp) {
this.bindIp = bindIp;
}
public int getDefaultMaxLimit() {
return defaultMaxLimit;
}
public void setDefaultMaxLimit(int defaultMaxLimit) {
this.defaultMaxLimit = defaultMaxLimit;
}
public static String getHomePath() {
String home = System.getProperty(SystemConfig.SYS_HOME);
if (home != null) {
if (home.endsWith(File.pathSeparator)) {
home = home.substring(0, home.length() - 1);
System.setProperty(SystemConfig.SYS_HOME, home);
}
}
// MYCAT_HOMEBEN
if(home == null) {
try {
String path = new File("..").getCanonicalPath().replaceAll("\\\\", "/");
File conf = new File(path+"/conf");
if(conf.exists() && conf.isDirectory()) {
home = path;
} else {
path = new File(".").getCanonicalPath().replaceAll("\\\\", "/");
conf = new File(path+"/conf");
if(conf.exists() && conf.isDirectory()) {
home = path;
}
}
if (home != null) {
System.setProperty(SystemConfig.SYS_HOME, home);
}
} catch (IOException e) {
}
}
return home;
}
// SQL
public int getUseSqlStat()
{
return useSqlStat;
}
public void setUseSqlStat(int useSqlStat)
{
this.useSqlStat = useSqlStat;
}
public int getUseCompression()
{
return useCompression;
}
public void setUseCompression(int useCompression)
{
this.useCompression = useCompression;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public int getServerPort() {
return serverPort;
}
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
}
public int getManagerPort() {
return managerPort;
}
public void setManagerPort(int managerPort) {
this.managerPort = managerPort;
}
public int getProcessors() {
return processors;
}
public void setProcessors(int processors) {
this.processors = processors;
}
public int getProcessorExecutor() {
return processorExecutor;
}
public void setProcessorExecutor(int processorExecutor) {
this.processorExecutor = processorExecutor;
}
public int getManagerExecutor() {
return managerExecutor;
}
public void setManagerExecutor(int managerExecutor) {
this.managerExecutor = managerExecutor;
}
public int getTimerExecutor() {
return timerExecutor;
}
public void setTimerExecutor(int timerExecutor) {
this.timerExecutor = timerExecutor;
}
public long getIdleTimeout() {
return idleTimeout;
}
public void setIdleTimeout(long idleTimeout) {
this.idleTimeout = idleTimeout;
}
public long getProcessorCheckPeriod() {
return processorCheckPeriod;
}
public void setProcessorCheckPeriod(long processorCheckPeriod) {
this.processorCheckPeriod = processorCheckPeriod;
}
public long getDataNodeIdleCheckPeriod() {
return dataNodeIdleCheckPeriod;
}
public void setDataNodeIdleCheckPeriod(long dataNodeIdleCheckPeriod) {
this.dataNodeIdleCheckPeriod = dataNodeIdleCheckPeriod;
}
public long getDataNodeHeartbeatPeriod() {
return dataNodeHeartbeatPeriod;
}
public void setDataNodeHeartbeatPeriod(long dataNodeHeartbeatPeriod) {
this.dataNodeHeartbeatPeriod = dataNodeHeartbeatPeriod;
}
public String getClusterHeartbeatUser() {
return clusterHeartbeatUser;
}
public void setClusterHeartbeatUser(String clusterHeartbeatUser) {
this.clusterHeartbeatUser = clusterHeartbeatUser;
}
public long getSqlExecuteTimeout() {
return sqlExecuteTimeout;
}
public void setSqlExecuteTimeout(long sqlExecuteTimeout) {
this.sqlExecuteTimeout = sqlExecuteTimeout;
}
public String getClusterHeartbeatPass() {
return clusterHeartbeatPass;
}
public void setClusterHeartbeatPass(String clusterHeartbeatPass) {
this.clusterHeartbeatPass = clusterHeartbeatPass;
}
public long getClusterHeartbeatPeriod() {
return clusterHeartbeatPeriod;
}
public void setClusterHeartbeatPeriod(long clusterHeartbeatPeriod) {
this.clusterHeartbeatPeriod = clusterHeartbeatPeriod;
}
public long getClusterHeartbeatTimeout() {
return clusterHeartbeatTimeout;
}
public void setClusterHeartbeatTimeout(long clusterHeartbeatTimeout) {
this.clusterHeartbeatTimeout = clusterHeartbeatTimeout;
}
public int getFrontsocketsorcvbuf() {
return frontSocketSoRcvbuf;
}
public int getFrontsocketsosndbuf() {
return frontSocketSoSndbuf;
}
public int getBacksocketsorcvbuf() {
return backSocketSoRcvbuf;
}
public int getBacksocketsosndbuf() {
return backSocketSoSndbuf;
}
public int getClusterHeartbeatRetry() {
return clusterHeartbeatRetry;
}
public void setClusterHeartbeatRetry(int clusterHeartbeatRetry) {
this.clusterHeartbeatRetry = clusterHeartbeatRetry;
}
public int getTxIsolation() {
return txIsolation;
}
public void setTxIsolation(int txIsolation) {
this.txIsolation = txIsolation;
}
public int getParserCommentVersion() {
return parserCommentVersion;
}
public void setParserCommentVersion(int parserCommentVersion) {
this.parserCommentVersion = parserCommentVersion;
}
public int getSqlRecordCount() {
return sqlRecordCount;
}
public void setSqlRecordCount(int sqlRecordCount) {
this.sqlRecordCount = sqlRecordCount;
}
public short getBufferPoolChunkSize() {
return bufferPoolChunkSize;
}
public void setBufferPoolChunkSize(short bufferPoolChunkSize) {
this.bufferPoolChunkSize = bufferPoolChunkSize;
}
public int getBufferPoolPageSize() {
return bufferPoolPageSize;
}
public void setBufferPoolPageSize(int bufferPoolPageSize) {
this.bufferPoolPageSize = bufferPoolPageSize;
}
public short getBufferPoolPageNumber() {
return bufferPoolPageNumber;
}
public void setBufferPoolPageNumber(short bufferPoolPageNumber) {
this.bufferPoolPageNumber = bufferPoolPageNumber;
}
public int getFrontSocketSoRcvbuf() {
return frontSocketSoRcvbuf;
}
public void setFrontSocketSoRcvbuf(int frontSocketSoRcvbuf) {
this.frontSocketSoRcvbuf = frontSocketSoRcvbuf;
}
public int getFrontSocketSoSndbuf() {
return frontSocketSoSndbuf;
}
public void setFrontSocketSoSndbuf(int frontSocketSoSndbuf) {
this.frontSocketSoSndbuf = frontSocketSoSndbuf;
}
public int getBackSocketSoRcvbuf() {
return backSocketSoRcvbuf;
}
public void setBackSocketSoRcvbuf(int backSocketSoRcvbuf) {
this.backSocketSoRcvbuf = backSocketSoRcvbuf;
}
public int getBackSocketSoSndbuf() {
return backSocketSoSndbuf;
}
public void setBackSocketSoSndbuf(int backSocketSoSndbuf) {
this.backSocketSoSndbuf = backSocketSoSndbuf;
}
public int getFrontSocketNoDelay() {
return frontSocketNoDelay;
}
public void setFrontSocketNoDelay(int frontSocketNoDelay) {
this.frontSocketNoDelay = frontSocketNoDelay;
}
public int getBackSocketNoDelay() {
return backSocketNoDelay;
}
public void setBackSocketNoDelay(int backSocketNoDelay) {
this.backSocketNoDelay = backSocketNoDelay;
}
public int getMaxStringLiteralLength() {
return maxStringLiteralLength;
}
public void setMaxStringLiteralLength(int maxStringLiteralLength) {
this.maxStringLiteralLength = maxStringLiteralLength;
}
public int getMutiNodeLimitType() {
return mutiNodeLimitType;
}
public void setMutiNodeLimitType(int mutiNodeLimitType) {
this.mutiNodeLimitType = mutiNodeLimitType;
}
public int getMutiNodePatchSize() {
return mutiNodePatchSize;
}
public void setMutiNodePatchSize(int mutiNodePatchSize) {
this.mutiNodePatchSize = mutiNodePatchSize;
}
public int getProcessorBufferLocalPercent() {
return processorBufferLocalPercent;
}
public void setProcessorBufferLocalPercent(int processorBufferLocalPercent) {
this.processorBufferLocalPercent = processorBufferLocalPercent;
}
public String getSqlInterceptorType() {
return sqlInterceptorType;
}
public void setSqlInterceptorType(String sqlInterceptorType) {
this.sqlInterceptorType = sqlInterceptorType;
}
public String getSqlInterceptorFile() {
return sqlInterceptorFile;
}
public void setSqlInterceptorFile(String sqlInterceptorFile) {
this.sqlInterceptorFile = sqlInterceptorFile;
}
public int getUsingAIO() {
return usingAIO;
}
public void setUsingAIO(int usingAIO) {
this.usingAIO = usingAIO;
}
public int getMycatNodeId() {
return mycatNodeId;
}
public void setMycatNodeId(int mycatNodeId) {
this.mycatNodeId = mycatNodeId;
}
@Override
public String toString() {
return "SystemConfig [processorBufferLocalPercent="
+ processorBufferLocalPercent + ", frontSocketSoRcvbuf="
+ frontSocketSoRcvbuf + ", frontSocketSoSndbuf="
+ frontSocketSoSndbuf + ", backSocketSoRcvbuf="
+ backSocketSoRcvbuf + ", backSocketSoSndbuf="
+ backSocketSoSndbuf + ", frontSocketNoDelay="
+ frontSocketNoDelay + ", backSocketNoDelay="
+ backSocketNoDelay + ", maxStringLiteralLength="
+ maxStringLiteralLength + ", frontWriteQueueSize="
+ frontWriteQueueSize + ", bindIp=" + bindIp + ", serverPort="
+ serverPort + ", managerPort=" + managerPort + ", charset="
+ charset + ", processors=" + processors
+ ", processorExecutor=" + processorExecutor
+ ", timerExecutor=" + timerExecutor + ", managerExecutor="
+ managerExecutor + ", idleTimeout=" + idleTimeout
+ ", catletClassCheckSeconds=" + catletClassCheckSeconds
+ ", sqlExecuteTimeout=" + sqlExecuteTimeout
+ ", processorCheckPeriod=" + processorCheckPeriod
+ ", dataNodeIdleCheckPeriod=" + dataNodeIdleCheckPeriod
+ ", dataNodeHeartbeatPeriod=" + dataNodeHeartbeatPeriod
+ ", clusterHeartbeatUser=" + clusterHeartbeatUser
+ ", clusterHeartbeatPass=" + clusterHeartbeatPass
+ ", clusterHeartbeatPeriod=" + clusterHeartbeatPeriod
+ ", clusterHeartbeatTimeout=" + clusterHeartbeatTimeout
+ ", clusterHeartbeatRetry=" + clusterHeartbeatRetry
+ ", txIsolation=" + txIsolation + ", parserCommentVersion="
+ parserCommentVersion + ", sqlRecordCount=" + sqlRecordCount
+ ", bufferPoolPageSize=" + bufferPoolPageSize
+ ", bufferPoolChunkSize=" + bufferPoolChunkSize
+ ", bufferPoolPageNumber=" + bufferPoolPageNumber
+ ", defaultMaxLimit=" + defaultMaxLimit
+ ", sequnceHandlerType=" + sequnceHandlerType
+ ", sqlInterceptor=" + sqlInterceptor
+ ", sqlInterceptorType=" + sqlInterceptorType
+ ", sqlInterceptorFile=" + sqlInterceptorFile
+ ", mutiNodeLimitType=" + mutiNodeLimitType
+ ", mutiNodePatchSize=" + mutiNodePatchSize
+ ", defaultSqlParser=" + defaultSqlParser
+ ", usingAIO=" + usingAIO
+ ", packetHeaderSize=" + packetHeaderSize
+ ", maxPacketSize=" + maxPacketSize
+ ", mycatNodeId=" + mycatNodeId + "]";
}
public int getCheckTableConsistency() {
return checkTableConsistency;
}
public void setCheckTableConsistency(int checkTableConsistency) {
this.checkTableConsistency = checkTableConsistency;
}
public long getCheckTableConsistencyPeriod() {
return checkTableConsistencyPeriod;
}
public void setCheckTableConsistencyPeriod(long checkTableConsistencyPeriod) {
this.checkTableConsistencyPeriod = checkTableConsistencyPeriod;
}
public int getProcessorBufferPoolType() {
return processorBufferPoolType;
}
public void setProcessorBufferPoolType(int processorBufferPoolType) {
this.processorBufferPoolType = processorBufferPoolType;
}
} |
package jbyoshi.blockdodge.core;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import javax.swing.*;
import jbyoshi.blockdodge.*;
public final class BlockDodge extends JPanel {
private final int width, height;
final Random rand = new Random();
private static final Color[] COLORS = new Color[] { Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA,
new Color(255, 127, 0), new Color(0, 140, 0), Color.RED, Color.YELLOW };
private static final int FRAME_TIME = 1000 / 75;
private BufferedImage buffer;
private final Set<DodgeShape> shapes = new HashSet<DodgeShape>();
private final PlayerDodgeShape player = new PlayerDodgeShape(this);
private final AtomicBoolean stop = new AtomicBoolean(false);
public BlockDodge(int width, int height) {
this.width = width;
this.height = height;
this.buffer = createBuffer();
addKeyListener(player);
}
private BufferedImage createBuffer() {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
public void add(DodgeShape shape) {
shapes.add(shape);
}
public void remove(DodgeShape shape) {
shapes.remove(shape);
if (shape.getDropCount() == 0) {
shape.onRemoved();
}
}
public boolean contains(DodgeShape shape) {
return shapes.contains(shape);
}
public PlayerDodgeShape getPlayer() {
return player;
}
public void go(boolean includePlayer) {
shapes.clear();
if (includePlayer) {
player.reset();
shapes.add(player);
}
int timer = 0;
stop.set(false);
while (!stop.get()) {
long start = System.currentTimeMillis();
for (DodgeShape shape : new HashSet<DodgeShape>(shapes)) {
shape.move();
}
for (DodgeShape one : new HashSet<DodgeShape>(shapes)) {
if (!shapes.contains(one)) {
continue; // Removed during a previous iteration
}
for (DodgeShape two : new HashSet<DodgeShape>(shapes)) {
if (!shapes.contains(two) || one == two) {
continue;
}
if (one.collides(two)) {
// Drops take care of it themselves.
boolean handled = false;
if (one instanceof DodgeShape.Drop) {
one.onCollided(two);
handled = true;
}
if (two instanceof DodgeShape.Drop) {
two.onCollided(one);
handled = true;
}
if (!handled) {
one.onCollided(two);
two.onCollided(one);
}
}
}
}
if (timer % 100 == 0) {
int w = rand.nextInt(25) + 8;
int h = rand.nextInt(25) + 8;
int pos = rand.nextInt(width + w + width + w + height + h + height + h);
int x, y;
float dirChg;
if (pos < width + w) {
// From top
x = pos - w + 1;
y = -h;
dirChg = 0.25f;
} else {
pos -= width + w;
if (pos < width + w) {
// From bottom
x = pos - w;
y = height;
dirChg = 0.75f;
} else {
pos -= width + w;
if (pos < height + h) {
// From left
x = -w;
y = pos - h;
dirChg = 0;
} else {
// From right
pos -= height + h;
x = width;
y = pos - h + 1;
dirChg = 0.5f;
}
}
}
float dir = (rand.nextFloat() / 2 + dirChg) % 1;
Color c = COLORS[rand.nextInt(COLORS.length)];
add(new BadDodgeShape(this, x, y, w, h, c, (float) (dir * 2 * Math.PI)));
}
BufferedImage buffer = createBuffer();
Graphics2D g = buffer.createGraphics();
for (DodgeShape shape : shapes) {
g.setColor(shape.color);
g.fill(shape.shape);
}
g.dispose();
this.buffer = buffer;
repaint();
timer++;
if (contains(player)) {
requestFocusInWindow();
} else if (includePlayer && player.getDropCount() == 0) {
return;
}
long sleep = FRAME_TIME - (System.currentTimeMillis() - start);
if (sleep > 0) {
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
}
}
}
}
public void stop() {
stop.set(true);
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(buffer, 0, 0, null);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(width, height);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(width, height);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Block Dodge");
final BlockDodge game = new BlockDodge(800, 600);
frame.setContentPane(game);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
final AtomicBoolean isPlaying = new AtomicBoolean(false);
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (isPlaying.get()) {
return;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
case KeyEvent.VK_SPACE:
game.stop();
break;
}
}
});
while (true) {
game.go(false);
isPlaying.set(true);
game.go(true);
isPlaying.set(false);
}
}
} |
package markpeng.kaggle.ssr;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.en.KStemFilter;
import org.apache.lucene.analysis.miscellaneous.WordDelimiterFilter;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.spell.LevensteinDistance;
import org.apache.lucene.search.spell.NGramDistance;
import org.apache.lucene.search.spell.PlainTextDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
public class DatasetCleaner {
private static final int BUFFER_LENGTH = 1000;
private static final String newLine = System.getProperty("line.separator");
private static final double MIN_SIMILARITY = 0.75;
public List<String> readFile(String filePath) throws Exception {
List<String> result = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), "UTF-8"));
try {
String aLine = null;
while ((aLine = in.readLine()) != null) {
String tmp = aLine.toLowerCase().trim();
if (tmp.length() > 0 && !result.contains(tmp))
result.add(tmp);
}
} finally {
in.close();
}
return result;
}
public Set<String> readDictionary(String dicPath) throws Exception {
TreeSet<String> result = new TreeSet<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(dicPath), "UTF-8"));
try {
String aLine = null;
while ((aLine = in.readLine()) != null) {
String tmp = aLine.toLowerCase().trim();
if (!result.contains(tmp) && !tmp.startsWith("'"))
result.add(tmp);
}
} finally {
in.close();
}
return result;
}
public List<String> readFeature(String... featureFiles) throws Exception {
List<String> features = new ArrayList<String>();
for (String featureFile : featureFiles) {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(featureFile), "UTF-8"));
try {
String aLine = null;
while ((aLine = in.readLine()) != null) {
String tmp = aLine.toLowerCase().trim();
String[] tmpArray = tmp.split("\\s");
String feature = tmpArray[0].trim();
if (!features.contains(feature))
features.add(feature);
}
} finally {
in.close();
}
}
return features;
}
public String replaceSynonyms(String text) {
String result = text.toLowerCase();
if (result.contains("fridge"))
result = result.replace("fridge", "refrigerator");
if (result.contains("refrigirator"))
result = result.replace("refrigirator", "refrigerator");
if (result.contains("assassinss"))
result = result.replace("assassinss", "assassin");
if (result.contains("assassins"))
result = result.replace("assassins", "assassin");
if (result.contains("bedspreads"))
result = result.replace("bedspreads", "bed spread");
if (result.contains("bedspread"))
result = result.replace("bedspread", "bed spread");
if (result.contains("blue toot"))
result = result.replace("blue toot", "blue tooth");
if (result.contains("bluetooth"))
result = result.replace("bluetooth", "blue tooth");
if (result.contains("bike"))
result = result.replace("bike", "bicycle");
if (result.contains("photo"))
result = result.replace("photo", "picture");
if (result.contains("fragance"))
result = result.replace("fragance", "fragrance");
if (result.contains("beard trimmer"))
result = result.replace("beard trimmer", "shaver");
if (result.contains("evening gown"))
result = result.replace("evening gown", "prom dress");
if (result.contains("handbag"))
result = result.replace("handbag", "hand bag");
if (result.contains("hdtv"))
result = result.replace("hdtv", "hd tv");
if (result.contains("parfum"))
result = result.replace("parfum", "perfume");
if (result.contains("plus size"))
result = result.replace("plus size", "women clothes");
if (result.contains("tervi 11"))
result = result.replace("tervi 11", "reuse straw");
if (result.contains("micromink"))
result = result.replace("micromink", "blanket");
if (result.contains("gown"))
result = result.replace("gown", "dress");
if (result.contains("cushion"))
result = result.replace("cushion", "rug");
if (result.contains("mat"))
result = result.replace("mat", "rug");
if (result.contains("doormat"))
result = result.replace("doormat", "door mat");
// if (result.contains(""))
// result = result.replace("", "");
return result;
}
public void clean(String trainFile, String testFile, String outputTrain,
String outputTest, String compoundPath) throws Exception {
List<String> compounds = readFile(compoundPath);
StringBuffer resultStr = new StringBuffer();
BufferedReader trainIn = new BufferedReader(new InputStreamReader(
new FileInputStream(trainFile), "UTF-8"));
BufferedReader testIn = new BufferedReader(new InputStreamReader(
new FileInputStream(testFile), "UTF-8"));
BufferedWriter trainOut = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputTrain, false), "UTF-8"));
BufferedWriter testOut = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputTest, false), "UTF-8"));
CsvParserSettings settings = new CsvParserSettings();
settings.setParseUnescapedQuotes(false);
settings.getFormat().setLineSeparator("\n");
settings.getFormat().setDelimiter(',');
settings.getFormat().setQuote('"');
settings.setHeaderExtractionEnabled(true);
settings.setEmptyValue("");
settings.setMaxCharsPerColumn(40960);
// Train Data
// create headers
resultStr
.append("\"id\",\"query\",\"product_title\",\"product_description\",\""
+ "median_relevance\",\"relevance_variance\"");
resultStr.append(newLine);
try {
// creates a CSV parser
CsvParser trainParser = new CsvParser(settings);
// call beginParsing to read records one by one, iterator-style.
trainParser.beginParsing(trainIn);
int count = 0;
String[] tokens;
while ((tokens = trainParser.parseNext()) != null) {
String id = tokens[0];
String query = tokens[1].replace("\"", "").trim();
String productTitle = tokens[2].replace("\"", "").trim();
String productDesc = tokens[3].replace("\"", "").trim();
int medianRelevance = Integer.parseInt(tokens[4]);
double relevance_variance = Double.parseDouble(tokens[5]);
// preprocessing
String cleanQuery = processTextByLucene(getTextFromRawData(query));
String cleanProductTitle = processTextByLucene(getTextFromRawData(productTitle));
String cleanProductDesc = processTextByLucene(getTextFromRawData(productDesc));
// replace compounds
for (String c : compounds) {
String tmp = c.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, c);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, c);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, c);
}
resultStr.append("\"" + id + "\",\"" + cleanQuery + "\",\""
+ cleanProductTitle + "\",\"" + cleanProductDesc
+ "\",\"" + medianRelevance + "\",\""
+ relevance_variance + "\"");
resultStr.append(newLine);
if (resultStr.length() >= BUFFER_LENGTH) {
trainOut.write(resultStr.toString());
trainOut.flush();
resultStr.setLength(0);
}
count++;
}
System.out.println("Total train records: " + count);
} finally {
trainIn.close();
trainOut.write(resultStr.toString());
trainOut.flush();
trainOut.close();
resultStr.setLength(0);
}
// Test Data
resultStr.setLength(0);
// create headers
resultStr
.append("\"id\",\"query\",\"product_title\",\"product_description\"");
resultStr.append(newLine);
try {
// creates a CSV parser
CsvParser testParser = new CsvParser(settings);
// call beginParsing to read records one by one, iterator-style.
testParser.beginParsing(testIn);
int count = 0;
String[] tokens;
while ((tokens = testParser.parseNext()) != null) {
String id = tokens[0];
String query = tokens[1].replace("\"", "").trim();
String productTitle = tokens[2].replace("\"", "").trim();
String productDesc = tokens[3].replace("\"", "").trim();
// preprocessing
String cleanQuery = processTextByLucene(getTextFromRawData(query));
String cleanProductTitle = processTextByLucene(getTextFromRawData(productTitle));
String cleanProductDesc = processTextByLucene(getTextFromRawData(productDesc));
// replace compounds
for (String c : compounds) {
String tmp = c.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, c);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, c);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, c);
}
resultStr
.append("\"" + id + "\",\"" + cleanQuery + "\",\""
+ cleanProductTitle + "\",\""
+ cleanProductDesc + "\"");
resultStr.append(newLine);
if (resultStr.length() >= BUFFER_LENGTH) {
testOut.write(resultStr.toString());
testOut.flush();
resultStr.setLength(0);
}
count++;
}
System.out.println("Total test records: " + count);
} finally {
testIn.close();
testOut.write(resultStr.toString());
testOut.flush();
testOut.close();
resultStr.setLength(0);
}
System.out.flush();
}
public void generate(String trainFile, String testFile, String outputTrain,
String outputTest, String compoundPath, String smallWordPath)
throws Exception {
System.setOut(new PrintStream(
new BufferedOutputStream(
new FileOutputStream(
"/home/markpeng/Share/Kaggle/Search Results Relevance/preprocess_notmatched_score4_20150518.txt")),
true));
List<String> compounds = readFile(compoundPath);
List<String> smallWords = readFile(smallWordPath);
NGramDistance similarityTool = new NGramDistance(2);
StringBuffer resultStr = new StringBuffer();
BufferedReader trainIn = new BufferedReader(new InputStreamReader(
new FileInputStream(trainFile), "UTF-8"));
BufferedReader testIn = new BufferedReader(new InputStreamReader(
new FileInputStream(testFile), "UTF-8"));
BufferedWriter trainOut = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputTrain, false), "UTF-8"));
BufferedWriter testOut = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputTest, false), "UTF-8"));
CsvParserSettings settings = new CsvParserSettings();
settings.setParseUnescapedQuotes(false);
settings.getFormat().setLineSeparator("\n");
settings.getFormat().setDelimiter(',');
settings.getFormat().setQuote('"');
settings.setHeaderExtractionEnabled(true);
settings.setEmptyValue("");
settings.setMaxCharsPerColumn(40960);
// Train Data
int score4Count = 0;
int score3Count = 0;
int score2Count = 0;
int score1Count = 0;
int score4MatchedCount = 0;
int score3MatchedCount = 0;
int score2MatchedCount = 0;
int score1MatchedCount = 0;
// create headers
resultStr
.append("\"id\",\"query\",\"product_title\",\"product_description\",\""
+ "median_relevance\",\"relevance_variance\",\""
+ "qInTitle\",\"qInDesc\",\""
+ "prefixMatchInTitle\",\"secondMatchInTitle\",\"midMatchInTitle\",\"suffixMatchInTitle\"");
resultStr.append(newLine);
try {
// creates a CSV parser
CsvParser trainParser = new CsvParser(settings);
// call beginParsing to read records one by one, iterator-style.
trainParser.beginParsing(trainIn);
int count = 0;
String[] tokens;
while ((tokens = trainParser.parseNext()) != null) {
String id = tokens[0];
String query = tokens[1].replace("\"", "").trim();
String productTitle = tokens[2].replace("\"", "").trim();
String productDesc = tokens[3].replace("\"", "").trim();
int medianRelevance = Integer.parseInt(tokens[4]);
double relevance_variance = Double.parseDouble(tokens[5]);
// if (id.equals("204"))
// System.out.println();
// preprocessing
String cleanQuery = processTextByLucene(getTextFromRawData(query));
String cleanProductTitle = processTextByLucene(getTextFromRawData(productTitle));
String cleanProductDesc = processTextByLucene(getTextFromRawData(productDesc));
// replace compounds
for (String c : compounds) {
String tmp = c.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, c);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, c);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, c);
}
// replace small words generated from title
for (String s : smallWords) {
String tmp = s.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, s);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, s);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, s);
}
// replace all synonyms
cleanQuery = replaceSynonyms(cleanQuery);
cleanProductTitle = replaceSynonyms(cleanProductTitle);
cleanProductDesc = replaceSynonyms(cleanProductDesc);
Hashtable<String, Integer> qTokens = getTermFreqByLucene(
cleanQuery, true, true);
Hashtable<String, Integer> titleTokens = getTermFreqByLucene(
cleanProductTitle, true, true);
Hashtable<String, Integer> descTokens = getTermFreqByLucene(
cleanProductDesc, true, true);
Hashtable<String, Integer> matchedTermsInTitle = new Hashtable<String, Integer>();
Hashtable<String, Integer> matchedTermsInDesc = new Hashtable<String, Integer>();
int titleMatched = 0;
int descMatched = 0;
for (String q : qTokens.keySet()) {
if (titleTokens.containsKey(q)) {
if (!matchedTermsInTitle.containsKey(query))
matchedTermsInTitle.put(query, titleTokens.get(q));
else
matchedTermsInTitle.put(query,
matchedTermsInTitle.get(query)
+ titleTokens.get(q));
titleMatched++;
} else {
for (String t : titleTokens.keySet()) {
float sim = similarityTool.getDistance(q, t);
if (sim >= MIN_SIMILARITY) {
titleMatched++;
break;
}
}
}
if (descTokens.containsKey(q)) {
if (!matchedTermsInDesc.containsKey(query))
matchedTermsInDesc.put(query, descTokens.get(q));
else
matchedTermsInDesc.put(
query,
matchedTermsInDesc.get(query)
+ descTokens.get(q));
descMatched++;
} else {
for (String d : descTokens.keySet()) {
float sim = similarityTool.getDistance(q, d);
if (sim >= MIN_SIMILARITY) {
descMatched++;
break;
}
}
}
}
// qInTitle
double qInTitle = (double) titleMatched / qTokens.size();
// qInDesc
double qInDesc = (double) descMatched / qTokens.size();
// matching statistics
if (medianRelevance == 4) {
if (qInTitle == 1 || qInDesc == 1)
score4MatchedCount++;
else {
System.out.println("\n[id=" + id + "]");
System.out.println("query:" + cleanQuery);
System.out
.println("product_title:" + cleanProductTitle);
System.out.println("product_description:"
+ cleanProductDesc);
System.out.println("median_relevance:"
+ medianRelevance);
System.out.println("qInTitle:" + qInTitle);
System.out.println("qInDesc:" + qInDesc);
}
score4Count++;
} else if (medianRelevance == 3) {
if (qInTitle == 1 || qInDesc == 1)
score3MatchedCount++;
else {
// System.out.println("\n[id=" + id + "]");
// System.out.println("query:" + cleanQuery);
// System.out
// .println("product_title:" + cleanProductTitle);
// System.out.println("product_description:"
// + cleanProductDesc);
// System.out.println("median_relevance:"
// + medianRelevance);
}
score3Count++;
} else if (medianRelevance == 2) {
if (qInTitle == 1 || qInDesc == 1)
score2MatchedCount++;
else {
// System.out.println("\n[id=" + id + "]");
// System.out.println("query:" + cleanQuery);
// System.out
// .println("product_title:" + cleanProductTitle);
// System.out.println("product_description:"
// + cleanProductDesc);
// System.out.println("median_relevance:"
// + medianRelevance);
}
score2Count++;
} else if (medianRelevance == 1) {
if (qInTitle == 1 || qInDesc == 1)
score1MatchedCount++;
else {
// System.out.println("\n[id=" + id + "]");
// System.out.println("query:" + cleanQuery);
// System.out
// .println("product_title:" + cleanProductTitle);
// System.out.println("product_description:"
// + cleanProductDesc);
// System.out.println("median_relevance:"
// + medianRelevance);
}
score1Count++;
}
String[] qTmp = cleanQuery.split("\\s");
// prefixMatch in title
int prefixMatchInTitle = 0;
String prefixQ = qTmp[0];
if (titleTokens.containsKey(prefixQ))
prefixMatchInTitle = 1;
// TODO:
// prefix match in 1st token of title
// 2nd match in 2nd token of title
// suffix match in last token of title
// query token match in 1st token of title
// query token match in 2nd token of title
// query token match in last token of title
// matched distance with query tokens in title and desc
// TODO:
// match in description
// TODO:
// compound match in prefix of title
// compound match in mid of title
// compound match in suffix of title
// TODO:
// fully matched or fully not matched flag in query token
// (either appearing in title or description)
// secondMatch in title
int secondMatchInTitle = 0;
if (qTmp.length >= 2) {
String secondQ = qTmp[1];
if (titleTokens.containsKey(secondQ))
secondMatchInTitle = 1;
}
// midMatch in title
int midMatchInTitle = 0;
for (int i = 1; i < qTmp.length - 1; i++) {
if (titleTokens.containsKey(qTmp[i]))
midMatchInTitle = 1;
}
// suffixMatch in title
int suffixMatchInTitle = 0;
String suffixQ = qTmp[qTmp.length - 1];
if (titleTokens.containsKey(suffixQ))
suffixMatchInTitle = 1;
resultStr.append("\"" + id + "\",\"" + cleanQuery + "\",\""
+ cleanProductTitle + "\",\"" + cleanProductDesc
+ "\",\"" + medianRelevance + "\",\""
+ relevance_variance + "\",\"" + qInTitle + "\",\""
+ qInDesc + "\",\"" + prefixMatchInTitle + "\",\""
+ secondMatchInTitle + "\",\"" + midMatchInTitle
+ "\",\"" + suffixMatchInTitle + "\"");
resultStr.append(newLine);
if (resultStr.length() >= BUFFER_LENGTH) {
trainOut.write(resultStr.toString());
trainOut.flush();
resultStr.setLength(0);
}
count++;
}
System.out.println("Total train records: " + count);
System.out.println("Full match rate for score 4: "
+ ((double) score4MatchedCount / score4Count) * 100);
System.out.println("Full match rate for score 3: "
+ ((double) score3MatchedCount / score3Count) * 100);
System.out.println("Full match rate for score 2: "
+ ((double) score2MatchedCount / score2Count) * 100);
System.out.println("Full match rate for score 1: "
+ ((double) score1MatchedCount / score1Count) * 100);
} finally {
trainIn.close();
trainOut.write(resultStr.toString());
trainOut.flush();
trainOut.close();
resultStr.setLength(0);
}
// Test Data
resultStr.setLength(0);
// create headers
resultStr
.append("\"id\",\"query\",\"product_title\",\"product_description\",\""
+ "qInTitle\",\"qInDesc\",\""
+ "prefixMatchInTitle\",\"secondMatchInTitle\",\"midMatchInTitle\",\"suffixMatchInTitle\"");
resultStr.append(newLine);
try {
// creates a CSV parser
CsvParser testParser = new CsvParser(settings);
// call beginParsing to read records one by one, iterator-style.
testParser.beginParsing(testIn);
int count = 0;
String[] tokens;
while ((tokens = testParser.parseNext()) != null) {
String id = tokens[0];
String query = tokens[1].replace("\"", "").trim();
String productTitle = tokens[2].replace("\"", "").trim();
String productDesc = tokens[3].replace("\"", "").trim();
// preprocessing
String cleanQuery = processTextByLucene(getTextFromRawData(query));
String cleanProductTitle = processTextByLucene(getTextFromRawData(productTitle));
String cleanProductDesc = processTextByLucene(getTextFromRawData(productDesc));
// replace compounds
for (String c : compounds) {
String tmp = c.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, c);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, c);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, c);
}
// replace small words generated from title
for (String s : smallWords) {
String tmp = s.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, s);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, s);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, s);
}
// replace all synonyms
cleanQuery = replaceSynonyms(cleanQuery);
cleanProductTitle = replaceSynonyms(cleanProductTitle);
cleanProductDesc = replaceSynonyms(cleanProductDesc);
Hashtable<String, Integer> qTokens = getTermFreqByLucene(
cleanQuery, true, true);
Hashtable<String, Integer> titleTokens = getTermFreqByLucene(
cleanProductTitle, true, true);
Hashtable<String, Integer> descTokens = getTermFreqByLucene(
cleanProductDesc, true, true);
Hashtable<String, Integer> matchedTermsInTitle = new Hashtable<String, Integer>();
Hashtable<String, Integer> matchedTermsInDesc = new Hashtable<String, Integer>();
int titleMatched = 0;
int descMatched = 0;
for (String q : qTokens.keySet()) {
if (titleTokens.containsKey(q)) {
if (!matchedTermsInTitle.containsKey(query))
matchedTermsInTitle.put(query, titleTokens.get(q));
else
matchedTermsInTitle.put(query,
matchedTermsInTitle.get(query)
+ titleTokens.get(q));
titleMatched++;
}
if (descTokens.containsKey(q)) {
if (!matchedTermsInDesc.containsKey(query))
matchedTermsInDesc.put(query, descTokens.get(q));
else
matchedTermsInDesc.put(
query,
matchedTermsInDesc.get(query)
+ descTokens.get(q));
descMatched++;
}
}
// qInTitle
double qInTitle = (double) titleMatched / qTokens.size();
// qInDesc
double qInDesc = (double) descMatched / qTokens.size();
String[] qTmp = cleanQuery.split("\\s");
// prefixMatch in title
int prefixMatchInTitle = 0;
String prefixQ = qTmp[0];
if (titleTokens.containsKey(prefixQ))
prefixMatchInTitle = 1;
// secondMatch in title
int secondMatchInTitle = 0;
if (qTmp.length >= 2) {
String secondQ = qTmp[1];
if (titleTokens.containsKey(secondQ))
secondMatchInTitle = 1;
}
// midMatch in title
int midMatchInTitle = 0;
for (int i = 1; i < qTmp.length - 1; i++) {
if (titleTokens.containsKey(qTmp[i]))
midMatchInTitle = 1;
}
// suffixMatch in title
int suffixMatchInTitle = 0;
String suffixQ = qTmp[qTmp.length - 1];
if (titleTokens.containsKey(suffixQ))
suffixMatchInTitle = 1;
resultStr.append("\"" + id + "\",\"" + cleanQuery + "\",\""
+ cleanProductTitle + "\",\"" + cleanProductDesc
+ "\",\"" + qInTitle + "\",\"" + qInDesc + "\",\""
+ prefixMatchInTitle + "\",\"" + secondMatchInTitle
+ "\",\"" + midMatchInTitle + "\",\""
+ suffixMatchInTitle + "\"");
resultStr.append(newLine);
if (resultStr.length() >= BUFFER_LENGTH) {
testOut.write(resultStr.toString());
testOut.flush();
resultStr.setLength(0);
}
count++;
}
System.out.println("Total test records: " + count);
} finally {
testIn.close();
testOut.write(resultStr.toString());
testOut.flush();
testOut.close();
resultStr.setLength(0);
}
System.out.flush();
}
public void run(String trainFile, String testFile, String outputTrain,
String outputTest, String compoundPath, String smallWordPath)
throws Exception {
System.setOut(new PrintStream(
new BufferedOutputStream(
new FileOutputStream(
"/home/markpeng/Share/Kaggle/Search Results Relevance/preprocess_notmatched_all_20150522.txt")),
true));
// System.setOut(new PrintStream(
// new BufferedOutputStream(
// new FileOutputStream(
// "/home/markpeng/Share/Kaggle/Search Results Relevance/preprocess_notmatched_train.txt")),
// true));
// Set<String> dictionary = readDictionary(dicPath);
List<String> compounds = readFile(compoundPath);
List<String> smallWords = readFile(smallWordPath);
NGramDistance similarityTool = new NGramDistance(2);
BufferedReader trainIn = new BufferedReader(new InputStreamReader(
new FileInputStream(trainFile), "UTF-8"));
BufferedReader testIn = new BufferedReader(new InputStreamReader(
new FileInputStream(testFile), "UTF-8"));
CsvParserSettings settings = new CsvParserSettings();
settings.setParseUnescapedQuotes(false);
settings.getFormat().setLineSeparator("\n");
settings.getFormat().setDelimiter(',');
settings.getFormat().setQuote('"');
settings.setHeaderExtractionEnabled(true);
settings.setEmptyValue("");
settings.setMaxCharsPerColumn(40960);
// Train Data
try {
// creates a CSV parser
CsvParser trainParser = new CsvParser(settings);
// call beginParsing to read records one by one, iterator-style.
trainParser.beginParsing(trainIn);
// for (String[] tokens : allRows) {
int matched = 0;
int count = 0;
String[] tokens;
while ((tokens = trainParser.parseNext()) != null) {
String id = tokens[0];
String query = tokens[1].replace("\"", "").trim();
String productTitle = tokens[2].replace("\"", "").trim();
String productDesc = tokens[3].replace("\"", "").trim();
int medianRelevance = Integer.parseInt(tokens[4]);
double relevance_variance = Double.parseDouble(tokens[5]);
// preprocessing
String cleanQuery = processTextByLucene(getTextFromRawData(query));
String cleanProductTitle = processTextByLucene(getTextFromRawData(productTitle));
String cleanProductDesc = processTextByLucene(getTextFromRawData(productDesc));
// replace compounds
for (String c : compounds) {
String tmp = c.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, c);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, c);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, c);
}
// replace small words generated from title
for (String s : smallWords) {
String tmp = s.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, s);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, s);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, s);
}
// replace all synonyms
cleanQuery = replaceSynonyms(cleanQuery);
cleanProductTitle = replaceSynonyms(cleanProductTitle);
cleanProductDesc = replaceSynonyms(cleanProductDesc);
Hashtable<String, Integer> qTokens = getTermFreqByLucene(
cleanQuery, true, true);
Hashtable<String, Integer> titleTokens = getTermFreqByLucene(
cleanProductTitle, true, true);
Hashtable<String, Integer> descTokens = getTermFreqByLucene(
cleanProductDesc, true, true);
Hashtable<String, Integer> matchedTermsInTitle = new Hashtable<String, Integer>();
Hashtable<String, Integer> matchedTermsInDesc = new Hashtable<String, Integer>();
int titleMatched = 0;
int descMatched = 0;
for (String q : qTokens.keySet()) {
if (titleTokens.containsKey(q)) {
if (!matchedTermsInTitle.containsKey(query))
matchedTermsInTitle.put(query, titleTokens.get(q));
else
matchedTermsInTitle.put(query,
matchedTermsInTitle.get(query)
+ titleTokens.get(q));
titleMatched++;
} else {
for (String t : titleTokens.keySet()) {
float sim = similarityTool.getDistance(q, t);
if (sim >= MIN_SIMILARITY) {
if (!matchedTermsInTitle.containsKey(t))
matchedTermsInTitle.put(t,
titleTokens.get(t));
else
matchedTermsInTitle.put(t,
matchedTermsInTitle.get(t)
+ titleTokens.get(t));
titleMatched++;
break;
}
}
}
if (descTokens.containsKey(q)) {
if (!matchedTermsInDesc.containsKey(query))
matchedTermsInDesc.put(query, descTokens.get(q));
else
matchedTermsInDesc.put(
query,
matchedTermsInDesc.get(query)
+ descTokens.get(q));
descMatched++;
} else {
for (String d : descTokens.keySet()) {
float sim = similarityTool.getDistance(q, d);
if (sim >= MIN_SIMILARITY) {
if (!matchedTermsInDesc.containsKey(d))
matchedTermsInDesc
.put(d, descTokens.get(d));
else
matchedTermsInDesc.put(d,
matchedTermsInDesc.get(d)
+ descTokens.get(d));
descMatched++;
break;
}
}
}
}
if (titleMatched > 0 || descMatched > 0) {
// System.out.println("[id=" + id + "]");
// System.out.println("query:" + cleanQuery);
// System.out.println("product_title:" + cleanProductTitle);
// System.out.println("product_description:"
// + cleanProductDesc);
// System.out.println("median_relevance:" +
// medianRelevance);
// System.out.println("relevance_variance:"
// + relevance_variance);
// System.out.println("matched query terms in title:"
// + matchedTermsInTitle.toString());
// System.out.println("matched query terms in description:"
// + matchedTermsInDesc.toString());
// System.out.println("\n");
// System.out.println();
matched++;
} else {
if (medianRelevance >= 3) {
System.out.println("[id=" + id + "]");
System.out.println("query:" + cleanQuery);
System.out
.println("product_title:" + cleanProductTitle);
System.out.println("product_description:"
+ cleanProductDesc);
System.out.println("median_relevance:"
+ medianRelevance);
System.out.println("relevance_variance:"
+ relevance_variance);
System.out.println("matched query terms in title:"
+ matchedTermsInTitle.toString());
System.out
.println("matched query terms in description:"
+ matchedTermsInDesc.toString());
System.out.println("\n");
// System.out.println();
}
}
count++;
}
System.out.println("Total train records: " + count);
System.out
.println("Total query-matched records in title or description: "
+ matched);
System.out
.println("Total not-matched records in title or description: "
+ (count - matched));
} finally {
trainIn.close();
}
// Test Data
try {
System.out
.println("\n\n
System.out.println("Test Data");
// creates a CSV parser
CsvParser testParser = new CsvParser(settings);
// call beginParsing to read records one by one, iterator-style.
testParser.beginParsing(testIn);
int matched = 0;
int count = 0;
String[] tokens;
while ((tokens = testParser.parseNext()) != null) {
String id = tokens[0];
String query = tokens[1].replace("\"", "").trim();
String productTitle = tokens[2].replace("\"", "").trim();
String productDesc = tokens[3].replace("\"", "").trim();
// preprocessing
String cleanQuery = processTextByLucene(getTextFromRawData(query));
String cleanProductTitle = processTextByLucene(getTextFromRawData(productTitle));
String cleanProductDesc = processTextByLucene(getTextFromRawData(productDesc));
// replace compounds
for (String c : compounds) {
String tmp = c.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, c);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, c);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, c);
}
// replace small words generated from title
for (String s : smallWords) {
String tmp = s.replace(" ", "");
if (cleanQuery.contains(tmp))
cleanQuery = cleanQuery.replace(tmp, s);
if (cleanProductTitle.contains(tmp))
cleanProductTitle = cleanProductTitle.replace(tmp, s);
if (cleanProductDesc.contains(tmp))
cleanProductDesc = cleanProductDesc.replace(tmp, s);
}
// replace all synonyms
cleanQuery = replaceSynonyms(cleanQuery);
cleanProductTitle = replaceSynonyms(cleanProductTitle);
cleanProductDesc = replaceSynonyms(cleanProductDesc);
Hashtable<String, Integer> qTokens = getTermFreqByLucene(
cleanQuery, true, true);
Hashtable<String, Integer> titleTokens = getTermFreqByLucene(
cleanProductTitle, true, true);
Hashtable<String, Integer> descTokens = getTermFreqByLucene(
cleanProductDesc, true, true);
Hashtable<String, Integer> matchedTermsInTitle = new Hashtable<String, Integer>();
Hashtable<String, Integer> matchedTermsInDesc = new Hashtable<String, Integer>();
int titleMatched = 0;
int descMatched = 0;
for (String q : qTokens.keySet()) {
if (titleTokens.containsKey(q)) {
if (!matchedTermsInTitle.containsKey(query))
matchedTermsInTitle.put(query, titleTokens.get(q));
else
matchedTermsInTitle.put(query,
matchedTermsInTitle.get(query)
+ titleTokens.get(q));
titleMatched++;
} else {
for (String t : titleTokens.keySet()) {
float sim = similarityTool.getDistance(q, t);
if (sim >= MIN_SIMILARITY) {
if (!matchedTermsInTitle.containsKey(t))
matchedTermsInTitle.put(t,
titleTokens.get(t));
else
matchedTermsInTitle.put(t,
matchedTermsInTitle.get(t)
+ titleTokens.get(t));
titleMatched++;
break;
}
}
}
if (descTokens.containsKey(q)) {
if (!matchedTermsInDesc.containsKey(query))
matchedTermsInDesc.put(query, descTokens.get(q));
else
matchedTermsInDesc.put(
query,
matchedTermsInDesc.get(query)
+ descTokens.get(q));
descMatched++;
} else {
for (String d : descTokens.keySet()) {
float sim = similarityTool.getDistance(q, d);
if (sim >= MIN_SIMILARITY) {
if (!matchedTermsInDesc.containsKey(d))
matchedTermsInDesc
.put(d, descTokens.get(d));
else
matchedTermsInDesc.put(d,
matchedTermsInDesc.get(d)
+ descTokens.get(d));
descMatched++;
break;
}
}
}
}
if (titleMatched > 0 || descMatched > 0) {
// System.out.println("[id=" + id + "]");
// System.out.println("query:" + cleanQuery);
// System.out.println("product_title:" + cleanProductTitle);
// System.out.println("product_description:"
// + cleanProductDesc);
// System.out.println("median_relevance:" +
// medianRelevance);
// System.out.println("relevance_variance:"
// + relevance_variance);
// System.out.println("matched query terms in title:"
// + matchedTermsInTitle.toString());
// System.out.println("matched query terms in description:"
// + matchedTermsInDesc.toString());
// System.out.println("\n");
// System.out.println();
matched++;
} else {
System.out.println("[id=" + id + "]");
System.out.println("query:" + cleanQuery);
System.out.println("product_title:" + cleanProductTitle);
System.out.println("product_description:"
+ cleanProductDesc);
System.out.println("matched query terms in title:"
+ matchedTermsInTitle.toString());
System.out.println("matched query terms in description:"
+ matchedTermsInDesc.toString());
System.out.println("\n");
// System.out.println();
}
count++;
}
System.out.println("Total test records: " + count);
System.out
.println("Total query-matched records in title or description: "
+ matched);
System.out
.println("Total not-matched records in title or description: "
+ (count - matched));
} finally {
testIn.close();
}
System.out.flush();
}
public String getTextFromRawData(String raw) {
String result = raw;
Document doc = Jsoup.parse(raw);
Element body = doc.body();
String plainText = body.text().trim();
if (plainText.length() > 2) {
// System.out.println(plainText);
result = plainText;
}
return result;
}
private Hashtable<String, Integer> getTermFreqByLucene(String text)
throws IOException {
return getTermFreqByLucene(text, true, false);
}
private Hashtable<String, Integer> getTermFreqByLucene(String text,
boolean english, boolean digits) throws IOException {
Hashtable<String, Integer> result = new Hashtable<String, Integer>();
Set stopWords = new StandardAnalyzer(Version.LUCENE_46)
.getStopwordSet();
TokenStream ts = new StandardTokenizer(Version.LUCENE_46,
new StringReader(text));
ts = new StopFilter(Version.LUCENE_46, ts, (CharArraySet) stopWords);
// ts = new PorterStemFilter(ts);
try {
CharTermAttribute termAtt = ts
.addAttribute(CharTermAttribute.class);
ts.reset();
int wordCount = 0;
while (ts.incrementToken()) {
if (termAtt.length() > 0) {
String word = termAtt.toString();
boolean valid = false;
if (english && !digits)
valid = isAllEnglish(word);
else if (!english && digits)
valid = isAllDigits(word);
else if (english && digits)
valid = isAllEnglishAndDigits(word);
if (valid) {
if (result.get(word) == null)
result.put(word, 1);
else {
result.put(word, result.get(word) + 1);
}
}
wordCount++;
}
}
} finally {
// Fixed error : close ts:TokenStream
ts.end();
ts.close();
}
return result;
}
private List<String> getTermsAsListByLucene(String text) throws IOException {
List<String> result = new ArrayList<String>();
Set stopWords = new StandardAnalyzer(Version.LUCENE_46)
.getStopwordSet();
TokenStream ts = new StandardTokenizer(Version.LUCENE_46,
new StringReader(text));
ts = new StopFilter(Version.LUCENE_46, ts, (CharArraySet) stopWords);
// ts = new PorterStemFilter(ts);
try {
CharTermAttribute termAtt = ts
.addAttribute(CharTermAttribute.class);
ts.reset();
int wordCount = 0;
while (ts.incrementToken()) {
if (termAtt.length() > 0) {
String word = termAtt.toString();
if (isAllEnglish(word)) {
if (!result.contains(word))
result.add(word);
}
wordCount++;
}
}
} finally {
// Fixed error : close ts:TokenStream
ts.end();
ts.close();
}
return result;
}
public String processTextByLucene(String text) throws IOException {
String result = text;
StringBuffer postText = new StringBuffer();
Set stopWords = new StandardAnalyzer(Version.LUCENE_46)
.getStopwordSet();
TokenStream ts = new StandardTokenizer(Version.LUCENE_46,
new StringReader(text));
ts = new StopFilter(Version.LUCENE_46, ts, (CharArraySet) stopWords);
int flags = WordDelimiterFilter.SPLIT_ON_NUMERICS
| WordDelimiterFilter.SPLIT_ON_CASE_CHANGE
| WordDelimiterFilter.GENERATE_NUMBER_PARTS
| WordDelimiterFilter.GENERATE_WORD_PARTS;
ts = new WordDelimiterFilter(ts, flags, null);
ts = new LowerCaseFilter(Version.LUCENE_46, ts);
// ts = new PorterStemFilter(ts);
// ts = new DictionaryCompoundWordTokenFilter(Version.LUCENE_46, ts,
// new CharArraySet(Version.LUCENE_46, dictionary, true), 6, 4,
// 10, false);
// less aggressive, better than PorterStemFilter!
ts = new KStemFilter(ts);
try {
CharTermAttribute termAtt = ts
.addAttribute(CharTermAttribute.class);
ts.reset();
int wordCount = 0;
while (ts.incrementToken()) {
if (termAtt.length() > 0) {
String word = termAtt.toString();
postText.append(word + " ");
// System.out.println(word);
wordCount++;
}
}
String finalText = postText.toString().trim().replace("'", "");
if (finalText.length() > 1)
result = finalText;
} finally {
// Fixed error : close ts:TokenStream
ts.end();
ts.close();
}
return result;
}
public boolean isAllEnglish(String text) {
boolean result = true;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (!Character.isAlphabetic(c) && c != '-') {
result = false;
break;
}
}
return result;
}
public boolean isAllDigits(String text) {
boolean result = true;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (!Character.isDigit(c)) {
result = false;
break;
}
}
return result;
}
public boolean isAllEnglishAndDigits(String text) {
boolean result = true;
String[] tokens = text.split("\\s");
for (String token : tokens) {
for (int i = 0; i < token.length(); i++) {
char c = token.charAt(i);
if (!Character.isAlphabetic(c) && c != '-'
&& !Character.isDigit(c)) {
result = false;
break;
}
}
}
return result;
}
public SpellChecker loadDictionary(String indexPath, String dicPath) {
SpellChecker spellChecker = null;
try {
File dir = new File(indexPath);
Directory directory = FSDirectory.open(dir);
spellChecker = new SpellChecker(directory);
PlainTextDictionary dictionary = new PlainTextDictionary(new File(
dicPath));
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_46,
analyzer);
spellChecker.indexDictionary(dictionary, config, false);
} catch (IOException e) {
e.printStackTrace();
}
return spellChecker;
}
public static void main(String[] args) throws Exception {
args = new String[6];
args[0] = "/home/markpeng/Share/Kaggle/Search Results Relevance/train.csv";
args[1] = "/home/markpeng/Share/Kaggle/Search Results Relevance/test.csv";
args[2] = "/home/markpeng/Share/Kaggle/Search Results Relevance/train_filterred_stem_compound_markpeng.csv";
args[3] = "/home/markpeng/Share/Kaggle/Search Results Relevance/test_filterred_stem_compound_markpeng.csv";
// args[2] =
// "/home/markpeng/Share/Kaggle/Search Results Relevance/train_filterred_markpeng.csv";
// args[3] =
// "/home/markpeng/Share/Kaggle/Search Results Relevance/test_filterred_markpeng.csv";
// args[4] =
// "/home/markpeng/Share/Kaggle/Search Results Relevance/JOrtho/dictionary_en_2015_05/IncludedWords.txt";
args[4] = "/home/markpeng/Share/Kaggle/Search Results Relevance/english-compound-words.txt";
args[5] = "/home/markpeng/Share/Kaggle/Search Results Relevance/small_words_in_title_20150519.txt";
if (args.length < 5) {
System.out
.println("Arguments: [train.csv] [test.csv] [output train] [output test] [compound path] [smallword path]");
return;
}
String trainFile = args[0];
String testFile = args[1];
// String[] featureFiles = args[2].split("\\|");
String outputTrain = args[2];
String outputTest = args[3];
String compoundPath = args[4];
String smallWordPath = args[5];
DatasetCleaner worker = new DatasetCleaner();
worker.generate(trainFile, testFile, outputTrain, outputTest,
compoundPath, smallWordPath);
// worker.clean(trainFile, testFile, outputTrain, outputTest,
// compoundPath);
// worker.run(trainFile, testFile, outputTrain, outputTest,
// compoundPath,
// smallWordPath);
// LevensteinDistance similarityTool = new LevensteinDistance();
// NGramDistance similarityTool = new NGramDistance(2);
// System.out.println(similarityTool.getDistance("bags", "bag"));
// System.out.println(similarityTool.getDistance("duffle", "duffel"));
// String testQ = "refrigir";
// String testP = "refriger";
// // String testQ = "fridge";
// // String testP = "Refrigerator";
// String indexPath =
// "/home/markpeng/Share/Kaggle/Search Results Relevance/spellCheckerIndex";
// String dicPath =
// "/home/markpeng/Share/Kaggle/Search Results Relevance/JOrtho/dictionary_en_2015_05/IncludedWords.txt";
// SpellChecker checker = worker.loadDictionary(indexPath, dicPath);
// String[] suggestions = checker.suggestSimilar(testQ, 5);
// checker.setAccuracy((float) 0.7);
// // best measure =>
// checker.setStringDistance(new JaroWinklerDistance());
// // checker.setStringDistance(new NGramDistance(7));
// // checker.setStringDistance(new LevensteinDistance());
// System.out.println("Minimum accurarcy: " + checker.getAccuracy());
// System.out.println(checker.getStringDistance().toString());
// System.out.println(checker.getStringDistance()
// .getDistance(testQ, testP));
// if (suggestions.length > 0) {
// System.out.println(testQ + " correction: "
// + Arrays.asList(suggestions));
// suggestions = checker.suggestSimilar(testP, 5);
// if (suggestions.length > 0) {
// System.out.println(testP + " correction: "
// + Arrays.asList(suggestions));
// WordBreakSpellChecker breakChecker = new WordBreakSpellChecker();
// breakChecker.suggestWordBreaks(term, maxSuggestions, ir, suggestMode,
// sortMethod)
}
} |
package marubinotto.piggydb.api;
import marubinotto.piggydb.model.auth.User;
import marubinotto.piggydb.service.DomainModelBeans;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import static spark.Spark.*;
import spark.*;
import spark.servlet.SparkApplication;
public class PiggydbApi implements SparkApplication {
private static Log log = LogFactory.getLog(PiggydbApi.class);
protected ApplicationContext applicationContext;
protected DomainModelBeans domain;
protected Session session;
protected User user;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.domain = new DomainModelBeans(this.applicationContext);
}
protected User autoLoginAsAnonymous() {
User user = this.domain.getAuthentication().authenticateAsAnonymous();
if (user == null) return null;
this.session.start(user, null);
log.debug("Anonymous session created");
return user;
}
@Override
public void init() {
before(new Filter() {
@Override
public void handle(Request request, Response response) {
session = new Session(
request.raw(),
response.raw(),
domain.getAuthentication().isEnableAnonymous());
user = session.getUser();
if (user == null) user = autoLoginAsAnonymous();
// TODO: check the session
}
});
get(new Route("/login") {
@Override
public Object handle(Request request, Response response) {
return "Hello World!";
}
});
}
} |
package me.unrealization.jeeves.bot;
import me.unrealization.jeeves.interfaces.BotModule;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import me.unrealization.jeeves.modules.Ccn;
import me.unrealization.jeeves.modules.Cron;
import me.unrealization.jeeves.modules.Edsm;
import me.unrealization.jeeves.modules.Internal;
import me.unrealization.jeeves.modules.ModLog;
import me.unrealization.jeeves.modules.ParadoxWing;
import me.unrealization.jeeves.modules.Roles;
import me.unrealization.jeeves.modules.UserLog;
import me.unrealization.jeeves.modules.Welcome;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.xml.sax.SAXException;
import discord4j.core.DiscordClient;
import discord4j.core.DiscordClientBuilder;
import discord4j.core.event.EventDispatcher;
import discord4j.core.event.domain.lifecycle.ReadyEvent;
import discord4j.core.object.entity.Channel;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.GuildChannel;
import discord4j.core.object.entity.Member;
import discord4j.core.object.entity.Role;
import discord4j.core.object.entity.User;
public class Jeeves
{
public static String version = null;
public static DiscordClient bot = null;
public static ClientConfig clientConfig = null;
public static ServerConfig serverConfig = null;
private static HashMap<String, BotModule> modules = null;
private static void loadModules()
{
Jeeves.modules = new HashMap< String, BotModule>();
Jeeves.modules.put("ccn", new Ccn());
try
{
Jeeves.modules.put("cron", new Cron());
}
catch (ParserConfigurationException | SAXException e)
{
Jeeves.debugException(e);
}
try
{
Jeeves.modules.put("edsm", new Edsm());
}
catch (ParserConfigurationException | SAXException e)
{
Jeeves.debugException(e);
}
Jeeves.modules.put("internal", new Internal());
Jeeves.modules.put("modLog", new ModLog());
Jeeves.modules.put("paradoxWing", new ParadoxWing());
Jeeves.modules.put("roles", new Roles());
Jeeves.modules.put("userLog", new UserLog());
Jeeves.modules.put("welcome", new Welcome());
}
public static BotModule getModule(String moduleName)
{
BotModule module = Jeeves.modules.get(moduleName);
return module;
}
public static String[] getModuleList()
{
Set<String> moduleSet = Jeeves.modules.keySet();
String[] moduleList = moduleSet.toArray(new String[moduleSet.size()]);
return moduleList;
}
public static void checkConfig(long serverId, HashMap<String, Object> defaultConfig) throws ParserConfigurationException, TransformerException
{
if (defaultConfig == null)
{
return;
}
boolean updated = false;
Set<String> keySet = defaultConfig.keySet();
String[] keyList = keySet.toArray(new String[keySet.size()]);
for (int keyIndex = 0; keyIndex < keyList.length; keyIndex++)
{
if (Jeeves.serverConfig.hasKey(serverId, keyList[keyIndex]) == false)
{
Jeeves.serverConfig.setValue(serverId, keyList[keyIndex], defaultConfig.get(keyList[keyIndex]));
updated = true;
}
}
if (updated == true)
{
Jeeves.serverConfig.saveConfig();
}
}
public static boolean debugException(Exception e)
{
String debugging = (String)Jeeves.clientConfig.getValue("debugging");
if (debugging.equals("1") == true)
{
e.printStackTrace();
return true;
}
return false;
}
public static List<String> listToStringList(List<?> list)
{
List<String> stringList = new ArrayList<String>();
for (int listIndex = 0; listIndex < list.size(); listIndex++)
{
Object item = list.get(listIndex);
if (item.getClass() != String.class)
{
continue;
}
String value = (String)item;
stringList.add(value);
}
return stringList;
}
public static GuildChannel findChannel(Guild server, String channelName)
{
List<GuildChannel> channelList = server.getChannels().collectList().block();
for (int channelIndex = 0; channelIndex < channelList.size(); channelIndex++)
{
GuildChannel channel = channelList.get(channelIndex);
if ((channel.getName().equals(channelName) == true) || (channel.getMention().equals(channelName) == true))
{
return channel;
}
}
return null;
}
public static Role findRole(Guild server, String roleName)
{
List<Role> roleList = server.getRoles().collectList().block();
for (int roleIndex = 0; roleIndex < roleList.size(); roleIndex++)
{
Role role = roleList.get(roleIndex);
if ((role.getName().equals(roleName) == true) || (role.getMention().equals(roleName) == true))
{
return role;
}
}
return null;
}
public static Member findUser(Guild server, String userName)
{
List<Member> userList = server.getMembers().collectList().block();
for (int userIndex = 0; userIndex < userList.size(); userIndex++)
{
Member user = userList.get(userIndex);
if ((user.getDisplayName().equals(userName)) || (user.getNickname().toString().equals(userName) == true) || (user.getMention().equals(userName) == true) || (user.getNicknameMention().equals(userName) == true))
{
return user;
}
}
return null;
}
public static boolean isIgnored(long serverId, Channel channel)
{
Object ignoredChannels = Jeeves.serverConfig.getValue(serverId, "ignoredChannels");
if (ignoredChannels.getClass() == String.class)
{
return false;
}
List<String> ignoredChannelList = Jeeves.listToStringList((List<?>)ignoredChannels);
return ignoredChannelList.contains(channel.getId().asString());
}
public static boolean isIgnored(long serverId, User user)
{
Object ignoredUsers = Jeeves.serverConfig.getValue(serverId, "ignoredUsers");
if (ignoredUsers.getClass() == String.class)
{
return false;
}
List<String> ignoredUserList = Jeeves.listToStringList((List<?>)ignoredUsers);
return ignoredUserList.contains(user.getId().asString());
}
public static boolean isIgnored(long serverId, Role role)
{
Object ignoredRoles = Jeeves.serverConfig.getValue(serverId, "ignoredRoles");
if (ignoredRoles.getClass() == String.class)
{
return false;
}
List<String> ignoredRoleList = Jeeves.listToStringList((List<?>)ignoredRoles);
return ignoredRoleList.contains(role.getId().asString());
}
public static boolean isDisabled(long serverId, BotModule module)
{
Long discordId = module.getDiscordId();
if ((discordId != null) && (discordId.equals(serverId) == false))
{
return true;
}
Object disabledModules = Jeeves.serverConfig.getValue(serverId, "disabledModules");
if (disabledModules.getClass() == String.class)
{
return false;
}
String moduleName = module.getClass().getSimpleName().toLowerCase();
List<String> disabledModuleList = Jeeves.listToStringList((List<?>)disabledModules);
return disabledModuleList.contains(moduleName);
}
public static String getUtcTime()
{
Instant now = Instant.now();
String timeString = now.toString();
Pattern regEx = Pattern.compile("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}:[\\d]{2}:[\\d]{2})\\.[\\d]{3}Z$");
Matcher regExMatcher = regEx.matcher(timeString);
if (regExMatcher.matches() == false)
{
return timeString;
}
String year = regExMatcher.group(1);
String month = regExMatcher.group(2);
String day = regExMatcher.group(3);
String time = regExMatcher.group(4);
timeString = year + "-" + month + "-" + day + " " + time;
return timeString;
}
public static String[] splitArguments(String argumentString)
{
String[] arguments = argumentString.split(":");
for (int index = 0; index < arguments.length; index++)
{
arguments[index] = arguments[index].trim();
}
return arguments;
}
private static class ShutdownHook extends Thread
{
@Override
public void run()
{
try
{
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.shutdown();
}
catch (SchedulerException e)
{
Jeeves.debugException(e);
}
if (Jeeves.bot.isConnected() == true)
{
Jeeves.bot.logout().block();
}
}
}
public static void main(String[] args)
{
Jeeves.version = Jeeves.class.getPackage().getImplementationVersion();
if (Jeeves.version == null)
{
Jeeves.version = "Testing";
}
try
{
Jeeves.clientConfig = new ClientConfig();
}
catch (ParserConfigurationException | SAXException | IOException e)
{
Jeeves.debugException(e);
return;
}
try
{
Jeeves.serverConfig = new ServerConfig();
}
catch (ParserConfigurationException | SAXException e)
{
Jeeves.debugException(e);
return;
}
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
Jeeves.loadModules();
Jeeves.bot = new DiscordClientBuilder((String)Jeeves.clientConfig.getValue("loginToken")).build();
EventDispatcher dispatcher = Jeeves.bot.getEventDispatcher();
dispatcher.on(ReadyEvent.class).subscribe(event -> new DiscordEventHandlers.ReadyEventListener().execute(event));
Jeeves.bot.login().block();
}
} |
package net.imglib2.meta.units;
import org.scijava.service.Service;
/**
* Service for defining units and making unit conversions.
*
* @author Barry DeZonia
*/
public interface UnitService extends Service {
/**
* Returns a value after conversion between two compatible types of units.
* Each unit can be a compound unit string. For instance "inch" or "kg*m/s" or
* "pounds/inch^2", "km/hour**2", etc. Returns the number of output unit
* values represented by the number of input values of input type. Returns
* Double.NaN if the unit types are incompatible.
*
* @param inputValue The double representing the number of input units.
* @param inputUnit The string representing the input unit.
* @param outputUnit The string representing the output unit.
* @return The value in output units after converting the inputValue from
* input units.
*/
public double value(double inputValue, String inputUnit, String outputUnit);
/**
* Return the last internal error message if any. Each time value() is called
* the internal message is initially set to null. When value() determines a
* desired unit conversion is invalid it returns Double.NaN and sets the
* internal failure message.
*/
public String failureMessage();
/**
* Defines a unit conversion that can be referred to via the value() method.
* Note that baseUnit is not necessarily a name. It could be a compound unit
* string like "m/s^2" etc. Imagine we define a unit called "fliggs" that is
* 14.2 m/s^2.
*
* @param unitName The name of the unit being defined e.g. "fliggs".
* @param baseUnit The unit the defined unit is based upon e.g. "m/s^2".
* @param scale The ratio of defined units to base units e.g. 14.2.
*/
public void defineUnit(String unitName, String baseUnit, double scale);
/**
* Defines a unit conversion that can be referred to via the value() method.
* Note that baseUnit is not necessarily a name. It could be a compound unit
* string like "m/s^2" etc. Imagine we define a unit called "fliggs" that is
* 14.2 m/s^2 offset by 3.3 from baseUnit. An example of an offset is the 32
* used in conversion between celsius and fahrenheit.
*
* @param unitName The name of the unit being defined e.g. "fliggs".
* @param baseUnit The unit the defined unit is based upon e.g. "m/s^2".
* @param scale The ratio of defined units to base units e.g. 14.2.
* @param offset The offset of defined units to base units e.g. 3.3.
*/
public void defineUnit(String unitName, String baseUnit, double scale,
double offset);
/**
* Defines a unit conversion that can be referred to via the value() method.
* Note that baseUnit is not necessarily a name. It could be a compound unit
* string like "m/s^2" etc. Imagine we define a unit called "fliggs" that has
* a nonlinear conversion from baseUnit. One supplies a {@link Calibrator}
* that handles conversion. The Calibrator allows any kind of conversion
* between units including nonlinear ones (i.e. can support log units).
*
* @param unitName The name of the unit being defined e.g. "fliggs".
* @param baseUnit The unit the defined unit is based upon e.g. "m/s^2".
* @param calibrator The Calibrator the maps between the two unit spaces.
*/
public void
defineUnit(String unitName, String baseUnit, Calibrator calibrator);
} |
package net.m4e.app.resources;
import org.jetbrains.annotations.NotNull;
import javax.json.bind.annotation.*;
/**
* @author boto
* Date of creation February 20, 2018
*/
public class DocumentInfo {
private String id;
private String name;
private String type;
private String resourceURL;
private String content;
private String eTag;
private String encoding;
public DocumentInfo() {
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getResourceURL() {
return resourceURL;
}
public String getContent() {
return content;
}
@JsonbProperty("eTag")
public String getETag() {
return eTag;
}
public String getEncoding() {
return encoding;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public void setResourceURL(String url) {
this.resourceURL = url;
}
public void setContent(String content) {
this.content = content;
}
@JsonbProperty("eTag")
public void setETag(String eTag) {
this.eTag = eTag;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
@JsonbTransient
public static DocumentInfo fromDocumentEntity(@NotNull DocumentEntity documentEntity) {
DocumentInfo documentInfo = new DocumentInfo();
documentInfo.setId("" + documentEntity.getId());
documentInfo.setName(documentEntity.getName());
documentInfo.setType(documentEntity.getType());
documentInfo.setResourceURL(documentEntity.getResourceURL());
documentInfo.setContent(new String(documentEntity.getContent()));
documentInfo.setETag(documentEntity.getETag());
documentInfo.setEncoding(documentEntity.getEncoding());
return documentInfo;
}
} |
package net.md_5.specialsource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.RemappingClassAdapter;
public class JarRemapper extends Remapper {
private static final int CLASS_LEN = ".class".length();
public final JarMapping jarMapping;
public JarRemapper(JarMapping jarMapping) {
this.jarMapping = jarMapping;
}
@Override
public String map(String typeName) {
return mapTypeName(typeName, jarMapping.packages, jarMapping.classes, typeName);
}
public static String mapTypeName(String typeName, LinkedHashMap<String, String> packageMap, Map<String, String> classMap, String defaultIfUnmapped) {
int index = typeName.indexOf('$');
String key = (index == -1) ? typeName : typeName.substring(0, index);
String mapped = mapClassName(key, packageMap, classMap);
return mapped != null ? mapped + (index == -1 ? "" : typeName.substring(index, typeName.length())) : defaultIfUnmapped;
}
/**
* Helper method to map a class name by package (prefix) or class (exact)
*/
private static String mapClassName(String className, LinkedHashMap<String, String> packageMap, Map<String, String> classMap) {
if (packageMap != null) {
Iterator<String> iter = packageMap.keySet().iterator();
while (iter.hasNext()) {
String oldPackage = iter.next();
if (className.startsWith(oldPackage)) {
String newPackage = packageMap.get(oldPackage);
return newPackage + className.substring(oldPackage.length());
}
}
}
return classMap != null ? classMap.get(className) : null;
}
@Override
public String mapFieldName(String owner, String name, String desc) {
String mapped = jarMapping.tryClimb(jarMapping.fields, NodeType.FIELD, owner, name);
return mapped == null ? name : mapped;
}
@Override
public String mapMethodName(String owner, String name, String desc) {
String mapped = jarMapping.tryClimb(jarMapping.methods, NodeType.METHOD, owner, name + " " + desc);
return mapped == null ? name : mapped;
}
/**
* Remap all the classes in a jar, writing a new jar to the target
*/
public void remapJar(Jar jar, File target) throws IOException {
JarOutputStream out = new JarOutputStream(new FileOutputStream(target));
try {
if (jar == null) {
return;
}
for (Enumeration<JarEntry> entr = jar.file.entries(); entr.hasMoreElements();) {
JarEntry entry = entr.nextElement();
InputStream is = jar.file.getInputStream(entry);
try {
String name = entry.getName();
byte[] data;
if (name.endsWith(".class")) {
name = name.substring(0, name.length() - CLASS_LEN);
data = remapClassFile(is);
String newName = map(name);
entry = new JarEntry(newName == null ? name : newName + ".class");
} else {
entry = new JarEntry(name);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int n;
byte[] b = new byte[1 << 15]; // Max class file size
while ((n = is.read(b, 0, b.length)) != -1) {
buffer.write(b, 0, n);
}
buffer.flush();
data = buffer.toByteArray();
}
entry.setTime(0);
out.putNextEntry(entry);
out.write(data);
} finally {
is.close();
}
}
} finally {
out.close();
}
}
/**
* Remap an individual class given an InputStream to its bytecode
*/
public byte[] remapClassFile(InputStream is) throws IOException {
ClassReader reader = new ClassReader(is);
ClassWriter wr = new ClassWriter(0);
RemappingClassAdapter mapper = new RemappingClassAdapter(wr, this);
reader.accept(mapper, ClassReader.EXPAND_FRAMES); // TODO: EXPAND_FRAMES necessary?
return wr.toByteArray();
}
public byte[] remapClassFile(byte[] in) {
ClassReader reader = new ClassReader(in);
ClassWriter wr = new ClassWriter(0);
RemappingClassAdapter mapper = new RemappingClassAdapter(wr, this);
reader.accept(mapper, ClassReader.EXPAND_FRAMES); // TODO: EXPAND_FRAMES necessary?
return wr.toByteArray();
}
} |
package nl.rutgerkok.blocklocker.impl;
import java.util.Collection;
import javax.annotation.Nullable;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import com.google.common.collect.ImmutableList;
/**
* Represents a single or double door. Used to find all blocks of a door, as
* well to open or close a door.
*
*/
public final class Door {
private static BlockFace getFaceToLeftDoor(Block bottomHalfDoorBlock) {
return getFaceToRightDoor(bottomHalfDoorBlock).getOppositeFace();
}
private static BlockFace getFaceToRightDoor(Block bottomHalfDoorBlock) {
@SuppressWarnings("deprecation")
byte data = bottomHalfDoorBlock.getData();
switch (data & 0x3) {
case 0:
return BlockFace.SOUTH;
case 1:
return BlockFace.WEST;
case 2:
return BlockFace.NORTH;
case 3:
return BlockFace.EAST;
default:
throw new AssertionError("Error: " + data);
}
}
private static boolean isHingeOnLeftSide(Block topHalfDoorBlock) {
@SuppressWarnings("deprecation")
byte data = topHalfDoorBlock.getData();
return (data & 0x1) == 0;
}
private static boolean isTopHalf(Block doorBlock) {
@SuppressWarnings("deprecation")
byte data = doorBlock.getData();
return (data & 0x8) != 0;
}
private final Material doorMaterial;
@Nullable
private final Block topLeftBlock;
@Nullable
private final Block topRightBlock;
@Nullable
private final Block bottomLeftBlock;
@Nullable
private final Block bottomRightBlock;
/**
* Creates a new door. The given block must be part of the door.
*
* @param doorBlock
* A block that is part of the door.
*/
public Door(Block doorBlock) {
doorMaterial = doorBlock.getType();
Block topBlock;
Block bottomBlock;
if (isTopHalf(doorBlock)) {
// Top half
topBlock = doorBlock;
bottomBlock = doorBlock.getRelative(BlockFace.DOWN);
} else {
// Bottom half
bottomBlock = doorBlock;
topBlock = doorBlock.getRelative(BlockFace.UP);
}
if (isHingeOnLeftSide(topBlock)) {
// Hinge on the left, there may be another door on the right
topLeftBlock = topBlock;
bottomLeftBlock = bottomBlock;
BlockFace faceToRightDoor = getFaceToRightDoor(bottomBlock);
topRightBlock = asDoorMaterialOrNull(topLeftBlock.getRelative(faceToRightDoor));
bottomRightBlock = asDoorMaterialOrNull(bottomLeftBlock.getRelative(faceToRightDoor));
} else {
// Hinge on the right, there may be another door on the left
topRightBlock = topBlock;
bottomRightBlock = bottomBlock;
BlockFace faceToLeftDoor = getFaceToLeftDoor(bottomBlock);
topLeftBlock = asDoorMaterialOrNull(topRightBlock.getRelative(faceToLeftDoor));
bottomLeftBlock = asDoorMaterialOrNull(bottomRightBlock.getRelative(faceToLeftDoor));
}
}
@Nullable
private Block asDoorMaterialOrNull(@Nullable Block block) {
if (block != null && block.getType() == doorMaterial) {
return block;
}
return null;
}
/**
* Gets a collection of all blocks where attached protection signs are used
* for this door.
*
* @return All blocks that can have protection signs attached.
*/
public Collection<Block> getBlocksForSigns() {
ImmutableList.Builder<Block> blocks = ImmutableList.builder();
if (bottomLeftBlock != null) {
blocks.add(bottomLeftBlock);
blocks.add(bottomLeftBlock.getRelative(BlockFace.DOWN));
}
if (bottomRightBlock != null) {
blocks.add(bottomRightBlock);
blocks.add(bottomRightBlock.getRelative(BlockFace.DOWN));
}
if (topLeftBlock != null) {
blocks.add(topLeftBlock);
blocks.add(topLeftBlock.getRelative(BlockFace.UP));
}
if (topRightBlock != null) {
blocks.add(topRightBlock);
blocks.add(topRightBlock.getRelative(BlockFace.UP));
}
return blocks.build();
}
/**
* Gets whether the door is currently open. The result is undefined if the
* door is half-open, half-closed.
*
* @return True if the door is currently open, false otherwise.
*/
@SuppressWarnings("deprecation")
public boolean isOpen() {
if (bottomRightBlock != null) {
return (bottomRightBlock.getData() & 0x4) != 0;
}
if (bottomLeftBlock != null) {
return (bottomLeftBlock.getData() & 0x4) != 0;
}
return false;
}
/**
* Opens or closes the door. If the door has been destroyed after creating
*
* @param open
* Whether the door must be opened (true) or closed (false).
*/
@SuppressWarnings("deprecation")
public void setOpen(boolean open) {
if (open) {
// Open door
if (asDoorMaterialOrNull(bottomLeftBlock) != null) {
bottomLeftBlock.setData((byte) (bottomLeftBlock.getData() | 0x4));
}
if (asDoorMaterialOrNull(bottomRightBlock) != null) {
bottomRightBlock.setData((byte) (bottomRightBlock.getData() | 0x4));
}
} else {
// Close door
if (asDoorMaterialOrNull(bottomLeftBlock) != null) {
bottomLeftBlock.setData((byte) (bottomLeftBlock.getData() & ~0x4));
}
if (asDoorMaterialOrNull(bottomRightBlock) != null) {
bottomRightBlock.setData((byte) (bottomRightBlock.getData() & ~0x4));
}
}
}
/**
* Closes the door if the door is open, opens the door if the door is
* closed. If parts of the door is opened, parts is closed then the whole
* door will be in one state after calling this method, but it is unknown in
* which state.
*/
public void toggleOpen() {
setOpen(!isOpen());
}
} |
package nl.topicus.jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;
public class CloudSpannerDriver implements Driver
{
static
{
try
{
java.sql.DriverManager.registerDriver(new CloudSpannerDriver());
}
catch (SQLException e)
{
}
}
static final int MAJOR_VERSION = 1;
static final int MINOR_VERSION = 0;
private static final String PROJECT_URL_PART = "Project=";
private static final String INSTANCE_URL_PART = "Instance=";
private static final String DATABASE_URL_PART = "Database=";
private static final String KEY_FILE_URL_PART = "PvtKeyPath=";
private static final String SIMULATE_PRODUCT_NAME = "SimulateProductName=";
/**
* Connects to a Google Cloud Spanner database.
*
* @param url
* Connection URL in the form
* jdbc:cloudspanner://localhost;Project
* =projectId;Instance=instanceId
* ;Database=databaseName;PvtKeyPath
* =path_to_key_file;SimulateProductName=product_name
* @param info
* not used
* @return A CloudSpannerConnection
* @throws SQLException
* if an error occurs while connecting to Google Cloud Spanner
*/
@Override
public Connection connect(String url, Properties info) throws SQLException
{
if (!acceptsURL(url))
return null;
String[] parts = url.split(":", 3);
String[] connectionParts = parts[2].split(";");
// String server = connectionParts[0];
String project = null;
String instance = null;
String database = null;
String keyFile = null;
String productName = null;
for (int i = 1; i < connectionParts.length; i++)
{
String conPart = connectionParts[i].replace(" ", "");
if (conPart.startsWith(PROJECT_URL_PART))
project = conPart.substring(PROJECT_URL_PART.length());
else if (conPart.startsWith(INSTANCE_URL_PART))
instance = conPart.substring(INSTANCE_URL_PART.length());
else if (conPart.startsWith(DATABASE_URL_PART))
database = conPart.substring(DATABASE_URL_PART.length());
else if (conPart.startsWith(KEY_FILE_URL_PART))
keyFile = conPart.substring(KEY_FILE_URL_PART.length());
else if (conPart.startsWith(SIMULATE_PRODUCT_NAME))
productName = conPart.substring(SIMULATE_PRODUCT_NAME.length());
else
throw new SQLException("Unknown URL parameter " + conPart);
}
CloudSpannerConnection connection = new CloudSpannerConnection(url, project, instance, database, keyFile);
connection.setSimulateProductName(productName);
return connection;
}
@Override
public boolean acceptsURL(String url) throws SQLException
{
return url.startsWith("jdbc:cloudspanner:");
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException
{
DriverPropertyInfo[] res = new DriverPropertyInfo[0];
return res;
}
@Override
public int getMajorVersion()
{
return MAJOR_VERSION;
}
@Override
public int getMinorVersion()
{
return MINOR_VERSION;
}
@Override
public boolean jdbcCompliant()
{
return true;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException
{
throw new SQLFeatureNotSupportedException("java.util.logging is not used");
}
} |
package org.hocate.http.server;
import java.util.HashMap;
import java.util.Map;
import org.hocate.http.message.Request;
import org.hocate.http.message.packet.Cookie;
public class HttpRequest extends Request {
private HttpSession session;
private String remoteAddres;
private int remotePort;
private String characterSet;
private Map<String, String> parameters;
protected HttpRequest(Request request){
super(request);
characterSet="UTF-8";
parameters = new HashMap<String, String>();
parseParameters();
}
/**
* Cookie Cookie
* @param name
* @return
*/
public Cookie getCookie(String name){
for(Cookie cookie : this.cookies()){
if(cookie.getName().equals(name)){
return cookie;
}
}
return null;
}
/**
* Session
* @return
*/
public HttpSession getSession() {
return session;
}
/**
* Session
* @param session
*/
protected void setSession(HttpSession session) {
this.session = session;
}
/**
* IP
* @return
*/
public String getRemoteAddres() {
return remoteAddres;
}
/**
* IP
* @param remoteAddres
*/
protected void setRemoteAddres(String remoteAddres) {
this.remoteAddres = remoteAddres;
}
/**
*
* @return
*/
public int getRemotePort() {
return remotePort;
}
/**
*
* @param port
*/
protected void setRemotePort(int port) {
this.remotePort = port;
}
/**
*
* @return
*/
public String getCharacterSet() {
return characterSet;
}
/**
*
* @param charset
*/
public void setCharacterSet(String charset) {
this.characterSet = charset;
}
/**
*
* @return
*/
public String getQueryString(){
return getQueryString(characterSet);
}
private void parseParameters() {
String[] parameterEquals = getQueryString().split("&");
for(String parameterEqual :parameterEquals){
int equalFlagPos = parameterEqual.indexOf("=");
if(equalFlagPos>0){
String name = parameterEqual.substring(0, equalFlagPos);
String value = parameterEqual.substring(equalFlagPos+1, parameterEqual.length());
parameters.put(name, value);
}else{
parameters.put(parameterEqual, null);
}
}
}
} |
package org.holmes.evaluator;
import java.util.Date;
import org.holmes.Evaluator;
import org.holmes.Joint;
import org.holmes.evaluator.support.Diff;
import org.holmes.evaluator.support.FutureNumber;
import org.holmes.evaluator.support.Interval;
/**
* An {@link Evaluator} for the {@link Date} type.
*
* @author diegossilveira
*/
public class DateEvaluator extends ObjectEvaluator<Date> {
private static final int ZERO = 0;
public DateEvaluator(Date target) {
super(target);
}
/**
* Applies a diff between the target and a past or future date.
*
* @param diff
* The diff configuration.
* @return {@link NumberEvaluator}
*/
public NumberEvaluator applying(final Diff diff) {
final FutureNumber futureNumber = new FutureNumber();
final NumberEvaluator evaluator = new NumberEvaluator(futureNumber);
setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
diff.setTarget(target);
futureNumber.wrap(diff.calculate());
return evaluator.evaluate();
}
});
evaluator.setJoint(getJoint());
return evaluator;
}
/**
* Ensures that the target is after than the argument date.
*
* @param date
* the date to compare the target to
* @return an instance of {@link Joint} class
*/
public Joint isAfterThan(final Date date) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return target != null && target.compareTo(date) > ZERO;
}
}).getJoint();
}
/**
* Ensures that the target is after than or equal to the argument date.
*
* @param date
* the date to compare the target to
* @return an instance of {@link Joint} class
*/
public Joint isAfterThanOrEqualTo(final Date date) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return target != null && target.compareTo(date) >= ZERO;
}
}).getJoint();
}
/**
* Ensures that the target is before than the argument date.
*
* @param date
* the date to compare the target to
* @return an instance of {@link Joint} class
*/
public Joint isBeforeThan(final Date date) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return target != null && target.compareTo(date) < ZERO;
}
}).getJoint();
}
/**
* Ensures that the target is before than or equal to the argument date.
*
* @param date
* the date to compare the target to
* @return an instance of {@link Joint} class
*/
public Joint isBeforeThanOrEqualTo(final Date date) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return target != null && target.compareTo(date) <= ZERO;
}
}).getJoint();
}
/**
* Ensures that the target belongs to the closed interval [leftBoundary,
* rightBoundary].
*
* @param leftBoundary
* the left boundary, inclusive.
* @param rightBoundary
* the right boundary, inclusive.
* @return an instance of {@link Joint} class
*/
public Joint belongsToInterval(final Date leftBoundary,
final Date rightBoundary) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return Interval.closedInterval(leftBoundary, rightBoundary)
.contains(target);
}
}).getJoint();
}
/**
* Ensures that the target belongs to the left-open interval (leftBoundary,
* rightBoundary].
*
* @param leftBoundary
* the left boundary, exclusive.
* @param rightBoundary
* the right boundary, inclusive.
* @return an instance of {@link Joint} class
*/
public Joint belongsToLeftOpenInterval(final Date leftBoundary,
final Date rightBoundary) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return Interval.leftOpenInterval(leftBoundary, rightBoundary)
.contains(target);
}
}).getJoint();
}
/**
* Ensures that the target belongs to the right-open interval [leftBoundary,
* rightBoundary).
*
* @param leftBoundary
* the left boundary, inclusive.
* @param rightBoundary
* the right boundary, exclusive.
* @return an instance of {@link Joint} class
*/
public Joint belongsToRightOpenInterval(final Date leftBoundary,
final Date rightBoundary) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return Interval.rightOpenInterval(leftBoundary, rightBoundary)
.contains(target);
}
}).getJoint();
}
/**
* Ensures that the target belongs to the open interval (leftBoundary,
* rightBoundary).
*
* @param leftBoundary
* the left boundary, exclusive.
* @param rightBoundary
* the right boundary, exclusive.
* @return an instance of {@link Joint} class
*/
public Joint belongsToOpenInterval(final Date leftBoundary,
final Date rightBoundary) {
return setEvaluation(new Evaluation<Date>() {
public boolean evaluate(Date target) {
return Interval.openInterval(leftBoundary, rightBoundary)
.contains(target);
}
}).getJoint();
}
} |
package org.jlib.core.string;
// TODO: create method String transform(String, StringTransformer...)
/**
* Utility class providing static methods for String operations and manipulations.
*
* @author Igor Akkerman
*/
public final class StringUtility {
/** property name of the system's line separator */
public static final String LINE_SEPARATOR_PROPERTYNAME = "line.separator";
/** the system's line separator */
public static final String LINE_SEPARATOR = System.getProperty(LINE_SEPARATOR_PROPERTYNAME);
/** no visible constructor */
private StringUtility() {}
/**
* Pads the specified String with the blank character at the back to the specified length.
*
* @param string
* String to pad
* @param length
* integer specifying the desired length of the String
* @return padded String. If {@code string.length() >= length} then {@code string} is returned.
*/
public static String pad(String string, int length) {
return pad(string, length, ' ', PaddingType.BACK);
}
/**
* Pads the specified String with the blank character using the specified PaddingType to the
* specified length.
*
* @param string
* String to pad
* @param length
* integer specifying the desired length of the String
* @param paddingType
* PaddingType specifying how the string should be padded
* @return padded String. If {@code string.length() >= length} then {@code string} is returned.
*/
public static String pad(String string, int length, PaddingType paddingType) {
return pad(string, length, ' ', paddingType);
}
/**
* Pads the specified String with the specified character using the specified PaddingType to the
* specified length.
*
* @param string
* String to pad
* @param length
* integer specifying the desired length of the String
* @param paddingCharacter
* character used for padding
* @param paddingType
* PaddingType specifying how the string should be padded
* @return padded String. If {@code string.length() >= length} then {@code string} is returned.
*/
public static String pad(String string, int length, char paddingCharacter, PaddingType paddingType) {
int halfLength;
int currentLength = string.length();
if (currentLength >= length)
return string;
StringBuilder stringBuilder = new StringBuilder(length);
// TODO: use StringTransformer strategies instead
switch (paddingType) {
case FRONT:
for (; currentLength < length; currentLength ++)
stringBuilder.append(paddingCharacter);
stringBuilder.append(string);
break;
case BACK:
stringBuilder.append(string);
for (; currentLength < length; currentLength ++)
stringBuilder.append(paddingCharacter);
break;
case FRONTBACK:
halfLength = (currentLength + length + 1) / 2;
for (; currentLength < halfLength; currentLength ++)
stringBuilder.append(paddingCharacter);
stringBuilder.append(string);
for (; currentLength < length; currentLength ++)
stringBuilder.append(paddingCharacter);
break;
case BACKFRONT:
halfLength = (currentLength + length) / 2;
for (; currentLength < halfLength; currentLength ++)
stringBuilder.append(paddingCharacter);
stringBuilder.append(string);
for (; currentLength < length; currentLength ++)
stringBuilder.append(paddingCharacter);
}
return stringBuilder.toString();
}
// FIXME: fix this method
// public static String wrapOnWhitespace(String string, int lineWidth) {
// int stringLength = string.length();
// if (stringLength <= lineWidth)
// return string;
// StringBuilder stringBuilder = new StringBuilder(stringLength << 1);
// try {
//// stringBuilder.append();
// int nextWhitespaceIndex;
// nextWhitespaceIndex = indexOfWhitespace(string, whitespaceIndex + 1, endIndex);
// FIXME: fix this method
// int nextLIne
// for (int whitespaceIndex = 0; whitespaceIndex < stringLength; whitespaceIndex ++) {
// newWhitespaceIndex = subStringUntilNextWhitespace(stringBuilder, string, whitespaceIndex, );
// if (newWhitespaceIndex != whitespaceIndex) {
// stringBuilder.append(LINE_SEPARATOR);
// whitespaceIndex = newWhitespaceIndex;
// return stringBuilder.toString();
// FIXME: fix this method
// private static int indexOfWhitespace(String string, int startIndex, int endIndex)
// throws NoWhitespaceCharacterException, NullPointerException, IndexOutOfBoundsException {
// for (int stringIndex = startIndex; stringIndex <= endIndex; stringIndex ++) {
// if (Character.isWhitespace(string.charAt(stringIndex)))
// return stringIndex;
// throw new NoWhitespaceCharacterException();
// FIXME: fix this method
// public int subStringUntilNextWhitespace(StringBuilder stringBuilder, String string, int startIndex,
// int maximumLength) {
// int overIndex = Math.min(string.length(), startIndex + maximumLength);
// char character;
// int stringIndex;
// for (stringIndex = startIndex; stringIndex < overIndex; stringIndex ++) {
// character = string.charAt(stringIndex);
// if (Character.isWhitespace(character))
// return stringIndex;
// stringBuilder.append(character);
// return stringIndex - 1;
// private interface State {
// public int go(StringBuilder stringBuilder, String string, int startIndex, int maximumLength);
// private class LineStart
// implements State {
// public int go(StringBuilder stringBuilder, String string, int startIndex, int maximumLength) {};
// private class LineMiddle
// implements State {
// private class dingsResult {
// private int lastReadCharacterIndex;
// private State nextState();
} |
package org.kohsuke.github;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum ReactionContent {
PLUS_ONE("+1"),
MINUS_ONE("-1"),
LAUGH("laugh"),
CONFUSED("confused"),
HEART("heart"),
HOORAY("hooray"),
ROCKET("rocket"),
EYES("eyes");
private final String content;
ReactionContent(String content) {
this.content = content;
}
/**
* Gets content.
*
* @return the content
*/
@JsonValue
public String getContent() {
return content;
}
/**
* For content reaction content.
*
* @param content
* the content
* @return the reaction content
*/
@JsonCreator
public static ReactionContent forContent(String content) {
for (ReactionContent c : ReactionContent.values()) {
if (c.getContent().equals(content))
return c;
}
return null;
}
} |
package org.lightmare.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.jpa.datasource.PoolConfig;
import org.lightmare.utils.ObjectUtils;
/**
* Easy way to retrieve configuration properties from configuration file
*
* @author levan
*
*/
public class Configuration implements Cloneable {
// cache for all configuration passed programmatically or read from file
private final Map<String, Object> config = new HashMap<String, Object>();
// path where stored adminitrator users
public static final String ADMIN_USERS_PATH_KEY = "adminUsersPath";
/**
* <a href="netty.io">Netty</a> server / client configuration properties for
* RPC calls
*/
public static final String IP_ADDRESS = "listening_ip";
public static final String PORT = "listening_port";
public static final String BOSS_POOL = "boss_pool_size";
public static final String WORKER_POOL = "worker_pool_size";
public static final String CONNECTION_TIMEOUT = "timeout";
// properties for datasource path and deployment path
public static final String DEMPLOYMENT_PATH_KEY = "deploymentpath";
public static final String DATA_SOURCE_PATH_KEY = "dspath";
private Set<DeploymentDirectory> deploymentPaths;
private Set<String> dataSourcePaths;
// runtime to get avaliable processors
private static final Runtime RUNTIME = Runtime.getRuntime();
/**
* Default properties
*/
public static final String ADMIN_USERS_PATH_DEF = "./config/admin/users.properties";
public static final String IP_ADDRESS_DEF = "0.0.0.0";
public static final String PORT_DEF = "1199";
public static final String BOSS_POOL_DEF = "1";
public static final int WORKER_POOL_DEF = 3;
public static final String CONNECTION_TIMEOUT_DEF = "1000";
public static final boolean SERVER_DEF = Boolean.TRUE;
public static final String DATA_SOURCE_PATH_DEF = "./ds";
public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>(
Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE)));
public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>(
Arrays.asList("./ds"));
/**
* Properties which version of server is running remote it requires server
* client RPC infrastructure or local (embeddable mode)
*/
private boolean remote;
private static boolean server = SERVER_DEF;
private boolean client;
private static final String CONFIG_FILE = "./config/config.properties";
// String prefixes for jndi names
public static final String JPA_NAME = "java:comp/env/";
public static final String EJB_NAME = "ejb:";
public static final int EJB_NAME_LENGTH = 4;
// Configuration keys properties for deployment
private static final String DEPLOY_CONFIG_KEY = "deployConfiguration";
private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities";
private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName";
private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath";
private static final String LIBRARY_PATH_KEY = "libraryPaths";
private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar";
private static final String SWAP_DATASOURCE_KEY = "swapDataSource";
private static final String SCAN_ARCHIVES_KEY = "scanArchives";
private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource";
private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties";
private static final String POOL_CONFIG_KEY = "poolConfig";
// Configuration properties for deployment
private boolean hotDeployment;
private boolean watchStatus;
private static String ADMIN_USERS_PATH;
private static final Logger LOG = Logger.getLogger(Configuration.class);
public Configuration() {
}
public void setDefaults() {
boolean contains = config.containsKey(IP_ADDRESS);
if (ObjectUtils.notTrue(contains)) {
config.put(IP_ADDRESS, IP_ADDRESS_DEF);
}
contains = config.containsKey(PORT);
if (ObjectUtils.notTrue(contains)) {
config.put(PORT, PORT_DEF);
}
contains = config.containsKey(BOSS_POOL);
if (ObjectUtils.notTrue(contains)) {
config.put(BOSS_POOL, BOSS_POOL_DEF);
}
contains = config.containsKey(WORKER_POOL);
if (ObjectUtils.notTrue(contains)) {
int workers = RUNTIME.availableProcessors() * WORKER_POOL_DEF;
String workerProperty = String.valueOf(workers);
config.put(WORKER_POOL, workerProperty);
}
contains = config.containsKey(CONNECTION_TIMEOUT);
if (ObjectUtils.notTrue(contains)) {
config.put(CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_DEF);
}
if (ObjectUtils.notTrue(hotDeployment)) {
watchStatus = Boolean.TRUE;
} else {
watchStatus = Boolean.FALSE;
}
if (deploymentPaths == null) {
deploymentPaths = DEPLOYMENT_PATHS_DEF;
}
}
public void configure() {
setDefaults();
}
public void configure(Map<String, Object> configuration) {
configure();
if (ObjectUtils.available(configuration)) {
config.putAll(configuration);
}
}
/**
* Gets value associated with particular key as {@link String} instance
*
* @param key
* @return {@link String}
*/
public String getStringValue(String key) {
Object value = config.get(key);
String textValue;
if (value == null) {
textValue = null;
} else {
textValue = value.toString();
}
return textValue;
}
/**
* Gets value associated with particular key as <code>int</code> instance
*
* @param key
* @return {@link String}
*/
public int getIntValue(String key) {
String value = getStringValue(key);
return Integer.parseInt(value);
}
/**
* Gets value associated with particular key as <code>long</code> instance
*
* @param key
* @return {@link String}
*/
public long getLongValue(String key) {
String value = getStringValue(key);
return Long.parseLong(value);
}
/**
* Gets value associated with particular key as <code>boolean</code>
* instance
*
* @param key
* @return {@link String}
*/
public boolean getBooleanValue(String key) {
String value = getStringValue(key);
return Boolean.parseBoolean(value);
}
public void putValue(String key, String value) {
config.put(key, value);
}
/**
* Loads configuration form file
*
* @throws IOException
*/
public void loadFromFile() throws IOException {
InputStream propertiesStream = null;
try {
File configFile = new File(CONFIG_FILE);
if (configFile.exists()) {
propertiesStream = new FileInputStream(configFile);
loadFromStream(propertiesStream);
} else {
configFile.mkdirs();
}
} catch (IOException ex) {
LOG.error("Could not open config file", ex);
} finally {
if (ObjectUtils.notNull(propertiesStream)) {
propertiesStream.close();
}
}
}
/**
* Loads configuration form file by passed file path
*
* @param configFilename
* @throws IOException
*/
public void loadFromFile(String configFilename) throws IOException {
InputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream(new File(configFilename));
loadFromStream(propertiesStream);
} catch (IOException ex) {
LOG.error("Could not open config file", ex);
} finally {
if (ObjectUtils.notNull(propertiesStream)) {
propertiesStream.close();
}
}
}
/**
* Loads configuration from file contained in classpath
*
* @param resourceName
* @param loader
*/
public void loadFromResource(String resourceName, ClassLoader loader) {
InputStream resourceStream = loader
.getResourceAsStream(new StringBuilder("META-INF/").append(
resourceName).toString());
if (resourceStream == null) {
LOG.error("Configuration resource doesn't exist");
return;
}
loadFromStream(resourceStream);
try {
resourceStream.close();
} catch (IOException ex) {
LOG.error("Could not load resource", ex);
}
}
/**
* Load {@link Configuration} in memory as {@link Map} of parameters
*
* @throws IOException
*/
public void loadFromStream(InputStream propertiesStream) {
try {
Properties props = new Properties();
props.load(propertiesStream);
for (String propertyName : props.stringPropertyNames()) {
config.put(propertyName, props.getProperty(propertyName));
}
propertiesStream.close();
} catch (IOException ex) {
LOG.error("Could not load configuration", ex);
}
}
public boolean isRemote() {
return remote;
}
public void setRemote(boolean remote) {
this.remote = remote;
}
public static boolean isServer() {
return server;
}
public static void setServer(boolean serverValue) {
server = serverValue;
}
public boolean isClient() {
return client;
}
public void setClient(boolean client) {
this.client = client;
}
/**
* Adds path for deployments file or directory
*
* @param path
* @param scan
*/
public void addDeploymentPath(String path, boolean scan) {
synchronized (Configuration.class) {
if (deploymentPaths == null) {
deploymentPaths = new HashSet<DeploymentDirectory>();
}
deploymentPaths.add(new DeploymentDirectory(path, scan));
}
}
/**
* Adds path for data source file
*
* @param path
*/
public void addDataSourcePath(String path) {
synchronized (Configuration.class) {
if (dataSourcePaths == null) {
dataSourcePaths = new HashSet<String>();
}
dataSourcePaths.add(path);
}
}
public Set<DeploymentDirectory> getDeploymentPath() {
return deploymentPaths;
}
public Set<String> getDataSourcePath() {
return dataSourcePaths;
}
@SuppressWarnings("unchecked")
private <K, V> Map<K, V> getAsMap(String key) {
Map<K, V> value = (Map<K, V>) config.get(key);
return value;
}
private <K, V> void setSubConfigValue(String key, K subKey, V value) {
Map<K, V> subConfig = getAsMap(key);
if (subConfig == null) {
subConfig = new HashMap<K, V>();
config.put(key, subConfig);
}
subConfig.put(subKey, value);
}
private <K, V> V getSubConfigValue(String key, K subKey, V defaultValue) {
V def;
Map<K, V> subConfig = getAsMap(key);
if (ObjectUtils.available(subConfig)) {
def = subConfig.get(subKey);
if (def == null) {
def = defaultValue;
}
} else {
def = defaultValue;
}
return def;
}
private <K, V> V getSubConfigValue(String key, String subKey) {
return getSubConfigValue(key, subKey, null);
}
public boolean isScanForEntities() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, SCAN_FOR_ENTITIES_KEY,
Boolean.FALSE);
}
public void setScanForEntities(boolean scanForEntities) {
setSubConfigValue(DEPLOY_CONFIG_KEY, SCAN_FOR_ENTITIES_KEY,
scanForEntities);
}
public String getAnnotatedUnitName() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, ANNOTATED_UNIT_NAME_KEY);
}
public void setAnnotatedUnitName(String annotatedUnitName) {
setSubConfigValue(DEPLOY_CONFIG_KEY, ANNOTATED_UNIT_NAME_KEY,
annotatedUnitName);
}
public String getPersXmlPath() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, PERSISTENCE_XML_PATH_KEY);
}
public void setPersXmlPath(String persXmlPath) {
setSubConfigValue(DEPLOY_CONFIG_KEY, PERSISTENCE_XML_PATH_KEY,
persXmlPath);
}
public String[] getLibraryPaths() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, LIBRARY_PATH_KEY);
}
public void setLibraryPaths(String[] libraryPaths) {
setSubConfigValue(DEPLOY_CONFIG_KEY, LIBRARY_PATH_KEY, libraryPaths);
}
public boolean isPersXmlFromJar() {
return getSubConfigValue(DEPLOY_CONFIG_KEY,
PERSISTENCE_XML_FROM_JAR_KEY, Boolean.FALSE);
}
public void setPersXmlFromJar(boolean persXmlFromJar) {
setSubConfigValue(DEPLOY_CONFIG_KEY, PERSISTENCE_XML_FROM_JAR_KEY,
persXmlFromJar);
}
public boolean isSwapDataSource() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, SWAP_DATASOURCE_KEY,
Boolean.FALSE);
}
public void setSwapDataSource(boolean swapDataSource) {
setSubConfigValue(DEPLOY_CONFIG_KEY, SWAP_DATASOURCE_KEY,
swapDataSource);
}
public boolean isScanArchives() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, SCAN_ARCHIVES_KEY,
Boolean.FALSE);
}
public void setScanArchives(boolean scanArchives) {
setSubConfigValue(DEPLOY_CONFIG_KEY, SCAN_ARCHIVES_KEY, scanArchives);
}
public boolean isPooledDataSource() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, POOLED_DATA_SOURCE_KEY,
Boolean.FALSE);
}
public void setPooledDataSource(boolean pooledDataSource) {
setSubConfigValue(DEPLOY_CONFIG_KEY, POOLED_DATA_SOURCE_KEY,
pooledDataSource);
}
public PoolConfig getPoolConfig() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, POOL_CONFIG_KEY);
}
public void setPoolConfig(PoolConfig poolConfig) {
setSubConfigValue(DEPLOY_CONFIG_KEY, POOL_CONFIG_KEY, poolConfig);
}
public static String getAdminUsersPath() {
return ADMIN_USERS_PATH;
}
public static void setAdminUsersPath(String aDMIN_USERS_PATH) {
ADMIN_USERS_PATH = aDMIN_USERS_PATH;
}
public Map<Object, Object> getPersistenceProperties() {
return getSubConfigValue(DEPLOY_CONFIG_KEY, PERSISTENCE_PROPERTIES_KEY);
}
public void setPersistenceProperties(
Map<Object, Object> persistenceProperties) {
setSubConfigValue(DEPLOY_CONFIG_KEY, PERSISTENCE_PROPERTIES_KEY,
persistenceProperties);
}
public boolean isHotDeployment() {
return hotDeployment;
}
public void setHotDeployment(boolean hotDeployment) {
this.hotDeployment = hotDeployment;
}
public boolean isWatchStatus() {
return watchStatus;
}
public void setWatchStatus(boolean watchStatus) {
this.watchStatus = watchStatus;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
} |
package org.lightmare.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.jpa.datasource.PoolConfig;
import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.yaml.snakeyaml.Yaml;
/**
* Easy way to retrieve configuration properties from configuration file
*
* @author levan
*
*/
public class Configuration implements Cloneable {
// Cache for all configuration passed from API or read from file
private final Map<Object, Object> config = new HashMap<Object, Object>();
// Instance of pool configuration
private static final PoolConfig POOL_CONFIG = new PoolConfig();
// Runtime to get available processors
private static final Runtime RUNTIME = Runtime.getRuntime();
// Resource path (META-INF)
private static final String META_INF_PATH = "META-INF/";
// Error messages
private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration";
private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file";
private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist";
private static final Logger LOG = Logger.getLogger(Configuration.class);
public Configuration() {
}
private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) {
if (from == null) {
from = config;
}
@SuppressWarnings("unchecked")
Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from);
return value;
}
private <K, V> Map<K, V> getAsMap(Object key) {
return getAsMap(key, null);
}
private <K, V> void setSubConfigValue(Object key, K subKey, V value) {
Map<K, V> subConfig = getAsMap(key);
if (subConfig == null) {
subConfig = new HashMap<K, V>();
config.put(key, subConfig);
}
subConfig.put(subKey, value);
}
private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) {
V def;
Map<K, V> subConfig = getAsMap(key);
if (ObjectUtils.available(subConfig)) {
def = subConfig.get(subKey);
if (def == null) {
def = defaultValue;
}
} else {
def = defaultValue;
}
return def;
}
private <K> boolean containsSubConfigKey(Object key, K subKey) {
Map<K, ?> subConfig = getAsMap(key);
boolean valid = ObjectUtils.available(subConfig);
if (valid) {
valid = subConfig.containsKey(subKey);
}
return valid;
}
private <K> boolean containsConfigKey(K key) {
return containsSubConfigKey(Config.DEPLOY_CONFIG.key, key);
}
private <K, V> V getSubConfigValue(Object key, K subKey) {
return getSubConfigValue(key, subKey, null);
}
private <K, V> void setConfigValue(K subKey, V value) {
setSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, value);
}
private <K, V> V getConfigValue(K subKey, V defaultValue) {
return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, defaultValue);
}
private <K, V> V getConfigValue(K subKey) {
return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey);
}
private <K, V> Map<K, V> getWithInitialization(Object key) {
Map<K, V> result = getConfigValue(key);
if (result == null) {
result = new HashMap<K, V>();
setConfigValue(key, result);
}
return result;
}
private <K, V> void setWithInitialization(Object key, K subKey, V value) {
Map<K, V> result = getWithInitialization(key);
result.put(subKey, value);
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration if value is null then returns passed default value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key, V defaultValue) {
V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key,
Config.PERSISTENCE_CONFIG.key, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key) {
return getPersistenceConfigValue(key, null);
}
/**
* Sets specific value for appropriated key in persistence configuration sub
* {@link Map} of configuration
*
* @param key
* @param value
*/
public void setPersistenceConfigValue(Object key, Object value) {
setWithInitialization(Config.PERSISTENCE_CONFIG.key, key, value);
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration if value is null then returns passed default
* value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key, V defaultValue) {
V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key,
Config.POOL_CONFIG.key, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key) {
V value = getPoolConfigValue(key, null);
return value;
}
/**
* Sets specific value for appropriated key in connection pool configuration
* sub {@link Map} of configuraion
*
* @param key
* @param value
*/
public void setPoolConfigValue(Object key, Object value) {
setWithInitialization(Config.POOL_CONFIG.key, key, value);
}
/**
* Configuration for {@link PoolConfig} instance
*/
private void configurePool() {
Map<Object, Object> poolProperties = getPoolConfigValue(Config.POOL_PROPERTIES.key);
if (ObjectUtils.available(poolProperties)) {
setPoolProperties(poolProperties);
}
String type = getPoolConfigValue(Config.POOL_PROVIDER_TYPE.key);
if (ObjectUtils.available(type)) {
getPoolConfig().setPoolProviderType(type);
}
String path = getPoolConfigValue(Config.POOL_PROPERTIES_PATH.key);
if (ObjectUtils.available(path)) {
setPoolPropertiesPath(path);
}
}
/**
* Configures server from properties and default values
*/
private void configureServer() {
// Sets default values to remote server configuration
boolean contains = containsConfigKey(Config.IP_ADDRESS.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value);
}
contains = containsConfigKey(Config.PORT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.PORT.key, Config.PORT.value);
}
contains = containsConfigKey(Config.BOSS_POOL.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value);
}
contains = containsConfigKey(Config.WORKER_POOL.key);
if (ObjectUtils.notTrue(contains)) {
int workers = RUNTIME.availableProcessors()
* (Integer) Config.WORKER_POOL.value;
String workerProperty = String.valueOf(workers);
setConfigValue(Config.WORKER_POOL.key, workerProperty);
}
contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.CONNECTION_TIMEOUT.key,
Config.CONNECTION_TIMEOUT.value);
}
}
/**
* Merges configuration with default properties
*/
@SuppressWarnings("unchecked")
public void configureDeployments() {
// Checks if application run in hot deployment mode
Boolean hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key);
if (hotDeployment == null) {
setConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE);
hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key);
}
// Check if application needs directory watch service
boolean watchStatus;
if (ObjectUtils.notTrue(hotDeployment)) {
watchStatus = Boolean.TRUE;
} else {
watchStatus = Boolean.FALSE;
}
setConfigValue(Config.WATCH_STATUS.key, watchStatus);
// Sets deployments directories
Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key);
if (deploymentPaths == null) {
deploymentPaths = (Set<DeploymentDirectory>) Config.DEMPLOYMENT_PATH.value;
setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths);
}
}
/**
* Configures server and connection pooling
*/
public void configure() {
configureServer();
configureDeployments();
configurePool();
}
/**
* Merges two {@link Map}s and if second {@link Map}'s value is instance of
* {@link Map} merges this value with first {@link Map}'s value recursively
*
* @param map1
* @param map2
* @return <code>{@link Map}<Object, Object></code>
*/
@SuppressWarnings("unchecked")
protected Map<Object, Object> deepMerge(Map<Object, Object> map1,
Map<Object, Object> map2) {
if (map1 == null) {
map1 = map2;
} else {
Set<Map.Entry<Object, Object>> entries2 = map2.entrySet();
Object key;
Map<Object, Object> value1;
Object value2;
Object mergedValue;
for (Map.Entry<Object, Object> entry2 : entries2) {
key = entry2.getKey();
value2 = entry2.getValue();
if (value2 instanceof Map) {
value1 = ObjectUtils.getAsMap(key, map1);
mergedValue = deepMerge(value1,
(Map<Object, Object>) value2);
} else {
mergedValue = value2;
}
if (ObjectUtils.notNull(mergedValue)) {
map1.put(key, mergedValue);
}
}
}
return map1;
}
/**
* Reads configuration from passed properties
*
* @param configuration
*/
public void configure(Map<Object, Object> configuration) {
deepMerge(config, configuration);
}
/**
* Reads configuration from passed file path
*
* @param configuration
*/
public void configure(String path) throws IOException {
File yamlFile = new File(path);
if (yamlFile.exists()) {
InputStream stream = new FileInputStream(yamlFile);
try {
Yaml yaml = new Yaml();
Object configuration = yaml.load(stream);
if (configuration instanceof Map) {
@SuppressWarnings("unchecked")
Map<Object, Object> innerConfig = (Map<Object, Object>) configuration;
configure(innerConfig);
}
} finally {
ObjectUtils.close(stream);
}
}
}
/**
* Gets value associated with particular key as {@link String} instance
*
* @param key
* @return {@link String}
*/
public String getStringValue(String key) {
Object value = config.get(key);
String textValue;
if (value == null) {
textValue = null;
} else {
textValue = value.toString();
}
return textValue;
}
/**
* Gets value associated with particular key as <code>int</code> instance
*
* @param key
* @return {@link String}
*/
public int getIntValue(String key) {
String value = getStringValue(key);
return Integer.parseInt(value);
}
/**
* Gets value associated with particular key as <code>long</code> instance
*
* @param key
* @return {@link String}
*/
public long getLongValue(String key) {
String value = getStringValue(key);
return Long.parseLong(value);
}
/**
* Gets value associated with particular key as <code>boolean</code>
* instance
*
* @param key
* @return {@link String}
*/
public boolean getBooleanValue(String key) {
String value = getStringValue(key);
return Boolean.parseBoolean(value);
}
public void putValue(String key, String value) {
config.put(key, value);
}
/**
* Load {@link Configuration} in memory as {@link Map} of parameters
*
* @throws IOException
*/
public void loadFromStream(InputStream propertiesStream) throws IOException {
try {
Properties props = new Properties();
props.load(propertiesStream);
for (String propertyName : props.stringPropertyNames()) {
config.put(propertyName, props.getProperty(propertyName));
}
} catch (IOException ex) {
LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex);
} finally {
ObjectUtils.close(propertiesStream);
}
}
/**
* Loads configuration form file
*
* @throws IOException
*/
public void loadFromFile() throws IOException {
InputStream propertiesStream = null;
String configFilePath = (String) Config.CONFIG_FILE.value;
try {
File configFile = new File(configFilePath);
if (configFile.exists()) {
propertiesStream = new FileInputStream(configFile);
loadFromStream(propertiesStream);
} else {
configFile.mkdirs();
}
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration form file by passed file path
*
* @param configFilename
* @throws IOException
*/
public void loadFromFile(String configFilename) throws IOException {
InputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream(new File(configFilename));
loadFromStream(propertiesStream);
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration from file contained in classpath
*
* @param resourceName
* @param loader
*/
public void loadFromResource(String resourceName, ClassLoader loader)
throws IOException {
InputStream resourceStream = loader.getResourceAsStream(StringUtils
.concat(META_INF_PATH, resourceName));
if (resourceStream == null) {
LOG.error(RESOURCE_NOT_EXISTS_ERROR);
} else {
loadFromStream(resourceStream);
}
}
public static String getAdminUsersPath() {
return (String) Config.ADMIN_USER_PATH.value;
}
public static void setAdminUsersPath(String adminUserPath) {
Config.ADMIN_USERS_PATH.value = adminUserPath;
}
public boolean isRemote() {
return (Boolean) Config.REMOTE.value;
}
public void setRemote(boolean remote) {
Config.REMOTE.value = remote;
}
public static boolean isServer() {
return (Boolean) Config.SERVER.value;
}
public static void setServer(boolean server) {
Config.SERVER.value = server;
}
public boolean isClient() {
return getConfigValue(Config.CLIENT.key, Boolean.FALSE);
}
public void setClient(boolean client) {
setConfigValue(Config.CLIENT.key, client);
}
/**
* Adds path for deployments file or directory
*
* @param path
* @param scan
*/
public void addDeploymentPath(String path, boolean scan) {
Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key);
if (deploymentPaths == null) {
deploymentPaths = new HashSet<DeploymentDirectory>();
setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths);
}
deploymentPaths.add(new DeploymentDirectory(path, scan));
}
/**
* Adds path for data source file
*
* @param path
*/
public void addDataSourcePath(String path) {
Set<String> dataSourcePaths = getConfigValue(Config.DATA_SOURCE_PATH.key);
if (dataSourcePaths == null) {
dataSourcePaths = new HashSet<String>();
setConfigValue(Config.DATA_SOURCE_PATH.key, dataSourcePaths);
}
dataSourcePaths.add(path);
}
public Set<DeploymentDirectory> getDeploymentPath() {
return getConfigValue(Config.DEMPLOYMENT_PATH.key);
}
public Set<String> getDataSourcePath() {
return getConfigValue(Config.DATA_SOURCE_PATH.key);
}
public String[] getLibraryPaths() {
return getConfigValue(Config.LIBRARY_PATH.key);
}
public void setLibraryPaths(String[] libraryPaths) {
setConfigValue(Config.LIBRARY_PATH.key, libraryPaths);
}
public boolean isHotDeployment() {
return getConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE);
}
public void setHotDeployment(boolean hotDeployment) {
setConfigValue(Config.HOT_DEPLOYMENT.key, hotDeployment);
}
public boolean isWatchStatus() {
return getConfigValue(Config.WATCH_STATUS.key, Boolean.FALSE);
}
public void setWatchStatus(boolean watchStatus) {
setConfigValue(Config.WATCH_STATUS.key, watchStatus);
}
/**
* Property for persistence configuration
*
* @return <code>boolean</code>
*/
public boolean isScanForEntities() {
return getPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key,
Boolean.FALSE);
}
public void setScanForEntities(boolean scanForEntities) {
setPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, scanForEntities);
}
public String getAnnotatedUnitName() {
return getPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key);
}
public void setAnnotatedUnitName(String annotatedUnitName) {
setPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key,
annotatedUnitName);
}
public String getPersXmlPath() {
return getPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key);
}
public void setPersXmlPath(String persXmlPath) {
setPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key, persXmlPath);
}
public boolean isPersXmlFromJar() {
return getPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key,
Boolean.FALSE);
}
public void setPersXmlFromJar(boolean persXmlFromJar) {
setPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key,
persXmlFromJar);
}
public boolean isSwapDataSource() {
return getPersistenceConfigValue(Config.SWAP_DATASOURCE.key,
Boolean.FALSE);
}
public void setSwapDataSource(boolean swapDataSource) {
setPersistenceConfigValue(Config.SWAP_DATASOURCE.key, swapDataSource);
}
public boolean isScanArchives() {
return getPersistenceConfigValue(Config.SCAN_ARCHIVES.key,
Boolean.FALSE);
}
public void setScanArchives(boolean scanArchives) {
setPersistenceConfigValue(Config.SCAN_ARCHIVES.key, scanArchives);
}
public boolean isPooledDataSource() {
return getPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key,
Boolean.FALSE);
}
public void setPooledDataSource(boolean pooledDataSource) {
setPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key,
pooledDataSource);
}
public Map<Object, Object> getPersistenceProperties() {
return getPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key);
}
public void setPersistenceProperties(
Map<Object, Object> persistenceProperties) {
setPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key,
persistenceProperties);
}
/**
* Property for connection pool configuration
*
* @return {@link PoolConfig}
*/
public static PoolConfig getPoolConfig() {
return POOL_CONFIG;
}
public void setDataSourcePooledType(boolean dsPooledType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPooledDataSource(dsPooledType);
}
public void setPoolPropertiesPath(String path) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolPath(path);
}
public void setPoolProperties(
Map<? extends Object, ? extends Object> properties) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().putAll(properties);
}
public void addPoolProperty(Object key, Object value) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().put(key, value);
}
public void setPoolProviderType(PoolProviderType poolProviderType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolProviderType(poolProviderType);
}
@Override
public Object clone() throws CloneNotSupportedException {
Configuration cloneConfig = (Configuration) super.clone();
cloneConfig.config.clear();
cloneConfig.configure(this.config);
return cloneConfig;
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.myrobotlab.framework.Registration;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.LeapData;
import org.myrobotlab.service.data.LeapHand;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.LeapDataListener;
import org.myrobotlab.service.interfaces.PinArrayListener;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
/**
* InMoovHand - The Hand sub service for the InMoov Robot. This service has 6
* servos controlled by an ServoController.
* thumb,index,majeure,ringFinger,pinky, and wrist
*
* There is also leap motion support.
*/
public class InMoov2Hand extends Service implements LeapDataListener, PinArrayListener {
public final static Logger log = LoggerFactory.getLogger(InMoov2Hand.class);
private static final long serialVersionUID = 1L;
/**
* peer services
*/
transient public LeapMotion leap;
transient public ServoController controller;
transient public ServoControl thumb;
transient public ServoControl index;
transient public ServoControl majeure;
transient public ServoControl ringFinger;
transient public ServoControl pinky;
transient public ServoControl wrist;
// The pins for the finger tip sensors
public String[] sensorPins = new String[] { "A0", "A1", "A2", "A3", "A4" };
// public int[] sensorLastValues = new int[] {0,0,0,0,0};
public boolean sensorsEnabled = false;
public int[] sensorThresholds = new int[] { 500, 500, 500, 500, 500 };
/**
* list of names of possible controllers
*/
public List<String> controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
public String controllerName;
boolean isAttached = false;
private int sensorPin;
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
InMoov i01 = (InMoov) Runtime.start("i01", "InMoov");
i01.startRightHand("COM15");
ServoController controller = (ServoController) Runtime.getService("i01.right");
// arduino.pinMode(13, ServoController.OUTPUT);
// arduino.digitalWrite(13, 1);
InMoov2Hand rightHand = (InMoov2Hand) Runtime.start("r01", "InMoov2Hand");// InMoovHand("r01");
Runtime.createAndStart("gui", "SwingGui");
Runtime.createAndStart("webgui", "WebGui");
// rightHand.connect("COM12"); TEST RECOVERY !!!
rightHand.close();
rightHand.open();
rightHand.openPinch();
rightHand.closePinch();
rightHand.rest();
/*
* SwingGui gui = new SwingGui("gui"); gui.startService();
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
public InMoov2Hand(String n, String id) {
super(n, id);
// FIXME - NO DIRECT REFERENCES ALL PUB SUB
}
public void startService() {
super.startService();
// FIXME - creatPeers()
startPeers();
// createPeers()
thumb.setPin(2);
index.setPin(3);
majeure.setPin(4);
ringFinger.setPin(5);
pinky.setPin(6);
wrist.setPin(7);
/*
* thumb.setSensorPin(A0); index.setSensorPin(A1); majeure.setSensorPin(A2);
* ringFinger.setSensorPin(A3); pinky.setSensorPin(A4);
*/
// TOOD: what are the initial velocities?
// Initial rest positions?
thumb.setRest(2.0);
thumb.setPosition(2.0);
index.setRest(2.0);
index.setPosition(2.0);
majeure.setRest(2.0);
majeure.setPosition(2.0);
ringFinger.setRest(2.0);
ringFinger.setPosition(2.0);
pinky.setRest(2.0);
pinky.setPosition(2.0);
wrist.setRest(90.0);
wrist.setPosition(90.0);
setSpeed(45.0, 45.0, 45.0, 45.0, 45.0, 45.0);
}
public void bird() {
moveTo(150.0, 180.0, 0.0, 180.0, 180.0, 90.0);
}
public void onRegistered(Registration s) {
refreshControllers();
broadcastState();
}
public List<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
return controllers;
}
// @Override
public ServoController getController() {
return controller;
}
public String getControllerName() {
String controlerName = null;
if (controller != null) {
controlerName = controller.getName();
}
return controlerName;
}
public boolean isAttached() {
if (controller != null) {
if (((Arduino) controller).getDeviceId((Attachable) this) != null) {
isAttached = true;
return true;
}
controller = null;
}
isAttached = false;
return false;
}
@Override
public void broadcastState() {
if (thumb != null)
thumb.broadcastState();
if (index != null)
index.broadcastState();
if (majeure != null)
majeure.broadcastState();
if (ringFinger != null)
ringFinger.broadcastState();
if (pinky != null)
pinky.broadcastState();
if (wrist != null)
wrist.broadcastState();
}
public void close() {
moveTo(130, 180, 180, 180, 180);
}
public void closePinch() {
moveTo(130, 140, 180, 180, 180);
}
public void releaseService() {
try {
disable();
releasePeers();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
public void count() {
one();
sleep(1);
two();
sleep(1);
three();
sleep(1);
four();
sleep(1);
five();
}
public void devilHorns() {
moveTo(150.0, 0.0, 180.0, 180.0, 0.0, 90.0);
}
public void disable() {
thumb.disable();
index.disable();
majeure.disable();
ringFinger.disable();
pinky.disable();
wrist.disable();
}
public boolean enable() {
thumb.enable();
index.enable();
majeure.enable();
ringFinger.enable();
pinky.enable();
wrist.enable();
return true;
}
@Deprecated
public void enableAutoDisable(Boolean param) {
setAutoDisable(param);
}
@Deprecated
public void enableAutoEnable(Boolean param) {
}
public void five() {
open();
}
public void four() {
moveTo(150.0, 0.0, 0.0, 0.0, 0.0, 90.0);
}
public void fullSpeed() {
thumb.fullSpeed();
index.fullSpeed();
majeure.fullSpeed();
ringFinger.fullSpeed();
pinky.fullSpeed();
wrist.fullSpeed();
}
/**
* this method returns the analog pins that the hand is listening to. The
* InMoovHand listens on analog pins A0-A4 for the finger tip sensors.
*
*/
@Override
public String[] getActivePins() {
// TODO Auto-generated method stub
// for the InMoov hand, we're just going to say A0 - A4 ... for now..
return sensorPins;
}
public long getLastActivityTime() {
long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime());
return lastActivityTime;
}
@Deprecated /* use LangUtils */
public String getScript(String inMoovServiceName) {
String side = getName().contains("left") ? "left" : "right";
return String.format(Locale.ENGLISH, "%s.moveHand(\"%s\",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, side, thumb.getCurrentInputPos(), index.getCurrentInputPos(),
majeure.getCurrentInputPos(), ringFinger.getCurrentInputPos(), pinky.getCurrentInputPos(), wrist.getCurrentInputPos());
}
public void hangTen() {
moveTo(0.0, 180.0, 180.0, 180.0, 0.0, 90.0);
}
public void map(double minX, double maxX, double minY, double maxY) {
if (thumb != null) {
thumb.map(minX, maxX, minY, maxY);
}
if (index != null) {
index.map(minX, maxX, minY, maxY);
}
if (majeure != null) {
majeure.map(minX, maxX, minY, maxY);
}
if (ringFinger != null) {
ringFinger.map(minX, maxX, minY, maxY);
}
if (pinky != null) {
pinky.map(minX, maxX, minY, maxY);
}
}
// TODO - waving thread fun
public void moveTo(double thumb, double index, double majeure, double ringFinger, double pinky) {
moveTo(thumb, index, majeure, ringFinger, pinky, null);
}
public void moveTo(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (log.isDebugEnabled()) {
log.debug("{}.moveTo {} {} {} {} {} {}", getName(), thumb, index, majeure, ringFinger, pinky, wrist);
}
if (thumb != null) {
this.thumb.moveTo(thumb);
}
if (index != null) {
this.index.moveTo(index);
}
if (majeure != null) {
this.majeure.moveTo(majeure);
}
if (ringFinger != null) {
this.ringFinger.moveTo(ringFinger);
}
if (pinky != null) {
this.pinky.moveTo(pinky);
}
if (wrist != null) {
this.wrist.moveTo(wrist);
}
}
public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky) {
moveToBlocking(thumb, index, majeure, ringFinger, pinky, null);
}
public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky, Double wrist) {
log.info("init {} moveToBlocking ", getName());
moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
waitTargetPos();
log.info("end {} moveToBlocking ", getName());
}
public void ok() {
moveTo(150.0, 180.0, 0.0, 0.0, 0.0, 90.0);
}
public void one() {
moveTo(150.0, 0.0, 180.0, 180.0, 180.0, 90.0);
}
public void attach(String controllerName, int sensorPin) throws Exception {
attach((ServoController) Runtime.getService(controllerName), sensorPin);
}
public void attach(String controllerName, String sensorPin) throws Exception {
attach((ServoController) Runtime.getService(controllerName), Integer.parseInt(sensorPin));
}
public void attach(ServoController controller, int sensorPin) {
try {
if (controller == null) {
error("setting null as controller");
return;
}
if (isAttached) {
log.info("Sensor already attached");
return;
}
this.sensorPin = sensorPin;
controller.attach(controller);
log.info("{} setController {}", getName(), controller.getName());
this.controller = controller;
controllerName = this.controller.getName();
isAttached = true;
broadcastState();
} catch (Exception e) {
error(e);
}
}
public void detach(ServoController controller) {
// let the controller you want to detach this device
if (controller != null) {
controller.detach(this);
}
// setting controller reference to null
this.controller = null;
isAttached = false;
refreshControllers();
broadcastState();
}
public void refresh() {
broadcastState();
}
@Override
public LeapData onLeapData(LeapData data) {
String side = getName().contains("left") ? "left" : "right";
if (!data.frame.isValid()) {
// TODO: we could return void here? not sure
// who wants the return value form this method.
log.info("Leap data frame not valid.");
return data;
}
LeapHand h;
if ("right".equalsIgnoreCase(side)) {
if (data.frame.hands().rightmost().isValid()) {
h = data.rightHand;
} else {
log.info("Right hand frame not valid.");
// return this hand isn't valid
return data;
}
} else if ("left".equalsIgnoreCase(side)) {
if (data.frame.hands().leftmost().isValid()) {
h = data.leftHand;
} else {
log.info("Left hand frame not valid.");
// return this frame isn't valid.
return data;
}
} else {
// side could be null?
log.info("Unknown Side or side not set on hand (Side = {})", side);
// we can default to the right side?
// TODO: come up with a better default or at least document this
// behavior.
if (data.frame.hands().rightmost().isValid()) {
h = data.rightHand;
} else {
log.info("Right(unknown) hand frame not valid.");
// return this hand isn't valid
return data;
}
}
return data;
}
// FIXME - use pub/sub attach to set this up without having this method !
@Override
public void onPinArray(PinData[] pindata) {
log.info("On Pin Data: {}", pindata.length);
if (!sensorsEnabled)
return;
// just return ? TOOD: maybe still track the last read values...
// TODO : change the interface to get a map of pin data, keyed off the name.
for (PinData pin : pindata) {
log.info("Pin Data: {}", pin);
// if (sensorPins.contains(pin.pin)) {
// // it's one of our finger pins.. let's operate on it.
// log.info("Pin Data : {} value {}", pin.pin, pin.value );
// if (sensorPins[0].equalsIgnoreCase(pin.pin)) {
// // thumb / A0
// // here we want to test the pin state.. and potentially take an action
// // based on the updated sensor pin state
// if (pin.value > sensorThresholds[0])
// thumb.stop();
// } else if (sensorPins[1].equalsIgnoreCase(pin.pin)) {
// // index / A1
// if (pin.value > sensorThresholds[1])
// index.stop();
// } else if (sensorPins[2].equalsIgnoreCase(pin.pin)) {
// // middle / A2
// if (pin.value > sensorThresholds[2])
// majeure.stop();
// } else if (sensorPins[3].equalsIgnoreCase(pin.pin)) {
// // ring / A3
// if (pin.value > sensorThresholds[3])
// ringFinger.stop();
// } else if (sensorPins[4].equalsIgnoreCase(pin.pin)) {
// // pinky / A4
// if (pin.value > sensorThresholds[4])
// pinky.stop();
}
}
public void open() {
rest();
}
public void openPinch() {
moveTo(0, 0, 180, 180, 180);
}
public void release() {
disable();
}
public void rest() {
thumb.rest();
index.rest();
majeure.rest();
ringFinger.rest();
pinky.rest();
wrist.rest();
}
@Override
public boolean save() {
super.save();
thumb.save();
index.save();
majeure.save();
ringFinger.save();
pinky.save();
wrist.save();
return true;
}
@Deprecated
public boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
String script = null;
try {
script = FileIO.toString(f.getAbsolutePath());
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
// evaluate the scripts in a blocking way.
boolean result = p.exec(script, true);
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
public void setAutoDisable(Boolean param) {
thumb.setAutoDisable(param);
index.setAutoDisable(param);
majeure.setAutoDisable(param);
ringFinger.setAutoDisable(param);
pinky.setAutoDisable(param);
wrist.setAutoDisable(param);
}
public void setPins(int thumbPin, int indexPin, int majeurePin, int ringFingerPin, int pinkyPin, int wristPin) {
log.info("setPins {} {} {} {} {} {}", thumbPin, indexPin, majeurePin, ringFingerPin, pinkyPin, wristPin);
thumb.setPin(thumbPin);
index.setPin(indexPin);
majeure.setPin(majeurePin);
ringFinger.setPin(ringFingerPin);
pinky.setPin(pinkyPin);
wrist.setPin(wristPin);
}
public void setSensorPins(int thumbSensorPin, int indexSensorPin, int majeureSensorPin, int ringFingerSensorPin, int pinkySensorPin) {
log.info("setSensorPins {} {} {} {} {}", thumbSensorPin, indexSensorPin, majeureSensorPin, ringFingerSensorPin, pinkySensorPin);
/*
* thumb.setSensorPin(thumbSensorPin); index.setSensorPin(indexSensorPin);
* majeure.setSensorPin(majeureSensorPin);
* ringFinger.setSensorPin(ringFingerSensorPin);
* pinky.setSensorPin(pinkySensorPin);
*/
}
public void setRest(double thumb, double index, double majeure, double ringFinger, double pinky) {
setRest(thumb, index, majeure, ringFinger, pinky, null);
}
public void setRest(double thumb, double index, double majeure, double ringFinger, double pinky, Double wrist) {
log.info("setRest {} {} {} {} {} {}", thumb, index, majeure, ringFinger, pinky, wrist);
this.thumb.setRest(thumb);
this.index.setRest(index);
this.majeure.setRest(majeure);
this.ringFinger.setRest(ringFinger);
this.pinky.setRest(pinky);
if (wrist != null) {
this.wrist.setRest(wrist);
}
}
/**
* @param pins
* Set the array of pins that should be listened to.
*
*/
public void setSensorPins(String[] pins) {
// TODO, this should probably be a sorted set.. and sensorPins itself should
// probably be a map to keep the mapping of pin to finger
this.sensorPins = pins;
}
public void setSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
this.thumb.setSpeed(thumb);
this.index.setSpeed(index);
this.majeure.setSpeed(majeure);
this.ringFinger.setSpeed(ringFinger);
this.pinky.setSpeed(pinky);
this.wrist.setSpeed(wrist);
}
@Deprecated
public void setVelocity(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
log.warn("setspeed deprecated please use setSpeed");
setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
// FIXME - if multiple systems are dependent on the ServoControl map and
// limits to be a certain value
// leap should change its output, and leave the map and limits here alone
// FIXME !!! - should not have LeapMotion defined here at all - it should be
// pub/sub !!!
public void startLeapTracking() throws Exception {
if (leap == null) {
leap = (LeapMotion) startPeer("leap");
}
this.index.map(90.0, 0.0, this.index.getMin(), this.index.getMax());
this.thumb.map(90.0, 50.0, this.thumb.getMin(), this.thumb.getMax());
this.majeure.map(90.0, 0.0, this.majeure.getMin(), this.majeure.getMax());
this.ringFinger.map(90.0, 0.0, this.ringFinger.getMin(), this.ringFinger.getMax());
this.pinky.map(90.0, 0.0, this.pinky.getMin(), this.pinky.getMax());
leap.addLeapDataListener(this);
leap.startTracking();
return;
}
public void stop() {
thumb.stop();
index.stop();
majeure.stop();
ringFinger.stop();
pinky.stop();
wrist.stop();
}
// FIXME !!! - should not have LeapMotion defined here at all - it should be
// pub/sub !!!
public void stopLeapTracking() {
leap.stopTracking();
this.index.map(this.index.getMin(), this.index.getMax(), this.index.getMin(), this.index.getMax());
this.thumb.map(this.thumb.getMin(), this.thumb.getMax(), this.thumb.getMin(), this.thumb.getMax());
this.majeure.map(this.majeure.getMin(), this.majeure.getMax(), this.majeure.getMin(), this.majeure.getMax());
this.ringFinger.map(this.ringFinger.getMin(), this.ringFinger.getMax(), this.ringFinger.getMin(), this.ringFinger.getMax());
this.pinky.map(this.pinky.getMin(), this.pinky.getMax(), this.pinky.getMin(), this.pinky.getMax());
this.rest();
return;
}
public void test() {
thumb.moveTo(thumb.getCurrentInputPos() + 2);
index.moveTo(index.getCurrentInputPos() + 2);
majeure.moveTo(majeure.getCurrentInputPos() + 2);
ringFinger.moveTo(ringFinger.getCurrentInputPos() + 2);
pinky.moveTo(pinky.getCurrentInputPos() + 2);
wrist.moveTo(wrist.getCurrentInputPos() + 2);
info("test completed");
}
public void three() {
moveTo(150.0, 0.0, 0.0, 0.0, 180.0, 90.0);
}
public void thumbsUp() {
moveTo(0.0, 180.0, 180.0, 180.0, 180.0, 90.0);
}
public void two() {
victory();
}
public void victory() {
moveTo(150.0, 0.0, 0.0, 180.0, 180.0, 90.0);
}
public void waitTargetPos() {
thumb.waitTargetPos();
index.waitTargetPos();
majeure.waitTargetPos();
ringFinger.waitTargetPos();
pinky.waitTargetPos();
wrist.waitTargetPos();
}
@Override
public void detach(String controllerName) {
// TODO Auto-generated method stub
}
@Override
public boolean isAttached(String name) {
return controller != null && name.equals(controller.getName());
}
@Override
public Set<String> getAttached() {
Set<String> ret = new HashSet<String>();
if (controller != null) {
ret.add(controller.getName());
}
return ret;
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.myrobotlab.framework.Registration;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.LeapData;
import org.myrobotlab.service.data.LeapHand;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.LeapDataListener;
import org.myrobotlab.service.interfaces.PinArrayListener;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
/**
* InMoovHand - The Hand sub service for the InMoov Robot. This service has 6
* servos controlled by an ServoController.
* thumb,index,majeure,ringFinger,pinky, and wrist
*
* There is also leap motion support.
*/
public class InMoov2Hand extends Service implements LeapDataListener, PinArrayListener {
public final static Logger log = LoggerFactory.getLogger(InMoov2Hand.class);
private static final long serialVersionUID = 1L;
/**
* peer services
*/
transient public LeapMotion leap;
transient public ServoController controller;
transient public ServoControl thumb;
transient public ServoControl index;
transient public ServoControl majeure;
transient public ServoControl ringFinger;
transient public ServoControl pinky;
transient public ServoControl wrist;
// The pins for the finger tip sensors
public String[] sensorPins = new String[] { "A0", "A1", "A2", "A3", "A4" };
// public int[] sensorLastValues = new int[] {0,0,0,0,0};
public boolean sensorsEnabled = false;
public int[] sensorThresholds = new int[] { 500, 500, 500, 500, 500 };
/**
* list of names of possible controllers
*/
public List<String> controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
public String controllerName;
boolean isAttached = false;
private int sensorPin;
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
InMoov i01 = (InMoov) Runtime.start("i01", "InMoov");
i01.startRightHand("COM15");
ServoController controller = (ServoController) Runtime.getService("i01.right");
// arduino.pinMode(13, ServoController.OUTPUT);
// arduino.digitalWrite(13, 1);
InMoov2Hand rightHand = (InMoov2Hand) Runtime.start("r01", "InMoov2Hand");// InMoovHand("r01");
Runtime.createAndStart("gui", "SwingGui");
Runtime.createAndStart("webgui", "WebGui");
// rightHand.connect("COM12"); TEST RECOVERY !!!
rightHand.close();
rightHand.open();
rightHand.openPinch();
rightHand.closePinch();
rightHand.rest();
/*
* SwingGui gui = new SwingGui("gui"); gui.startService();
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
public InMoov2Hand(String n, String id) {
super(n, id);
// FIXME - NO DIRECT REFERENCES ALL PUB SUB
// FIXME - creatPeers()
startPeers();
// createPeers()
thumb.setPin(2);
index.setPin(3);
majeure.setPin(4);
ringFinger.setPin(5);
pinky.setPin(6);
wrist.setPin(7);
/*
* thumb.setSensorPin(A0); index.setSensorPin(A1); majeure.setSensorPin(A2);
* ringFinger.setSensorPin(A3); pinky.setSensorPin(A4);
*/
// TOOD: what are the initial velocities?
// Initial rest positions?
thumb.setRest(2.0);
thumb.setPosition(2.0);
index.setRest(2.0);
index.setPosition(2.0);
majeure.setRest(2.0);
majeure.setPosition(2.0);
ringFinger.setRest(2.0);
ringFinger.setPosition(2.0);
pinky.setRest(2.0);
pinky.setPosition(2.0);
wrist.setRest(90.0);
wrist.setPosition(90.0);
setSpeed(45.0, 45.0, 45.0, 45.0, 45.0, 45.0);
}
public void bird() {
moveTo(150.0, 180.0, 0.0, 180.0, 180.0, 90.0);
}
public void onRegistered(Registration s) {
refreshControllers();
broadcastState();
}
public List<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
return controllers;
}
// @Override
public ServoController getController() {
return controller;
}
public String getControllerName() {
String controlerName = null;
if (controller != null) {
controlerName = controller.getName();
}
return controlerName;
}
public boolean isAttached() {
if (controller != null) {
if (((Arduino) controller).getDeviceId((Attachable) this) != null) {
isAttached = true;
return true;
}
controller = null;
}
isAttached = false;
return false;
}
@Override
public void broadcastState() {
thumb.broadcastState();
index.broadcastState();
majeure.broadcastState();
ringFinger.broadcastState();
pinky.broadcastState();
wrist.broadcastState();
}
public void close() {
moveTo(130, 180, 180, 180, 180);
}
public void closePinch() {
moveTo(130, 140, 180, 180, 180);
}
public void releaseService() {
try {
disable();
releasePeers();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
public void count() {
one();
sleep(1);
two();
sleep(1);
three();
sleep(1);
four();
sleep(1);
five();
}
public void devilHorns() {
moveTo(150.0, 0.0, 180.0, 180.0, 0.0, 90.0);
}
public void disable() {
thumb.disable();
index.disable();
majeure.disable();
ringFinger.disable();
pinky.disable();
wrist.disable();
}
public boolean enable() {
thumb.enable();
index.enable();
majeure.enable();
ringFinger.enable();
pinky.enable();
wrist.enable();
return true;
}
@Deprecated
public void enableAutoDisable(Boolean param) {
setAutoDisable(param);
}
@Deprecated
public void enableAutoEnable(Boolean param) {
}
public void five() {
open();
}
public void four() {
moveTo(150.0, 0.0, 0.0, 0.0, 0.0, 90.0);
}
public void fullSpeed() {
thumb.fullSpeed();
index.fullSpeed();
majeure.fullSpeed();
ringFinger.fullSpeed();
pinky.fullSpeed();
wrist.fullSpeed();
}
/**
* this method returns the analog pins that the hand is listening to. The
* InMoovHand listens on analog pins A0-A4 for the finger tip sensors.
*
*/
@Override
public String[] getActivePins() {
// TODO Auto-generated method stub
// for the InMoov hand, we're just going to say A0 - A4 ... for now..
return sensorPins;
}
public long getLastActivityTime() {
long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime());
return lastActivityTime;
}
@Deprecated /* use LangUtils */
public String getScript(String inMoovServiceName) {
String side = getName().contains("left") ? "left" : "right";
return String.format(Locale.ENGLISH, "%s.moveHand(\"%s\",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, side, thumb.getCurrentInputPos(), index.getCurrentInputPos(), majeure.getCurrentInputPos(),
ringFinger.getCurrentInputPos(), pinky.getCurrentInputPos(), wrist.getCurrentInputPos());
}
public void hangTen() {
moveTo(0.0, 180.0, 180.0, 180.0, 0.0, 90.0);
}
public void map(double minX, double maxX, double minY, double maxY) {
thumb.map(minX, maxX, minY, maxY);
index.map(minX, maxX, minY, maxY);
majeure.map(minX, maxX, minY, maxY);
ringFinger.map(minX, maxX, minY, maxY);
pinky.map(minX, maxX, minY, maxY);
}
// TODO - waving thread fun
public void moveTo(double thumb, double index, double majeure, double ringFinger, double pinky) {
moveTo(thumb, index, majeure, ringFinger, pinky, null);
}
public void moveTo(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (log.isDebugEnabled()) {
log.debug("{}.moveTo {} {} {} {} {} {}", getName(), thumb, index, majeure, ringFinger, pinky, wrist);
}
this.thumb.moveTo(thumb);
this.index.moveTo(index);
this.majeure.moveTo(majeure);
this.ringFinger.moveTo(ringFinger);
this.pinky.moveTo(pinky);
this.wrist.moveTo(wrist);
}
public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky) {
moveToBlocking(thumb, index, majeure, ringFinger, pinky, null);
}
public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky, Double wrist) {
log.info("init {} moveToBlocking ", getName());
moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
waitTargetPos();
log.info("end {} moveToBlocking ", getName());
}
public void ok() {
moveTo(150.0, 180.0, 0.0, 0.0, 0.0, 90.0);
}
public void one() {
moveTo(150.0, 0.0, 180.0, 180.0, 180.0, 90.0);
}
public void attach(String controllerName, int sensorPin) throws Exception {
attach((ServoController) Runtime.getService(controllerName), sensorPin);
}
public void attach(String controllerName, String sensorPin) throws Exception {
attach((ServoController) Runtime.getService(controllerName), Integer.parseInt(sensorPin));
}
public void attach(ServoController controller, int sensorPin) {
try {
if (controller == null) {
error("setting null as controller");
return;
}
if (isAttached) {
log.info("Sensor already attached");
return;
}
this.sensorPin = sensorPin;
controller.attach(controller);
log.info("{} setController {}", getName(), controller.getName());
this.controller = controller;
controllerName = this.controller.getName();
isAttached = true;
broadcastState();
} catch (Exception e) {
error(e);
}
}
public void detach(ServoController controller) {
// let the controller you want to detach this device
if (controller != null) {
controller.detach(this);
}
// setting controller reference to null
this.controller = null;
isAttached = false;
refreshControllers();
broadcastState();
}
public void refresh() {
broadcastState();
}
@Override
public LeapData onLeapData(LeapData data) {
String side = getName().contains("left") ? "left" : "right";
if (!data.frame.isValid()) {
// TODO: we could return void here? not sure
// who wants the return value form this method.
log.info("Leap data frame not valid.");
return data;
}
LeapHand h;
if ("right".equalsIgnoreCase(side)) {
if (data.frame.hands().rightmost().isValid()) {
h = data.rightHand;
} else {
log.info("Right hand frame not valid.");
// return this hand isn't valid
return data;
}
} else if ("left".equalsIgnoreCase(side)) {
if (data.frame.hands().leftmost().isValid()) {
h = data.leftHand;
} else {
log.info("Left hand frame not valid.");
// return this frame isn't valid.
return data;
}
} else {
// side could be null?
log.info("Unknown Side or side not set on hand (Side = {})", side);
// we can default to the right side?
// TODO: come up with a better default or at least document this
// behavior.
if (data.frame.hands().rightmost().isValid()) {
h = data.rightHand;
} else {
log.info("Right(unknown) hand frame not valid.");
// return this hand isn't valid
return data;
}
}
return data;
}
// FIXME - use pub/sub attach to set this up without having this method !
@Override
public void onPinArray(PinData[] pindata) {
log.info("On Pin Data: {}", pindata.length);
if (!sensorsEnabled)
return;
// just return ? TOOD: maybe still track the last read values...
// TODO : change the interface to get a map of pin data, keyed off the name.
for (PinData pin : pindata) {
log.info("Pin Data: {}", pin);
// if (sensorPins.contains(pin.pin)) {
// // it's one of our finger pins.. let's operate on it.
// log.info("Pin Data : {} value {}", pin.pin, pin.value );
// if (sensorPins[0].equalsIgnoreCase(pin.pin)) {
// // thumb / A0
// // here we want to test the pin state.. and potentially take an action
// // based on the updated sensor pin state
// if (pin.value > sensorThresholds[0])
// thumb.stop();
// } else if (sensorPins[1].equalsIgnoreCase(pin.pin)) {
// // index / A1
// if (pin.value > sensorThresholds[1])
// index.stop();
// } else if (sensorPins[2].equalsIgnoreCase(pin.pin)) {
// // middle / A2
// if (pin.value > sensorThresholds[2])
// majeure.stop();
// } else if (sensorPins[3].equalsIgnoreCase(pin.pin)) {
// // ring / A3
// if (pin.value > sensorThresholds[3])
// ringFinger.stop();
// } else if (sensorPins[4].equalsIgnoreCase(pin.pin)) {
// // pinky / A4
// if (pin.value > sensorThresholds[4])
// pinky.stop();
}
}
public void open() {
rest();
}
public void openPinch() {
moveTo(0, 0, 180, 180, 180);
}
public void release() {
disable();
}
public void rest() {
thumb.rest();
index.rest();
majeure.rest();
ringFinger.rest();
pinky.rest();
wrist.rest();
}
@Override
public boolean save() {
super.save();
thumb.save();
index.save();
majeure.save();
ringFinger.save();
pinky.save();
wrist.save();
return true;
}
@Deprecated
public boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
String script = null;
try {
script = FileIO.toString(f.getAbsolutePath());
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
// evaluate the scripts in a blocking way.
boolean result = p.exec(script, true);
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
public void speakBlocking(String text) {
if (speech != null) {
speech.speak(text);
}
}
public void setAutoDisable(Boolean param) {
thumb.setAutoDisable(param);
index.setAutoDisable(param);
majeure.setAutoDisable(param);
ringFinger.setAutoDisable(param);
pinky.setAutoDisable(param);
wrist.setAutoDisable(param);
}
public void setPins(int thumbPin, int indexPin, int majeurePin, int ringFingerPin, int pinkyPin, int wristPin) {
log.info("setPins {} {} {} {} {} {}", thumbPin, indexPin, majeurePin, ringFingerPin, pinkyPin, wristPin);
thumb.setPin(thumbPin);
index.setPin(indexPin);
majeure.setPin(majeurePin);
ringFinger.setPin(ringFingerPin);
pinky.setPin(pinkyPin);
wrist.setPin(wristPin);
}
public void setSensorPins(int thumbSensorPin, int indexSensorPin, int majeureSensorPin, int ringFingerSensorPin, int pinkySensorPin) {
log.info("setSensorPins {} {} {} {} {}", thumbSensorPin, indexSensorPin, majeureSensorPin, ringFingerSensorPin, pinkySensorPin);
/*
* thumb.setSensorPin(thumbSensorPin); index.setSensorPin(indexSensorPin);
* majeure.setSensorPin(majeureSensorPin);
* ringFinger.setSensorPin(ringFingerSensorPin);
* pinky.setSensorPin(pinkySensorPin);
*/
}
public void setRest(double thumb, double index, double majeure, double ringFinger, double pinky) {
setRest(thumb, index, majeure, ringFinger, pinky, null);
}
public void setRest(double thumb, double index, double majeure, double ringFinger, double pinky, Double wrist) {
log.info("setRest {} {} {} {} {} {}", thumb, index, majeure, ringFinger, pinky, wrist);
this.thumb.setRest(thumb);
this.index.setRest(index);
this.majeure.setRest(majeure);
this.ringFinger.setRest(ringFinger);
this.pinky.setRest(pinky);
if (wrist != null) {
this.wrist.setRest(wrist);
}
}
/**
* Set the array of pins that should be listened to.
*
* @param pins
*/
public void setSensorPins(String[] pins) {
// TODO, this should probably be a sorted set.. and sensorPins itself should
// probably be a map to keep the mapping of pin to finger
this.sensorPins = pins;
}
public void setSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
this.thumb.setSpeed(thumb);
this.index.setSpeed(index);
this.majeure.setSpeed(majeure);
this.ringFinger.setSpeed(ringFinger);
this.pinky.setSpeed(pinky);
this.wrist.setSpeed(wrist);
}
@Deprecated
public void setVelocity(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
log.warn("setspeed deprecated please use setSpeed");
setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
// FIXME - if multiple systems are dependent on the ServoControl map and
// limits to be a certain value
// leap should change its output, and leave the map and limits here alone
// FIXME !!! - should not have LeapMotion defined here at all - it should be
// pub/sub !!!
public void startLeapTracking() throws Exception {
if (leap == null) {
leap = (LeapMotion) startPeer("leap");
}
this.index.map(90.0, 0.0, this.index.getMin(), this.index.getMax());
this.thumb.map(90.0, 50.0, this.thumb.getMin(), this.thumb.getMax());
this.majeure.map(90.0, 0.0, this.majeure.getMin(), this.majeure.getMax());
this.ringFinger.map(90.0, 0.0, this.ringFinger.getMin(), this.ringFinger.getMax());
this.pinky.map(90.0, 0.0, this.pinky.getMin(), this.pinky.getMax());
leap.addLeapDataListener(this);
leap.startTracking();
return;
}
public void stop() {
thumb.stop();
index.stop();
majeure.stop();
ringFinger.stop();
pinky.stop();
wrist.stop();
}
// FIXME !!! - should not have LeapMotion defined here at all - it should be
// pub/sub !!!
public void stopLeapTracking() {
leap.stopTracking();
this.index.map(this.index.getMin(), this.index.getMax(), this.index.getMin(), this.index.getMax());
this.thumb.map(this.thumb.getMin(), this.thumb.getMax(), this.thumb.getMin(), this.thumb.getMax());
this.majeure.map(this.majeure.getMin(), this.majeure.getMax(), this.majeure.getMin(), this.majeure.getMax());
this.ringFinger.map(this.ringFinger.getMin(), this.ringFinger.getMax(), this.ringFinger.getMin(), this.ringFinger.getMax());
this.pinky.map(this.pinky.getMin(), this.pinky.getMax(), this.pinky.getMin(), this.pinky.getMax());
this.rest();
return;
}
public void test() {
thumb.moveTo(thumb.getCurrentInputPos() + 2);
index.moveTo(index.getCurrentInputPos() + 2);
majeure.moveTo(majeure.getCurrentInputPos() + 2);
ringFinger.moveTo(ringFinger.getCurrentInputPos() + 2);
pinky.moveTo(pinky.getCurrentInputPos() + 2);
wrist.moveTo(wrist.getCurrentInputPos() + 2);
info("test completed");
}
public void three() {
moveTo(150.0, 0.0, 0.0, 0.0, 180.0, 90.0);
}
public void thumbsUp() {
moveTo(0.0, 180.0, 180.0, 180.0, 180.0, 90.0);
}
public void two() {
victory();
}
public void victory() {
moveTo(150.0, 0.0, 0.0, 180.0, 180.0, 90.0);
}
public void waitTargetPos() {
thumb.waitTargetPos();
index.waitTargetPos();
majeure.waitTargetPos();
ringFinger.waitTargetPos();
pinky.waitTargetPos();
wrist.waitTargetPos();
}
@Override
public void detach(String controllerName) {
// TODO Auto-generated method stub
}
@Override
public boolean isAttached(String name) {
return controller != null && name.equals(controller.getName());
}
@Override
public Set<String> getAttached() {
Set<String> ret = new HashSet<String>();
if (controller != null) {
ret.add(controller.getName());
}
return ret;
}
} |
package org.nanopub;
import static org.nanopub.Nanopub.HAS_ASSERTION_URI;
import static org.nanopub.Nanopub.HAS_PROVENANCE_URI;
import static org.nanopub.Nanopub.HAS_PUBINFO_URI;
import static org.nanopub.Nanopub.SUB_GRAPH_OF;
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.HashMap;
import java.util.List;
import java.util.Map;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.helpers.RDFHandlerBase;
/**
* Handles files or streams with a sequence of nanopubs.
*
* @author Tobias Kuhn
*/
public class MultiNanopubRdfHandler extends RDFHandlerBase {
public static void process(RDFFormat format, InputStream in, NanopubHandler npHandler)
throws IOException, RDFParseException, RDFHandlerException {
RDFParser p = NanopubUtils.getParser(format);
p.setRDFHandler(new MultiNanopubRdfHandler(npHandler));
try {
p.parse(in, "");
} finally {
in.close();
}
}
public static void process(RDFFormat format, File file, NanopubHandler npHandler)
throws IOException, RDFParseException, RDFHandlerException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
process(format, in, npHandler);
}
private NanopubHandler npHandler;
private URI headUri = null;
private boolean headComplete = false;
private Map<URI,Boolean> graphs = new HashMap<>();
private List<Statement> statements = new ArrayList<>();
private List<String> nsPrefixes = new ArrayList<>();
private Map<String,String> ns = new HashMap<>();
private List<String> newNsPrefixes = new ArrayList<>();
private List<String> newNs = new ArrayList<>();
public MultiNanopubRdfHandler(NanopubHandler npHandler) {
this.npHandler = npHandler;
}
@Override
public void handleStatement(Statement st) throws RDFHandlerException {
if (!headComplete) {
if (headUri == null) {
headUri = (URI) st.getContext();
graphs.put(headUri, true);
}
if (headUri.equals(st.getContext())) {
URI p = st.getPredicate();
if (p.equals(HAS_ASSERTION_URI) || p.equals(HAS_PROVENANCE_URI) || p.equals(HAS_PUBINFO_URI)) {
graphs.put((URI) st.getObject(), true);
} else if (p.equals(SUB_GRAPH_OF)) {
graphs.put((URI) st.getSubject(), true);
}
} else {
headComplete = true;
}
}
if (headComplete && !graphs.containsKey(st.getContext())) {
finishNanopub();
handleStatement(st);
} else {
addNamespaces();
statements.add(st);
}
}
@Override
public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
newNs.add(uri);
newNsPrefixes.add(prefix);
}
public void addNamespaces() throws RDFHandlerException {
for (int i = 0 ; i < newNs.size() ; i++) {
String prefix = newNsPrefixes.get(i);
String nsUri = newNs.get(i);
nsPrefixes.remove(prefix);
nsPrefixes.add(prefix);
ns.put(prefix, nsUri);
}
newNs.clear();
newNsPrefixes.clear();
}
@Override
public void endRDF() throws RDFHandlerException {
finishNanopub();
}
private void finishNanopub() {
try {
npHandler.handleNanopub(new NanopubImpl(statements, nsPrefixes, ns));
} catch (MalformedNanopubException ex) {
throw new RuntimeException(ex);
}
headUri = null;
headComplete = false;
graphs.clear();
statements.clear();
}
public interface NanopubHandler {
public void handleNanopub(Nanopub np);
}
} |
package org.rembx.jeeshop.catalog;
import java.util.Date;
import java.util.List;
public class Category {
private Integer id;
private String name;
private String description;
private List<Category> childCategories;
private List<Product> childProducts;
private Date startDate;
private Date endDate;
private Boolean disabled;
private Promotion promotion;
} |
package rest.aplicacion;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import rest.dominio.entidades.JsonArrayDTO;
import rest.dominio.entidades.Profesor;
import rest.dominio.entidades.SeccionParking;
import rest.dominio.modelo.ConexionBBDD;
import rest.dominio.modelo.RepositorioProfesoresImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class ProfesorController {
private static final String template = "Hello OP chetao Bien formado, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping(value = "/", method = RequestMethod.GET)
public JsonArrayDTO index() {
RepositorioProfesoresImpl repProf = new RepositorioProfesoresImpl();
return new JsonArrayDTO(false, "Información de Profesores por planta", repProf.findFloor(0));
}
@RequestMapping(value = "/profesores/{planta}", method = RequestMethod.GET)
public ResponseEntity greeting(@PathVariable("planta") int planta) {
RepositorioProfesoresImpl repProf = new RepositorioProfesoresImpl();
return new ResponseEntity<JsonArrayDTO>(new JsonArrayDTO(false, "Información de Profesores por planta", repProf.findFloor(planta)),
HttpStatus.OK);
}
} |
package seedu.ezdo.logic.parser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import seedu.ezdo.commons.exceptions.IllegalValueException;
import seedu.ezdo.commons.util.StringUtil;
import seedu.ezdo.model.tag.Tag;
import seedu.ezdo.model.tag.UniqueTagList;
import seedu.ezdo.model.todo.DueDate;
import seedu.ezdo.model.todo.Name;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.StartDate;
import seedu.ezdo.model.todo.TaskDate;
/**
* Contains utility methods used for parsing strings in the various *Parser classes
*/
public class ParserUtil {
private static final Pattern INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern SORT_CRITERIA_ARGS_FORMAT = Pattern.compile("(?<sortCriteria>.) ?(?<sortOrder>.)?");
private static final Pattern INDEXES_ARGS_FORMAT = Pattern.compile("^([0-9]*\\s+)*[0-9]*$");
private static final Pattern COMMAND_ALIAS_ARGS_FORMAT = Pattern.compile("(?<command>.+) (?<alias>.+)");;
/**
* Returns the specified index in the {@code command} if it is a positive unsigned integer
* Returns an {@code Optional.empty()} otherwise.
*/
public static Optional<Integer> parseIndex(String command) {
final Matcher matcher = INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if (!StringUtil.isUnsignedInteger(index)) {
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
//@@author A0139248X
/**
* Returns the specified indexes in the {@code command} if they are
* positive unsigned integers separated by whitespaces.
* Returns empty array list otherwise.
*/
public static ArrayList<Integer> parseIndexes(String command) {
final Matcher matcher = INDEXES_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return new ArrayList<Integer>();
}
ArrayList<Integer> indexes = new ArrayList<Integer>();
for (String index : command.trim().split("\\s+")) {
indexes.add(Integer.parseInt(index));
}
return indexes;
}
//@@author A0138907W
/**
* Returns the specified sorting criteria in the {@code command} if it is present.
* Returns an {@code Optional.empty()} otherwise.
*/
public static Optional<String[]> parseSortCriteria(String command) {
final Matcher matcher = SORT_CRITERIA_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String sortCriteria = matcher.group("sortCriteria");
String sortOrder = matcher.group("sortOrder");
String[] resultPair = new String[] {sortCriteria, sortOrder};
return Optional.of(resultPair);
}
/**
* Returns a string array of the specified command and alias in the {@code command} if both are present.
* Returns an empty String {@code Array} otherwise.
*/
public static String[] parseCommandAlias(String command) {
final Matcher matcher = COMMAND_ALIAS_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return new String[0];
}
String commandToAlias = matcher.group("command");
String alias = matcher.group("alias");
return new String[] {commandToAlias, alias};
}
//@@author
/**
* Returns a new Set populated by all elements in the given list of strings
* Returns an empty set if the given {@code Optional} is empty,
* or if the list contained in the {@code Optional} is empty
*/
public static Set<String> toSet(Optional<List<String>> list) {
List<String> elements = list.orElse(Collections.emptyList());
return new HashSet<>(elements);
}
/**
* Splits a preamble string into ordered fields.
* @return A list of size {@code numFields} where the ith element is the ith field value if specified in
* the input, {@code Optional.empty()} otherwise.
*/
public static List<Optional<String>> splitPreamble(String preamble, int numFields) {
return Arrays.stream(Arrays.copyOf(preamble.split("\\s+", numFields), numFields))
.map(Optional::ofNullable)
.collect(Collectors.toList());
}
/**
* Parses a {@code Optional<String> name} into an {@code Optional<Name>} if {@code name} is present.
*/
public static Optional<Name> parseName(Optional<String> name) throws IllegalValueException {
assert name != null;
return name.isPresent() ? Optional.of(new Name(name.get())) : Optional.empty();
}
/**
* Parses a {@code Optional<String> priority} into an {@code Optional<Priority>} if {@code priority} is present.
*/
public static Optional<Priority> parsePriority(Optional<String> priority) throws IllegalValueException {
assert priority != null;
return priority.isPresent() ? Optional.of(new Priority(priority.get())) : Optional.empty();
}
/**
* Parses a {@code Optional<String> startDate} into an {@code Optional<StartDate>} if {@code startDate} is present.
*/
public static Optional<TaskDate> parseStartDate(Optional<String> startDate) throws IllegalValueException {
assert startDate != null;
return startDate.isPresent() ? Optional.of(new StartDate(startDate.get())) : Optional.empty();
}
public static Optional<TaskDate> parseStartDate(Optional<String> startDate, boolean isFind)
throws IllegalValueException {
assert startDate != null;
return startDate.isPresent() ? Optional.of(new StartDate(startDate.get(), isFind)) : Optional.empty();
}
/**
* Parses a {@code Optional<String> dueDate} into an {@code Optional<DueDate>} if {@code dueDate} is present.
*/
public static Optional<TaskDate> parseDueDate(Optional<String> dueDate) throws IllegalValueException {
assert dueDate != null;
return dueDate.isPresent() ? Optional.of(new DueDate(dueDate.get())) : Optional.empty();
}
/**
* Parses a {@code Optional<String> dueDate} into an {@code Optional<DueDate>} if {@code dueDate} is present.
*/
public static Optional<TaskDate> parseDueDate(Optional<String> dueDate, boolean isFind)
throws IllegalValueException {
assert dueDate != null;
return dueDate.isPresent() ? Optional.of(new DueDate(dueDate.get(), isFind)) : Optional.empty();
}
/**
* Parses {@code Collection<String> tags} into an {@code UniqueTagList}.
*/
public static UniqueTagList parseTags(Collection<String> tags) throws IllegalValueException {
assert tags != null;
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
return new UniqueTagList(tagSet);
}
} |
package tigase.component;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.Bindings;
import tigase.component.adhoc.AbstractAdHocCommandModule.ScriptCommandProcessor;
import tigase.component.eventbus.Event;
import tigase.component.eventbus.EventHandler;
import tigase.component.exceptions.ComponentException;
import tigase.component.modules.Module;
import tigase.component.modules.ModulesManager;
import tigase.disco.XMPPService;
import tigase.server.AbstractMessageReceiver;
import tigase.server.DisableDisco;
import tigase.server.Packet;
import tigase.util.TigaseStringprepException;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import tigase.xmpp.StanzaType;
/**
* Class description
*
*
* @param <T>
*
*/
public abstract class AbstractComponent<CTX extends Context> extends AbstractMessageReceiver implements XMPPService,
DisableDisco {
public interface ModuleRegisteredHandler extends EventHandler {
public static class ModuleRegisteredEvent extends Event<ModuleRegisteredHandler> {
private String id;
private Module module;
public ModuleRegisteredEvent(String id, Module module) {
this.module = module;
this.id = id;
}
@Override
protected void dispatch(ModuleRegisteredHandler handler) {
handler.onModuleRegistered(id, module);
}
/**
* @return the module
*/
public Module getModule() {
return module;
}
/**
* @param module
* the module to set
*/
public void setModule(Module module) {
this.module = module;
}
}
void onModuleRegistered(String id, Module module);
}
private static final String COMPONENT = "component";
protected final CTX context;
protected final ScriptCommandProcessor defaultScriptCommandProcessor = new ScriptCommandProcessor() {
@Override
public List<Element> getScriptItems(String node, JID jid, JID from) {
return AbstractComponent.this.getScriptItems(node, jid, from);
}
@Override
public boolean processScriptCommand(Packet pc, Queue<Packet> results) {
return AbstractComponent.this.processScriptCommand(pc, results);
}
};
/** Field description */
protected final Logger log = Logger.getLogger(this.getClass().getName());
/** Field description */
protected final ModulesManager modulesManager;
/**
* Constructs ...
*
*/
public AbstractComponent() {
this(null);
}
/**
* Constructs ...
*
*
* @param writer
*/
@SuppressWarnings("unchecked")
public AbstractComponent(Context context) {
if (context == null) {
this.context = createContext();
} else {
this.context = (CTX) context;
}
this.modulesManager = new ModulesManager(this.context);
}
public void addModuleRegisteredHandler(ModuleRegisteredHandler handler) {
this.context.getEventBus().addHandler(ModuleRegisteredHandler.ModuleRegisteredEvent.class, handler);
}
protected abstract CTX createContext();
protected Module createModuleInstance(Class<Module> moduleClass) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
log.finer("Create instance of: " + moduleClass.getName());
for (Constructor<?> x : moduleClass.getConstructors()) {
Object[] args = new Object[x.getParameterTypes().length];
boolean ok = true;
for (int i = 0; i < x.getParameterTypes().length; i++) {
final Class<?> type = x.getParameterTypes()[i];
Object value;
if (type.isAssignableFrom(Context.class)) {
value = context;
} else if (type.isAssignableFrom(ScriptCommandProcessor.class)) {
value = defaultScriptCommandProcessor;
} else {
value = null;
}
ok = ok && value != null;
args[i] = value;
}
if (ok) {
log.finest("Use constructor " + x);
return (Module) x.newInstance(args);
}
}
return null;
}
public abstract String getComponentVersion();
protected Context getContext() {
return context;
}
protected abstract Map<String, Class<? extends Module>> getDefaultModulesList();
/**
* Method description
*
*
* @param params
*
* @return
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
final Map<String, Object> props = super.getDefaults(params);
Map<String, Class<? extends Module>> modules = getDefaultModulesList();
if (modules != null)
for (Entry<String, Class<? extends Module>> m : modules.entrySet()) {
props.put("modules/" + m.getKey(), m.getValue().getName());
}
return props;
}
@Override
public void initBindings(Bindings binds) {
super.initBindings(binds); // To change body of generated methods,
// choose Tools | Templates.
binds.put(COMPONENT, this);
}
protected void initModules(Map<String, Object> props) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
for (Entry<String, Object> e : props.entrySet()) {
try {
if (e.getKey().startsWith("modules/")) {
final String id = e.getKey().substring(8);
final Class<Module> moduleClass = (Class<Module>) Class.forName(e.getValue().toString());
Module module = createModuleInstance(moduleClass);
registerModule(id, module);
}
} catch (ClassNotFoundException ex) {
log.warning("Cannot find Module class " + e.getValue().toString() + ".");
}
}
}
/**
* Is this component discoverable by disco#items for domain by non admin users
*
* @return true - if yes
*/
public abstract boolean isDiscoNonAdmin();
public boolean isRegistered(final String id) {
return this.modulesManager.isRegistered(id);
}
/**
* @param packet
*/
protected void processCommandPacket(Packet packet) {
Queue<Packet> results = new ArrayDeque<Packet>();
processScriptCommand(packet, results);
if (results.size() > 0) {
for (Packet res : results) {
// No more recurrential calls!!
addOutPacketNB(res);
// processPacket(res);
} // end of for ()
}
}
/**
* Method description
*
*
* @param packet
*/
@Override
public void processPacket(Packet packet) {
// if (packet.isCommand()) {
// processCommandPacket(packet);
// } else {
processStanzaPacket(packet);
}
/**
* Method description
*
*
* @param packet
*/
protected void processStanzaPacket(final Packet packet) {
try {
boolean handled = this.modulesManager.process(packet);
if (!handled) {
final String t = packet.getElement().getAttributeStaticStr(Packet.TYPE_ATT);
final StanzaType type = (t == null) ? null : StanzaType.valueof(t);
if (type != StanzaType.error) {
throw new ComponentException(Authorization.FEATURE_NOT_IMPLEMENTED);
} else {
if (log.isLoggable(Level.FINER)) {
log.finer(packet.getElemName() + " stanza with type='error' ignored");
}
}
}
} catch (TigaseStringprepException e) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, e.getMessage() + " when processing " + packet.toString());
}
sendException(packet, new ComponentException(Authorization.JID_MALFORMED));
} catch (ComponentException e) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, e.getMessageWithPosition() + " when processing " + packet.toString());
}
sendException(packet, e);
} catch (Exception e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage() + " when processing " + packet.toString(), e);
}
sendException(packet, new ComponentException(Authorization.INTERNAL_SERVER_ERROR));
}
}
public <M extends Module> M registerModule(final String id, final M module) {
if (this.modulesManager.isRegistered(id)) {
this.modulesManager.unregister(id);
}
M r = this.modulesManager.register(id, module);
if (r != null) {
context.getEventBus().fire(new ModuleRegisteredHandler.ModuleRegisteredEvent(id, r), this);
}
return r;
}
public void removeModuleRegisteredHandler(ModuleRegisteredHandler handler) {
this.context.getEventBus().remove(ModuleRegisteredHandler.ModuleRegisteredEvent.class, handler);
}
/**
* Method description
*
*
* @param packet
* @param e
*/
protected void sendException(final Packet packet, final ComponentException e) {
try {
final String t = packet.getElement().getAttributeStaticStr(Packet.TYPE_ATT);
if ((t != null) && (t == "error")) {
if (log.isLoggable(Level.FINER)) {
log.finer(packet.getElemName() + " stanza already with type='error' ignored");
}
return;
}
Packet result = e.makeElement(packet, true);
Element el = result.getElement();
el.setAttribute("from", BareJID.bareJIDInstance(el.getAttributeStaticStr(Packet.FROM_ATT)).toString());
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Sending back: " + result.toString());
}
context.getWriter().write(result);
} catch (Exception e1) {
if (log.isLoggable(Level.WARNING)) {
log.log(Level.WARNING, "Problem during generate error response", e1);
}
}
}
/**
* Method description
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
try {
initModules(props);
} catch (Exception e) {
log.log(Level.WARNING, "Can't initialize modules!", e);
}
}
@Override
public void updateServiceEntity() {
super.updateServiceEntity();
this.updateServiceDiscoveryItem(getName(), null, getDiscoDescription(), !isDiscoNonAdmin());
}
} |
package tk.justramon.ircbot.justabotx;
import java.io.File;
import org.pircbotx.Configuration;
import org.pircbotx.Configuration.Builder;
import org.pircbotx.PircBotX;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import tk.justramon.ircbot.justabotx.NotImportant.Passwords;
import tk.justramon.ircbot.justabotx.cmds.CommandSwitch;
import tk.justramon.ircbot.justabotx.cmds.QuitAndUpdate;
public class Core extends ListenerAdapter<PircBotX>
{
public static PircBotX bot;
public static boolean enabled = true;
public static boolean wip = false;
public void onMessage(MessageEvent<PircBotX> event) throws Exception
{
if(XtraFunc.isAllowed(event))
{
if((event.getMessage().toLowerCase().contains("*lennyface*") || event.getMessage().toLowerCase().contains("*lenny face*")) && enabled)
event.respond("( ͡° ͜ʖ ͡°)");
}
String[] args = event.getMessage().split(" ");
if(args[0].startsWith("?"))
CommandSwitch.exe(event, args);
Log.exe(event, args);
}
public static void main(String[] args) throws Exception
{
File oldJar = new File("JustLogBotX" + QuitAndUpdate.getJarInt(true) + ".jar");
Thread.sleep(3000);
oldJar.delete();
if(args.length > 0 && args[0].equals("-wip"))
{
wip = true;
Configuration<PircBotX> configuration = new Configuration.Builder<PircBotX>()
.setName(args.length > 1 ? args[1] : "JustABotDev")
.setLogin("JustLogBotX")
.setRealName("Just LogBot X.")
.setAutoReconnect(true)
.setServerHostname("irc.esper.net")
.addAutoJoinChannel("#bl4ckb0tTest")
.setAutoNickChange(true)
.setCapEnabled(true)
.addListener(new Core())
.buildConfiguration();
bot = new PircBotX(configuration);
bot.startBot()/*.addLove(Integer.MAX_VALUE)*/;
}
else
{
//Configure what we want our bot to do
Configuration<PircBotX> configuration = new Configuration.Builder<PircBotX>()
.setName("JustABotX")
.setNickservPassword(Passwords.NICKSERV.getPassword())
.setLogin("JustABotX")
.setRealName("Just a Bot X.")
.setAutoReconnect(true)
.setServerHostname("irc.esper.net")
.setAutoNickChange(true)
.setCapEnabled(true)
.addListener(new Core())
.buildConfiguration();
bot = new PircBotX(configuration);
bot.startBot();
Thread.sleep(1000);
Channels.joinAll(bot);
}
}
public static void setState(boolean state)
{
if(state)
enabled = true;
else
enabled = false;
}
} |
package net.maizegenetics.baseplugins;
import net.maizegenetics.gui.DialogUtils;
import net.maizegenetics.dna.snp.ImportUtils;
import net.maizegenetics.trait.ReadPhenotypeUtils;
import net.maizegenetics.dna.snp.ReadPolymorphismUtils;
import net.maizegenetics.dna.snp.ReadSequenceAlignmentUtils;
import net.maizegenetics.popgen.distance.ReadDistanceMatrix;
import net.maizegenetics.util.Report;
import net.maizegenetics.util.TableReportUtils;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.plugindef.PluginEvent;
import net.maizegenetics.prefs.TasselPrefs;
import net.maizegenetics.util.ExceptionUtils;
import net.maizegenetics.util.Utils;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
*
* @author Ed Buckler
*/
public class FileLoadPlugin extends AbstractPlugin {
private static final Logger myLogger = Logger.getLogger(FileLoadPlugin.class);
private String[] myOpenFiles = null;
private TasselFileType myFileType = TasselFileType.Unknown;
private PlinkLoadPlugin myPlinkLoadPlugin = null;
private ProjectionLoadPlugin myProjectionLoadPlugin = null;
private JFileChooser myOpenFileChooser = new JFileChooser(TasselPrefs.getOpenDir());
public enum TasselFileType {
SqrMatrix, Sequence, Numerical, Unknown, Fasta,
Hapmap, Plink, Phenotype, ProjectionAlignment, Phylip_Seq, Phylip_Inter, GeneticMap, Table,
Serial, HapmapDiploid, Text, HDF5, VCF, ByteHDF5
};
public static final String FILE_EXT_HAPMAP = ".hmp.txt";
public static final String FILE_EXT_HAPMAP_GZ = ".hmp.txt.gz";
public static final String FILE_EXT_PLINK_MAP = ".plk.map";
public static final String FILE_EXT_PLINK_PED = ".plk.ped";
public static final String FILE_EXT_SERIAL_GZ = ".serial.gz";
public static final String FILE_EXT_HDF5 = ".hmp.h5";
public static final String FILE_EXT_VCF = ".vcf";
/**
* Creates a new instance of FileLoadPlugin
*/
public FileLoadPlugin(Frame parentFrame, boolean isInteractive) {
super(parentFrame, isInteractive);
}
public FileLoadPlugin(Frame parentFrame, boolean isInteractive, PlinkLoadPlugin plinkLoadPlugin, ProjectionLoadPlugin projectionLoadPlugin) {
super(parentFrame, isInteractive);
myPlinkLoadPlugin = plinkLoadPlugin;
myProjectionLoadPlugin = projectionLoadPlugin;
}
public DataSet performFunction(DataSet input) {
try {
if (isInteractive()) {
FileLoadPluginDialog theDialog = new FileLoadPluginDialog();
theDialog.setLocationRelativeTo(getParentFrame());
theDialog.setVisible(true);
if (theDialog.isCancel()) {
return null;
}
myFileType = theDialog.getTasselFileType();
if (myFileType == TasselFileType.Plink) {
return myPlinkLoadPlugin.performFunction(null);
}
if (myFileType == TasselFileType.ProjectionAlignment) {
return myProjectionLoadPlugin.performFunction(null);
}
setOpenFiles(getOpenFilesByChooser());
theDialog.dispose();
}
if ((myOpenFiles == null) || (myOpenFiles.length == 0)) {
return null;
}
List result = new ArrayList();
ArrayList<String> alreadyLoaded = new ArrayList();
for (int i = 0; i < myOpenFiles.length; i++) {
if (alreadyLoaded.contains(myOpenFiles[i])) {
continue;
}
DataSet tds = null;
try {
if (myFileType == TasselFileType.Unknown) {
if (myOpenFiles[i].endsWith(FILE_EXT_HAPMAP) || myOpenFiles[i].endsWith(FILE_EXT_HAPMAP_GZ)) {
myLogger.info("guessAtUnknowns: type: " + TasselFileType.Hapmap);
alreadyLoaded.add(myOpenFiles[i]);
tds = processDatum(myOpenFiles[i], TasselFileType.Hapmap);
} else if (myOpenFiles[i].endsWith(FILE_EXT_PLINK_PED)) {
myLogger.info("guessAtUnknowns: type: " + TasselFileType.Plink);
String theMapFile = myOpenFiles[i].replaceFirst(FILE_EXT_PLINK_PED, FILE_EXT_PLINK_MAP);
alreadyLoaded.add(myOpenFiles[i]);
alreadyLoaded.add(theMapFile);
myPlinkLoadPlugin.loadFile(myOpenFiles[i], theMapFile, null);
} else if (myOpenFiles[i].endsWith(FILE_EXT_PLINK_MAP)) {
myLogger.info("guessAtUnknowns: type: " + TasselFileType.Plink);
String thePedFile = myOpenFiles[i].replaceFirst(FILE_EXT_PLINK_MAP, FILE_EXT_PLINK_PED);
alreadyLoaded.add(myOpenFiles[i]);
alreadyLoaded.add(thePedFile);
myPlinkLoadPlugin.loadFile(thePedFile, myOpenFiles[i], null);
} else if (myOpenFiles[i].endsWith(FILE_EXT_SERIAL_GZ)) {
myLogger.info("guessAtUnknowns: type: " + TasselFileType.Serial);
alreadyLoaded.add(myOpenFiles[i]);
tds = processDatum(myOpenFiles[i], TasselFileType.Serial);
} else if (myOpenFiles[i].endsWith(FILE_EXT_HDF5)) {
myLogger.info("guessAtUnknowns: type: " + TasselFileType.HDF5);
alreadyLoaded.add(myOpenFiles[i]);
tds = processDatum(myOpenFiles[i], TasselFileType.HDF5);
} else if (myOpenFiles[i].endsWith(FILE_EXT_VCF) || myOpenFiles[i].endsWith(FILE_EXT_VCF + ".gz")) {
myLogger.info("guessAtUnknowns: type: " + TasselFileType.VCF);
alreadyLoaded.add(myOpenFiles[i]);
tds = processDatum(myOpenFiles[i], TasselFileType.VCF);
} else {
alreadyLoaded.add(myOpenFiles[i]);
tds = guessAtUnknowns(myOpenFiles[i]);
}
} else {
alreadyLoaded.add(myOpenFiles[i]);
tds = processDatum(myOpenFiles[i], myFileType);
}
} catch (Exception e) {
e.printStackTrace();
StringBuilder builder = new StringBuilder();
builder.append("Error loading: ");
builder.append(myOpenFiles[i]);
builder.append("\n");
builder.append(Utils.shortenStrLineLen(ExceptionUtils.getExceptionCauses(e), 50));
String str = builder.toString();
if (isInteractive()) {
DialogUtils.showError(str, getParentFrame());
} else {
myLogger.error(str);
}
}
if (tds != null) {
result.add(tds);
fireDataSetReturned(new PluginEvent(tds, FileLoadPlugin.class));
}
}
return DataSet.getDataSet(result, this);
} finally {
fireProgress(100);
}
}
public DataSet guessAtUnknowns(String filename) {
TasselFileType guess = TasselFileType.Sequence;
DataSet tds = null;
try {
BufferedReader br = null;
if (filename.startsWith("http")) {
URL url = new URL(filename);
br = new BufferedReader(new InputStreamReader(url.openStream()));
} else {
br = new BufferedReader(new FileReader(filename));
}
String line1 = br.readLine().trim();
String[] sval1 = line1.split("\\s");
String line2 = br.readLine().trim();
String[] sval2 = line2.split("\\s");
boolean lociMatchNumber = false;
if (!sval1[0].startsWith("<") && (sval1.length == 2) && (line1.indexOf(':') < 0)) {
int countLoci = Integer.parseInt(sval1[1]);
if (countLoci == sval2.length) {
lociMatchNumber = true;
}
}
if (line1.startsWith("<") || line1.startsWith("
boolean isTrait = false;
boolean isMarker = false;
boolean isNumeric = false;
boolean isMap = false;
Pattern tagPattern = Pattern.compile("[<>\\s]+");
String[] info1 = tagPattern.split(line1);
String[] info2 = tagPattern.split(line2);
if (info1.length > 1) {
if (info1[1].toUpperCase().startsWith("MARKER")) {
isMarker = true;
} else if (info1[1].toUpperCase().startsWith("TRAIT")) {
isTrait = true;
} else if (info1[1].toUpperCase().startsWith("NUMER")) {
isNumeric = true;
} else if (info1[1].toUpperCase().startsWith("MAP")) {
isMap = true;
}
}
if (info2.length > 1) {
if (info2[1].toUpperCase().startsWith("MARKER")) {
isMarker = true;
} else if (info2[1].toUpperCase().startsWith("TRAIT")) {
isTrait = true;
} else if (info2[1].toUpperCase().startsWith("NUMER")) {
isNumeric = true;
} else if (info2[1].toUpperCase().startsWith("MAP")) {
isMap = true;
}
} else {
guess = null;
String inline = br.readLine();
while (guess == null && inline != null && (inline.startsWith("#") || inline.startsWith("<"))) {
if (inline.startsWith("<")) {
String[] info = tagPattern.split(inline);
if (info[1].toUpperCase().startsWith("MARKER")) {
isMarker = true;
} else if (info[1].toUpperCase().startsWith("TRAIT")) {
isTrait = true;
} else if (info[1].toUpperCase().startsWith("NUMER")) {
isNumeric = true;
} else if (info[1].toUpperCase().startsWith("MAP")) {
isMap = true;
}
}
}
}
if (isTrait || (isMarker && isNumeric)) {
guess = TasselFileType.Phenotype;
} else if (isMap) {
guess = TasselFileType.GeneticMap;
} else {
throw new IOException("Improperly formatted header. Data will not be imported.");
}
} else if ((line1.startsWith(">")) || (line1.startsWith(";"))) {
guess = TasselFileType.Fasta;
} else if (sval1.length == 1) {
guess = TasselFileType.SqrMatrix;
} else if ((line1.startsWith("#Nexus")) || (line1.startsWith("#NEXUS")) || (line1.startsWith("CLUSTAL"))
|| ((sval1.length == 2) && (sval2.length == 2))) {
guess = TasselFileType.Sequence;
} else if (sval1.length == 3) {
guess = TasselFileType.Numerical;
}
myLogger.info("guessAtUnknowns: type: " + guess);
tds = processDatum(filename, guess);
br.close();
} catch (Exception e) {
}
return tds;
}
private DataSet processDatum(String inFile, TasselFileType theFT) {
Object result = null;
String suffix = null;
try {
switch (theFT) {
case Hapmap: {
suffix = FILE_EXT_HAPMAP;
if (inFile.endsWith(".gz")) {
suffix = FILE_EXT_HAPMAP_GZ;
}
result = ImportUtils.readFromHapmap(inFile, true, this);
break;
}
case HDF5: {
suffix = FILE_EXT_HDF5;
// result = BitAlignmentHDF5.getInstance(inFile);
result = ImportUtils.readGuessFormat(inFile);
break;
}
case VCF: {
suffix = FILE_EXT_VCF;
if (inFile.endsWith(".gz")) {
suffix = FILE_EXT_VCF + ".gz";
}
result = ImportUtils.readFromVCF(inFile, this);
break;
}
case Sequence: {
result = ReadSequenceAlignmentUtils.readBasicAlignments(inFile, 40);
break;
}
case Numerical: {
result = ReadPhenotypeUtils.readNumericalAlignment(inFile);
break;
}
case SqrMatrix: {
result = ReadDistanceMatrix.readDistanceMatrix(inFile);
break;
}
case Phenotype: {
result = ReadPhenotypeUtils.readGenericFile(inFile);
break;
}
case GeneticMap: {
result = ReadPolymorphismUtils.readGeneticMapFile(inFile);
break;
}
case Table: {
result = TableReportUtils.readDelimitedTableReport(inFile, "\t");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
StringBuilder builder = new StringBuilder();
builder.append("Error loading: ");
builder.append(inFile);
builder.append("\n");
builder.append(Utils.shortenStrLineLen(ExceptionUtils.getExceptionCauses(e), 50));
String str = builder.toString();
if (isInteractive()) {
DialogUtils.showError(str, getParentFrame());
} else {
myLogger.error(str);
}
}
if (result != null) {
String theComment = "";
if (result instanceof Report) {
StringWriter sw = new StringWriter();
((Report) result).report(new PrintWriter(sw));
theComment = sw.toString();
}
String name = Utils.getFilename(inFile, suffix);
Datum td = new Datum(name, result, theComment);
//todo need to add logic of directories.
DataSet tds = new DataSet(td, this);
return tds;
}
return null;
}
/**
* Provides a open filer that remember the last location something was
* opened from
*/
private File[] getOpenFilesByChooser() {
myOpenFileChooser.setMultiSelectionEnabled(true);
File[] lopenFiles = null;
myOpenFileChooser.setVisible(true);
int returnVal = myOpenFileChooser.showOpenDialog(getParentFrame());
if (returnVal == JFileChooser.OPEN_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) {
lopenFiles = myOpenFileChooser.getSelectedFiles();
TasselPrefs.putOpenDir(myOpenFileChooser.getCurrentDirectory().getPath());
}
return lopenFiles;
}
public String[] getOpenFiles() {
return myOpenFiles;
}
public void setOpenFiles(File[] openFiles) {
if ((openFiles == null) || (openFiles.length == 0)) {
myOpenFiles = null;
return;
}
myOpenFiles = new String[openFiles.length];
for (int i = 0; i < openFiles.length; i++) {
myOpenFiles[i] = openFiles[i].getPath();
}
}
public void setOpenFiles(String[] openFiles) {
if ((openFiles == null) || (openFiles.length == 0)) {
myOpenFiles = null;
} else {
myOpenFiles = openFiles;
}
}
public TasselFileType getTheFileType() {
return myFileType;
}
public void setTheFileType(TasselFileType theFileType) {
myFileType = theFileType;
}
/**
* Icon for this plugin to be used in buttons, etc.
*
* @return ImageIcon
*/
public ImageIcon getIcon() {
URL imageURL = FileLoadPlugin.class.getResource("images/LoadFile.gif");
if (imageURL == null) {
return null;
} else {
return new ImageIcon(imageURL);
}
}
/**
* Button name for this plugin to be used in buttons, etc.
*
* @return String
*/
public String getButtonName() {
return "Load";
}
/**
* Tool Tip Text for this plugin
*
* @return String
*/
public String getToolTipText() {
return "Load data from files on your computer.";
}
}
class FileLoadPluginDialog extends JDialog {
boolean isCancel = true;
ButtonGroup conversionButtonGroup = new ButtonGroup();
JRadioButton hapMapRadioButton = new JRadioButton("Load Hapmap");
JRadioButton hdf5RadioButton = new JRadioButton("Load HDF5");
JRadioButton vcfRadioButton = new JRadioButton("Load VCF");
JRadioButton plinkRadioButton = new JRadioButton("Load Plink");
JRadioButton sequenceAlignRadioButton = new JRadioButton("Load sequence alignment (phylip, NEXUS)");
JRadioButton fastaRadioButton = new JRadioButton("Load FASTA file");
JRadioButton numericalRadioButton = new JRadioButton("Load Trait (data, covariates, or factors)");
JRadioButton loadMatrixRadioButton = new JRadioButton("Load square numerical matrix (eg. kinship) (phylip)");
JRadioButton guessRadioButton = new JRadioButton("I will make my best guess and try.");
JRadioButton projectionAlignmentRadioButton = new JRadioButton("Load Projection Alignment");
JRadioButton geneticMapRadioButton = new JRadioButton("Load a Genetic Map");
JRadioButton tableReportRadioButton = new JRadioButton("Load a Table Report");
public FileLoadPluginDialog() {
super((Frame) null, "File Loader", true);
try {
jbInit();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbInit() throws Exception {
setTitle("File Loader");
setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
setUndecorated(false);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
Container contentPane = getContentPane();
BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS);
contentPane.setLayout(layout);
JPanel main = getMain();
contentPane.add(main);
pack();
setResizable(false);
conversionButtonGroup.add(projectionAlignmentRadioButton);
conversionButtonGroup.add(hapMapRadioButton);
conversionButtonGroup.add(hdf5RadioButton);
conversionButtonGroup.add(vcfRadioButton);
conversionButtonGroup.add(plinkRadioButton);
conversionButtonGroup.add(sequenceAlignRadioButton);
conversionButtonGroup.add(fastaRadioButton);
conversionButtonGroup.add(loadMatrixRadioButton);
conversionButtonGroup.add(numericalRadioButton);
conversionButtonGroup.add(geneticMapRadioButton);
conversionButtonGroup.add(tableReportRadioButton);
conversionButtonGroup.add(guessRadioButton);
guessRadioButton.setSelected(true);
}
private JPanel getMain() {
JPanel inputs = new JPanel();
BoxLayout layout = new BoxLayout(inputs, BoxLayout.Y_AXIS);
inputs.setLayout(layout);
inputs.setAlignmentX(JPanel.CENTER_ALIGNMENT);
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getLabel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getOptionPanel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getButtons());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
return inputs;
}
private JPanel getLabel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
JLabel jLabel1 = new JLabel("Choose File Type to Load.");
jLabel1.setFont(new Font("Dialog", Font.BOLD, 18));
result.add(jLabel1);
return result;
}
private JPanel getOptionPanel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
result.setBorder(BorderFactory.createEtchedBorder());
result.add(hapMapRadioButton);
result.add(hdf5RadioButton);
result.add(vcfRadioButton);
result.add(plinkRadioButton);
result.add(projectionAlignmentRadioButton);
result.add(sequenceAlignRadioButton);
result.add(fastaRadioButton);
result.add(numericalRadioButton);
result.add(loadMatrixRadioButton);
result.add(geneticMapRadioButton);
result.add(tableReportRadioButton);
result.add(guessRadioButton);
result.add(Box.createRigidArea(new Dimension(1, 20)));
return result;
}
private JPanel getButtons() {
JButton okButton = new JButton();
JButton cancelButton = new JButton();
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButton_actionPerformed(e);
}
});
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButton_actionPerformed(e);
}
});
JPanel result = new JPanel(new FlowLayout(FlowLayout.CENTER));
result.add(okButton);
result.add(cancelButton);
return result;
}
public FileLoadPlugin.TasselFileType getTasselFileType() {
if (hapMapRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Hapmap;
}
if (hdf5RadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.HDF5;
}
if (vcfRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.VCF;
}
if (plinkRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Plink;
}
if (projectionAlignmentRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.ProjectionAlignment;
}
if (sequenceAlignRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Sequence;
}
if (fastaRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Fasta;
}
if (loadMatrixRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.SqrMatrix;
}
if (numericalRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Unknown;
}
if (geneticMapRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.GeneticMap;
}
if (tableReportRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Table;
}
return FileLoadPlugin.TasselFileType.Unknown;
}
public void okButton_actionPerformed(ActionEvent e) {
isCancel = false;
setVisible(false);
}
public void cancelButton_actionPerformed(ActionEvent e) {
isCancel = true;
setVisible(false);
}
public boolean isCancel() {
return isCancel;
}
} |
package net.rubyeye.xmemcached;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.code.yanf4j.nio.CodecFactory;
import com.google.code.yanf4j.util.ByteBufferMatcher;
import net.rubyeye.xmemcached.command.Command;
import net.rubyeye.xmemcached.exception.MemcachedClientException;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.exception.MemcachedServerException;
import net.spy.memcached.transcoders.CachedData;
public class MemcachedCodecFactory implements CodecFactory<Command> {
private static final ByteBuffer SPLIT = ByteBuffer.wrap(Command.SPLIT
.getBytes());
protected static final Log log = LogFactory
.getLog(MemcachedCodecFactory.class);
static ByteBufferMatcher SPLIT_MATCHER = new ByteBufferMatcher(SPLIT);
enum ParseStatus {
NULL, GET, END, STORED, NOT_STORED, ERROR, CLIENT_ERROR, SERVER_ERROR, DELETED, NOT_FOUND, VERSION, INCR;
}
@SuppressWarnings("unchecked")
public Decoder<Command> getDecoder() {
return new Decoder<Command>() {
private Command resultCommand;
private ParseStatus status = ParseStatus.NULL;
private String currentLine = null;
public Command decode(ByteBuffer buffer) {
int origPos = buffer.position();
int origLimit = buffer.limit();
LABEL: while (true) {
switch (this.status) {
case NULL:
nextLine(buffer);
if (currentLine == null) {
return null;
}
if (currentLine.startsWith("VALUE")) {
this.resultCommand = new Command(
Command.CommandType.GET);
List<String> keys = new ArrayList<String>(30);
this.resultCommand.setKey(keys);
List<CachedData> datas = new ArrayList<CachedData>(
30);
this.resultCommand.setResult(datas);
this.status = ParseStatus.GET;
} else if (currentLine.equals("STORED")) {
this.status = ParseStatus.STORED;
} else if (currentLine.equals("DELETED")) {
this.status = ParseStatus.DELETED;
} else if (currentLine.equals("END")) {
this.status = ParseStatus.END;
} else if (currentLine.equals("NOT_STORED")) {
this.status = ParseStatus.NOT_STORED;
} else if (currentLine.equals("NOT_FOUND")) {
this.status = ParseStatus.NOT_FOUND;
} else if (currentLine.equals("ERROR")) {
this.status = ParseStatus.ERROR;
} else if (currentLine.startsWith("CLIENT_ERROR")) {
this.status = ParseStatus.CLIENT_ERROR;
} else if (currentLine.startsWith("SERVER_ERROR")) {
this.status = ParseStatus.SERVER_ERROR;
} else if (currentLine.startsWith("VERSION ")) {
this.status = ParseStatus.VERSION;
} else {
this.status = ParseStatus.INCR;
}
if (!this.status.equals(ParseStatus.NULL))
continue LABEL;
else {
log.error("unknow response:" + this.currentLine);
throw new IllegalStateException("unknown response:"
+ this.currentLine);
}
case GET:
List<String> keys = (List<String>) this.resultCommand
.getKey();
List<CachedData> datas = (List<CachedData>) this.resultCommand
.getResult();
while (true) {
nextLine(buffer);
if (currentLine == null)
return null;
if (this.currentLine.equals("END")) {
Command returnCommand = this.resultCommand;
this.resultCommand = null;
reset();
return returnCommand;
} else if (currentLine.startsWith("VALUE")) {
String[] items = this.currentLine.split(" ");
int flag = Integer.parseInt(items[2]);
int dataLen = Integer.parseInt(items[3]);
if (buffer.remaining() < dataLen + 2) {
buffer.position(origPos).limit(origLimit);
this.currentLine = null;
return null;
}
keys.add(items[1]);
byte[] data = new byte[dataLen];
buffer.get(data);
datas.add(new CachedData(flag, data, dataLen));
buffer.position(buffer.position()
+ SPLIT.remaining());
this.currentLine = null;
} else {
buffer.position(origPos).limit(origLimit);
this.currentLine = null;
return null;
}
}
case END:
return parseEndCommand();
case STORED:
return parseStored();
case NOT_STORED:
return parseNotStored();
case DELETED:
return parseDeleted();
case NOT_FOUND:
return parseNotFound();
case ERROR:
return parseException();
case CLIENT_ERROR:
return parseClientException();
case SERVER_ERROR:
return parseServerException();
case VERSION:
return parseVersionCommand();
case INCR:
return parseIncrDecrCommand();
default:
return null;
}
}
}
private Command parseEndCommand() {
reset();
return new Command(Command.CommandType.GET);
}
private Command parseStored() {
reset();
return new Command(Command.CommandType.STORE) {
public Object getResult() {
return true;
}
};
}
private Command parseNotStored() {
reset();
return new Command(Command.CommandType.STORE) {
public Object getResult() {
return false;
}
};
}
private Command parseDeleted() {
reset();
return new Command(Command.CommandType.OTHER) {
public Object getResult() {
return true;
}
};
}
private Command parseNotFound() {
reset();
return new Command(Command.CommandType.OTHER) {
public Object getResult() {
return false;
}
};
}
private Command parseException() {
reset();
return new Command(Command.CommandType.EXCEPTION) {
@Override
public RuntimeException getException() {
return new MemcachedException("unknown command");
}
};
}
private Command parseClientException() {
String[] items = this.currentLine.split(" ");
final String error = items.length > 1 ? items[1]
: "unknown client error";
reset();
return new Command(Command.CommandType.EXCEPTION) {
@Override
public RuntimeException getException() {
return new MemcachedClientException(error);
}
};
}
private Command parseServerException() {
String[] items = this.currentLine.split(" ");
final String error = items.length > 1 ? items[1]
: "unknown server error";
reset();
return new Command() {
@Override
public RuntimeException getException() {
return new MemcachedServerException(error);
}
};
}
private Command parseVersionCommand() {
String[] items = this.currentLine.split(" ");
final String version = items.length > 1 ? items[1]
: "unknown version";
reset();
return new Command() {
@Override
public Object getResult() {
return version;
}
};
}
private void reset() {
this.status = ParseStatus.NULL;
this.currentLine = null;
}
private Command parseIncrDecrCommand() {
final Integer result = Integer.parseInt(this.currentLine);
reset();
return new Command(Command.CommandType.OTHER) {
@Override
public Object getResult() {
return result;
}
};
}
private void nextLine(ByteBuffer buffer) {
if (this.currentLine != null)
return;
int index = SPLIT_MATCHER.matchFirst(buffer);
if (index >= 0) {
int limit = buffer.limit();
buffer.limit(index);
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
buffer.limit(limit);
buffer.position(index + SPLIT.remaining());
try {
this.currentLine = new String(bytes, "utf-8");
} catch (UnsupportedEncodingException e) {
}
} else
this.currentLine = null;
}
};
}
public Encoder<Command> getEncoder() {
return new Encoder<Command>() {
public ByteBuffer[] encode(Command cmd) {
return new ByteBuffer[] { cmd.getByteBuffer() };
}
};
}
} |
package net.sf.jaer.util.avioutput;
import com.jogamp.common.nio.Buffers;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.awt.GLCanvas;
import java.awt.Desktop;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventio.AEInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
/**
* Base class for EventFilters that write out AVI files from jAER
*
* @author Tobi
*/
@Description("Base class for EventFilters that write out AVI files from jAER")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class AbstractAviWriter extends EventFilter2D implements FrameAnnotater, PropertyChangeListener {
protected AVIOutputStream aviOutputStream = null;
protected static String DEFAULT_FILENAME = "jAER.avi";
protected String lastFileName = getString("lastFileName", DEFAULT_FILENAME);
protected int framesWritten = 0;
protected final int logEveryThisManyFrames = 30;
protected boolean writeTimecodeFile = getBoolean("writeTimecodeFile", true);
protected static final String TIMECODE_SUFFIX = "-timecode.txt";
protected File timecodeFile = null;
protected FileWriter timecodeWriter = null;
protected boolean closeOnRewind = getBoolean("closeOnRewind", true);
private boolean chipPropertyChangeListenerAdded = false;
protected AVIOutputStream.VideoFormat format = AVIOutputStream.VideoFormat.valueOf(getString("format", AVIOutputStream.VideoFormat.RAW.toString()));
protected int maxFrames = getInt("maxFrames", 0);
protected float compressionQuality = getFloat("compressionQuality", 0.9f);
private String[] additionalComments = null;
private int frameRate=getInt("frameRate",30);
public AbstractAviWriter(AEChip chip) {
super(chip);
setPropertyTooltip("startRecordingAndSaveAVIAs", "Opens the output file and starts writing to it. The AVI file is in RAW format with pixel values 0-255 coming from ApsFrameExtractor displayed frames, which are offset and scaled by it.");
setPropertyTooltip("closeFile", "Closes the output file if it is open.");
setPropertyTooltip("writeTimecodeFile", "writes a file alongside AVI file (with suffix " + TIMECODE_SUFFIX + ") that maps from AVI frame to AER timestamp for that frame (the frame end timestamp)");
setPropertyTooltip("closeOnRewind", "closes recording on rewind event, to allow unattended operation");
setPropertyTooltip("resizeWindowTo16To9Format", "resizes AEViewer window to 19:9 format");
setPropertyTooltip("resizeWindowTo4To3Format", "resizes AEViewer window to 4:3 format");
setPropertyTooltip("format", "video file is writtent to this output format (note that RLE will throw exception because OpenGL frames are not 4 or 8 bit images)");
setPropertyTooltip("maxFrames", "file is automatically closed after this many frames have been written; set to 0 to disable");
setPropertyTooltip("framesWritten", "READONLY, shows number of frames written");
setPropertyTooltip("compressionQuality", "In PNG or JPG format, sets compression quality; 0 is lowest quality and 1 is highest, 0.9 is default value");
setPropertyTooltip("showFolderInDesktop", "Opens the folder containging the last-written AVI file");
setPropertyTooltip("frameRate", "Specifies frame rate of AVI file.");
chip.getSupport().addPropertyChangeListener(this);
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
if (!chipPropertyChangeListenerAdded) {
if (chip.getAeViewer() != null) {
chip.getAeViewer().addPropertyChangeListener(AEInputStream.EVENT_REWIND, this);
chipPropertyChangeListenerAdded = true;
}
}
return in;
}
@Override
public void resetFilter() {
}
@Override
public void initFilter() {
}
public void doResizeWindowTo4To3Format() {
resizeWindowTo(640, 480);
}
public void doResizeWindowTo16To9Format() {
resizeWindowTo(640, 360);
}
private void resizeWindowTo(int w, int h) {
if(aviOutputStream!=null){
log.warning("resizing disabled during recording to prevent AVI corruption");
return;
}
AEViewer v = chip.getAeViewer();
if (v == null) {
log.warning("No AEViewer");
return;
}
GLCanvas c = (GLCanvas) (chip.getCanvas().getCanvas());
if (c == null) {
log.warning("No Canvas to resize");
return;
}
int ww = c.getWidth(), hh = c.getHeight();
int vw=v.getWidth(), vh=v.getHeight();
v.setSize(w + (vw-ww), h + (vh-hh));
v.revalidate();
int ww2 = c.getWidth(), hh2 = c.getHeight();
log.info(String.format("Canvas resized from %d x %d to %d x %d pixels", ww, hh, ww2, hh2));
}
public void doShowFolderInDesktop() {
if (!Desktop.isDesktopSupported()) {
log.warning("Sorry, desktop operations are not supported");
return;
}
try {
Desktop desktop = Desktop.getDesktop();
File f = new File(lastFileName);
if (f.exists()) {
desktop.open(f.getParentFile());
}
} catch (Exception e) {
log.warning(e.toString());
}
}
synchronized public void doStartRecordingAndSaveAVIAs() {
if (aviOutputStream != null) {
JOptionPane.showMessageDialog(null, "AVI output stream is already opened");
return;
}
JFileChooser c = new JFileChooser(lastFileName);
c.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".avi");
}
@Override
public String getDescription() {
return "AVI (Audio Video Interleave) Microsoft video file";
}
});
c.setSelectedFile(new File(lastFileName));
int ret = c.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
if (!c.getSelectedFile().getName().toLowerCase().endsWith(".avi")) {
String newName = c.getSelectedFile().toString() + ".avi";
c.setSelectedFile(new File(newName));
}
lastFileName = c.getSelectedFile().toString();
if (c.getSelectedFile().exists()) {
int r = JOptionPane.showConfirmDialog(null, "File " + c.getSelectedFile().toString() + " already exists, overwrite it?");
if (r != JOptionPane.OK_OPTION) {
return;
}
}
openAVIOutputStream(c.getSelectedFile(), additionalComments);
}
synchronized public void doCloseFile() {
if (aviOutputStream != null) {
try {
aviOutputStream.close();
aviOutputStream = null;
if (timecodeWriter != null) {
timecodeWriter.close();
log.info("Closed timecode file " + timecodeFile.toString());
timecodeWriter = null;
}
log.info("Closed " + lastFileName + " in format " + format + " with " + framesWritten + " frames");
} catch (Exception ex) {
log.warning(ex.toString());
ex.printStackTrace();
aviOutputStream = null;
}
}
}
/**
* Opens AVI output stream and optionally the timecode file.
*
* @param f the file
* @param additionalComments additional comments to be written to timecode
* file, Comment header characters are added if not supplied.
*
*/
private void openAVIOutputStream(File f, String[] additionalComments) {
try {
aviOutputStream = new AVIOutputStream(f, format);
// aviOutputStream.setFrameRate(chip.getAeViewer().getFrameRate());
aviOutputStream.setFrameRate(frameRate);
aviOutputStream.setVideoCompressionQuality(compressionQuality);
// aviOutputStream.setVideoDimension(chip.getSizeX(), chip.getSizeY());
lastFileName = f.toString();
putString("lastFileName", lastFileName);
if (writeTimecodeFile) {
String s = f.toString().subSequence(0, f.toString().lastIndexOf(".")).toString() + TIMECODE_SUFFIX;
timecodeFile = new File(s);
timecodeWriter = new FileWriter(timecodeFile);
timecodeWriter.write(String.format("# timecode file relating frames of AVI file to AER timestamps\n"));
timecodeWriter.write(String.format("# written %s\n", new Date().toString()));
if (additionalComments != null) {
for (String st : additionalComments) {
if (!st.startsWith("
st = "
}
if (!st.endsWith("\n")) {
st = st + "\n";
}
timecodeWriter.write(st);
}
}
timecodeWriter.write(String.format("# frameNumber timestamp\n"));
log.info("Opened timecode file " + timecodeFile.toString());
}
log.info("Opened AVI output file " + f.toString() + " with format " + format);
setFramesWritten(0);
getSupport().firePropertyChange("framesWritten", null, framesWritten);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString(), "Couldn't create output file stream", JOptionPane.WARNING_MESSAGE, null);
return;
}
}
/**
* @return the writeTimecodeFile
*/
public boolean isWriteTimecodeFile() {
return writeTimecodeFile;
}
/**
* @param writeTimecodeFile the writeTimecodeFile to set
*/
public void setWriteTimecodeFile(boolean writeTimecodeFile) {
this.writeTimecodeFile = writeTimecodeFile;
putBoolean("writeTimecodeFile", writeTimecodeFile);
}
/**
* @return the closeOnRewind
*/
public boolean isCloseOnRewind() {
return closeOnRewind;
}
/**
* @param closeOnRewind the closeOnRewind to set
*/
public void setCloseOnRewind(boolean closeOnRewind) {
this.closeOnRewind = closeOnRewind;
putBoolean("closeOnRewind", closeOnRewind);
}
@Override
public void annotate(GLAutoDrawable drawable) {
}
/**
* Turns gl to BufferedImage with fixed format
*
* @param gl
* @param w
* @param h
* @return
*/
protected BufferedImage toImage(GL2 gl, int w, int h) {
gl.glReadBuffer(GL.GL_FRONT); // or GL.GL_BACK
ByteBuffer glBB = Buffers.newDirectByteBuffer(4 * w * h);
gl.glReadPixels(0, 0, w, h, GL2.GL_BGRA, GL.GL_BYTE, glBB);
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_BGR);
int[] bd = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int b = 2 * glBB.get();
int g = 2 * glBB.get();
int r = 2 * glBB.get();
int a = glBB.get(); // not using
bd[(h - y - 1) * w + x] = (b << 16) | (g << 8) | r | 0xFF000000;
}
}
return bi;
}
protected void writeTimecode(int timestamp) throws IOException {
if (timecodeWriter != null) {
timecodeWriter.write(String.format("%d %d\n", framesWritten, timestamp));
}
}
protected void incrementFramecountAndMaybeCloseOutput() {
if (++framesWritten % logEveryThisManyFrames == 0) {
log.info(String.format("wrote %d frames", framesWritten));
}
getSupport().firePropertyChange("framesWritten", null, framesWritten);
if (maxFrames > 0 && framesWritten >= maxFrames) {
log.info("wrote maxFrames=" + maxFrames + " frames; closing AVI file");
doCloseFile();
}
}
/**
* @return the format
*/
public AVIOutputStream.VideoFormat getFormat() {
return format;
}
/**
* @param format the format to set
*/
public void setFormat(AVIOutputStream.VideoFormat format) {
this.format = format;
putString("format", format.toString());
}
/**
* @return the maxFrames
*/
public int getMaxFrames() {
return maxFrames;
}
/**
* @param maxFrames the maxFrames to set
*/
public void setMaxFrames(int maxFrames) {
this.maxFrames = maxFrames;
putInt("maxFrames", maxFrames);
}
/**
* @return the framesWritten
*/
public int getFramesWritten() {
return framesWritten;
}
/**
* @param framesWritten the framesWritten to set
*/
public void setFramesWritten(int framesWritten) {
int old = this.framesWritten;
this.framesWritten = framesWritten;
getSupport().firePropertyChange("framesWritten", old, framesWritten);
}
/**
* @return the compressionQuality
*/
public float getCompressionQuality() {
return compressionQuality;
}
/**
* @param compressionQuality the compressionQuality to set
*/
public void setCompressionQuality(float compressionQuality) {
if (compressionQuality < 0) {
compressionQuality = 0;
} else if (compressionQuality > 1) {
compressionQuality = 1;
}
this.compressionQuality = compressionQuality;
putFloat("compressionQuality", compressionQuality);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (closeOnRewind && evt.getPropertyName() == AEInputStream.EVENT_REWIND) {
doCloseFile();
}
}
/**
* @return the additionalComments
*/
public String[] getAdditionalComments() {
return additionalComments;
}
/**
* Sets array of additional comment strings to be written to timecode file.
*
* @param additionalComments the additionalComments to set
*/
public void setAdditionalComments(String[] additionalComments) {
this.additionalComments = additionalComments;
}
/**
* @return the frameRate
*/
public int getFrameRate() {
return frameRate;
}
/**
* @param frameRate the frameRate to set
*/
public void setFrameRate(int frameRate) {
if(frameRate<1)frameRate=1;
this.frameRate = frameRate;
putInt("frameRate",frameRate);
}
} |
package net.sf.jaer.util.avioutput;
import static net.sf.jaer.graphics.AEViewer.DEFAULT_CHIP_CLASS;
import static net.sf.jaer.graphics.AEViewer.prefs;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import com.jogamp.opengl.GLAutoDrawable;
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import ch.unizh.ini.jaer.projects.npp.DvsFramer.TimeSliceMethod;
import ch.unizh.ini.jaer.projects.npp.DvsFramerSingleFrame;
import ch.unizh.ini.jaer.projects.npp.TargetLabeler;
import ch.unizh.ini.jaer.projects.npp.TargetLabeler.TargetLocation;
import eu.seebetter.ini.chips.DavisChip;
import ml.options.Options;
import ml.options.Options.Multiplicity;
import ml.options.Options.Separator;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.chip.EventExtractor2D;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEFileInputStream;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.EventFilter;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.ImageDisplay;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
import net.sf.jaer.util.avioutput.AVIOutputStream.VideoFormat;
import net.sf.jaer.util.filter.LowpassFilter;
/**
* Writes out AVI movie with DVS time or event slices as AVI frame images with
* desired output resolution
*
* @author Tobi Delbruck
*/
@Description("Writes out AVI movie with DVS constant-number-of-event subsampled 2D histogram slices as AVI frame images with desired output resolution")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class DvsSliceAviWriter extends AbstractAviWriter implements FrameAnnotater {
private DvsFramerSingleFrame dvsFrame = null;
private ApsFrameExtractor frameExtractor = null;
private TargetLabeler targetLabeler = null;
private float frameRateEstimatorTimeConstantMs = getFloat("frameRateEstimatorTimeConstantMs", 10f);
private JFrame frame = null;
public ImageDisplay display;
private boolean showOutput;
private volatile boolean newApsFrameAvailable = false;
private int endOfFrameTimestamp = Integer.MIN_VALUE, lastTimestamp = 0;
protected boolean writeDvsSliceImageOnApsFrame = getBoolean("writeDvsSliceImageOnApsFrame", false);
protected boolean writeDvsFrames = getBoolean("writeDvsFrames", true);
protected boolean writeApsFrames = getBoolean("writeApsFrames", false);
// protected boolean writeLatestApsDvsTogether = getBoolean("writeLatestApsDvsTogether", false); // happens anyhow since memory of image buffer is never cleared
protected boolean writeAPSDVSToRGChannels = getBoolean("writeAPSDVSToRGChannels", false); // happens anyhow since memory of image buffer is never cleared
private boolean writeTargetLocations = getBoolean("writeTargetLocations", true);
private boolean writeDvsEventsToTextFile = getBoolean("writeDvsEventsToTextFile", false);
protected static final String EVENTS_SUFFIX = "-events.txt";
protected FileWriter eventsWriter = null;
protected File eventsFile = null;
protected File targetLocationsFile = null;
private FileWriter targetLocationsWriter = null;
private boolean rendererPropertyChangeListenerAdded = false;
private LowpassFilter lowpassFilter = new LowpassFilter(frameRateEstimatorTimeConstantMs);
private int lastDvsFrameTimestamp = 0;
private float avgDvsFrameIntervalMs = 0;
private boolean showStatistics = getBoolean("showStatistics", false);
private String TARGETS_LOCATIONS_SUFFIX = "-targetLocations.txt";
private String APS_OUTPUT_SUFFIX = "-aps.avi";
private String DVS_OUTPUT_SUFFIX = "-dvs.avi"; // used for separate output option
private BufferedImage aviOutputImage = null; // holds either dvs or aps or both iamges
public DvsSliceAviWriter(AEChip chip) {
super(chip);
FilterChain chain = new FilterChain(chip);
if (chip instanceof DavisChip) {
frameExtractor = new ApsFrameExtractor(chip);
chain.add(frameExtractor);
frameExtractor.getSupport().addPropertyChangeListener(this);
}
targetLabeler = new TargetLabeler(chip);
chain.add(targetLabeler);
dvsFrame = new DvsFramerSingleFrame(chip);
chain.add(dvsFrame);
setEnclosedFilterChain(chain);
showOutput = getBoolean("showOutput", true);
DEFAULT_FILENAME = "DvsEventSlices.avi";
setPropertyTooltip("showOutput", "shows output in JFrame/ImageDisplay");
setPropertyTooltip("frameRateEstimatorTimeConstantMs", "time constant of lowpass filter that shows average DVS slice frame rate");
setPropertyTooltip("writeDvsSliceImageOnApsFrame", "<html>write DVS slice image for each APS frame end event (dvsMinEvents ignored).<br>The frame is written at the end of frame APS event.<br><b>Warning: to capture all frames, ensure that playback time slices are slow enough that all frames are rendered</b>");
setPropertyTooltip("writeApsFrames", "<html>write APS frames to file. Frame is written to LEFT half of image if DVS frames also on.<br><b>Warning: to capture all frames, ensure that playback time slices are slow enough that all frames are rendered</b>");
setPropertyTooltip("writeDvsFrames", "<html>write DVS frames to file. Frame is written to RIGHT half of image if APS frames also on.<br>");
// setPropertyTooltip("writeLatestApsDvsTogether", "<html>If writeDvsFrames and writeApsFrames, ,<br>duplicate most recent frame from each modality in each AVI file output frame. <br>If off, other half frame is black (all zeros|)<br>");
setPropertyTooltip("writeAPSDVSToRGChannels", "<html>If writeDvsFrames and writeApsFrames, ,<br>writes to RG of RGB channels on single frame size output. <br>If off, outputs are written to left (APS) and right (DVS)<br>");
setPropertyTooltip("writeTargetLocations", "<html>If TargetLabeler has locations, write them to a file named XXX-targetlocations.txt<br>");
setPropertyTooltip("writeDvsEventsToTextFile", "<html>write DVS events to text file, one event per line, timestamp, x, y, pol<br>");
setPropertyTooltip("showStatistics", "shows statistics of DVS frame (most off and on counts, frame rate, sparsity)");
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
// frameExtractor.filterPacket(in); // extracts frames with nornalization (brightness, contrast) and sends to apsNet on each frame in PropertyChangeListener
// send DVS timeslice to convnet
super.filterPacket(in);
if (frameExtractor != null) {
frameExtractor.filterPacket(in); // process frame extractor, target labeler and dvsframer
}
if (targetLabeler != null) {
targetLabeler.filterPacket(in);
}
dvsFrame.checkParameters();
if (aviOutputImage == null || aviOutputImage.getWidth() != getOutputImageWidth() || aviOutputImage.getHeight() != getOutputImageHeight()) {
aviOutputImage = new BufferedImage(getOutputImageWidth(),
dvsFrame.getOutputImageHeight(), BufferedImage.TYPE_INT_BGR);
}
checkSubsampler();
for (BasicEvent e : in) {
if (e.isSpecial() || e.isFilteredOut()) {
continue;
}
PolarityEvent p = (PolarityEvent) e;
lastTimestamp = e.timestamp;
dvsFrame.addEvent(p);
try {
writeEvent(p);
} catch (IOException ex) {
Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex);
doCloseFile();
}
if ((writeDvsSliceImageOnApsFrame && newApsFrameAvailable && (e.timestamp >= endOfFrameTimestamp))
|| ((!writeDvsSliceImageOnApsFrame && dvsFrame.getDvsFrame().isFilled())
&& ((chip.getAeViewer() == null) || !chip.getAeViewer().isPaused()))) { // added check for nonnull aeviewer in case filter is called from separate program
if (writeDvsSliceImageOnApsFrame) {
newApsFrameAvailable = false;
}
dvsFrame.normalizeFrame();
maybeShowOutput(dvsFrame);
if (isWriteDvsFrames() && (getAviOutputStream() != null) && isWriteEnabled()) {
BufferedImage bi = toImage(dvsFrame);
try {
writeTimecode(e.timestamp);
writeTargetLocation(e.timestamp, framesWritten);
getAviOutputStream().writeFrame(bi);
incrementFramecountAndMaybeCloseOutput();
} catch (IOException ex) {
doCloseFile();
log.warning(ex.toString());
ex.printStackTrace();
setFilterEnabled(false);
}
}
// dvsFrame.clear(); // already cleared by next event when next event added
if (lastDvsFrameTimestamp != 0) {
int lastFrameInterval = lastTimestamp - lastDvsFrameTimestamp;
avgDvsFrameIntervalMs = 1e-3f * lowpassFilter.filter(lastFrameInterval, lastTimestamp);
}
lastDvsFrameTimestamp = lastTimestamp;
}
}
if (writeDvsSliceImageOnApsFrame && ((lastTimestamp - endOfFrameTimestamp) > 1000000)) {
log.warning("last frame event was received more than 1s ago; maybe you need to enable Display Frames in the User Control Panel?");
}
return in;
}
public DvsFramerSingleFrame getDvsFrame() {
return dvsFrame;
}
@Override
public void annotate(GLAutoDrawable drawable) {
if (dvsFrame == null) {
return;
}
if (!isShowStatistics()) {
return;
}
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .8f);
MultilineAnnotationTextRenderer.setScale(.3f);
float avgFrameRate = avgDvsFrameIntervalMs == 0 ? Float.NaN : 1000 / avgDvsFrameIntervalMs;
String s = null;
if (dvsFrame.isNormalizeFrame()) {
s = String.format("mostOffCount=%d\n mostOnCount=%d\navg frame rate=%.1f\nsparsity=%.2f%%", dvsFrame.getMostOffCount(), dvsFrame.getMostOnCount(), avgFrameRate, 100 * dvsFrame.getSparsity());
} else {
s = String.format("mostOffCount=%d\n mostOnCount=%d\navg frame rate=%.1f", dvsFrame.getMostOffCount(), dvsFrame.getMostOnCount(), avgFrameRate);
}
MultilineAnnotationTextRenderer.renderMultilineString(s);
}
@Override
public synchronized void doStartRecordingAndSaveAVIAs() {
String[] s = {
"width=" + dvsFrame.getOutputImageWidth(),
"height=" + dvsFrame.getOutputImageHeight(),
"timeslicemethod=" + dvsFrame.getTimeSliceMethod().toString(),
"grayScale=" + dvsFrame.getDvsGrayScale(),
"normalize=" + dvsFrame.isNormalizeFrame(),
"normalizeDVSForZsNullhop=" + dvsFrame.isNormalizeDVSForZsNullhop(),
"dvsMinEvents=" + dvsFrame.getDvsEventsPerFrame(),
"timeDurationUsPerFrame=" + dvsFrame.getTimeDurationUsPerFrame(),
"format=" + format.toString(),
"compressionQuality=" + compressionQuality
};
setAdditionalComments(s);
if (getAviOutputStream() != null) {
JOptionPane.showMessageDialog(null, "AVI output stream is already opened");
return;
}
JFileChooser c = new JFileChooser(lastFile);
c.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".avi");
}
@Override
public String getDescription() {
return "AVI (Audio Video Interleave) Microsoft video file";
}
});
c.setSelectedFile(new File(lastFileName));
int ret = c.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
// above chooses base filename. Now we need to see if we just write to this file, or make two files for separate DVS and APS outputs
if (!c.getSelectedFile().getName().toLowerCase().endsWith(".avi")) {
String newName = c.getSelectedFile().toString() + ".avi";
c.setSelectedFile(new File(newName));
}
lastFileName = c.getSelectedFile().toString();
if (c.getSelectedFile().exists()) {
int r = JOptionPane.showConfirmDialog(null, "File " + c.getSelectedFile().toString() + " already exists, overwrite it?");
if (r != JOptionPane.OK_OPTION) {
return;
}
}
lastFile = c.getSelectedFile();
setAviOutputStream(openAVIOutputStream(c.getSelectedFile(), getAdditionalComments()));
openEventsTextFile(c.getSelectedFile(), getAdditionalComments());
openTargetLabelsFile(c.getSelectedFile(), getAdditionalComments());
if (isRewindBeforeRecording()) {
ignoreRewinwdEventFlag = true;
chip.getAeViewer().getAePlayer().rewind();
ignoreRewinwdEventFlag = true;
}
}
private int getOutputImageWidth() {
return (!isWriteAPSDVSToRGChannels() && isWriteApsFrames() && isWriteDvsFrames()) ? dvsFrame.getOutputImageWidth() * 2 : dvsFrame.getOutputImageWidth(); // 2X wide if both outputs and not RG channels
}
private int getOutputImageHeight() {
return dvsFrame.getOutputImageHeight();
// return (isWriteApsFrames() && isWriteDvsFrames()) ? dvsFrame.getOutputImageHeight() : dvsFrame.getOutputImageHeight(); // same height if both outputs on or not
}
private int getDvsStartingX() {
return (!isWriteAPSDVSToRGChannels() && isWriteApsFrames() && isWriteDvsFrames()) ? dvsFrame.getOutputImageWidth() : 0;
}
protected void writeEvent(PolarityEvent e) throws IOException {
if (eventsWriter != null) {
eventsWriter.write(String.format("%d,%d,%d,%d\n", e.timestamp, e.x, e.y, e.getPolaritySignum()));
}
}
private void openTargetLabelsFile(File f, String[] additionalComments) {
if (writeTargetLocations) {
try {
String s = null;
if (f.toString().lastIndexOf(".") == -1) {
s = f.toString() + TARGETS_LOCATIONS_SUFFIX;
} else {
s = f.toString().subSequence(0, f.toString().lastIndexOf(".")).toString() + TARGETS_LOCATIONS_SUFFIX;
}
targetLocationsFile = new File(s);
targetLocationsWriter = new FileWriter(targetLocationsFile);
targetLocationsWriter.write(String.format("# labeled target locations file\n"));
targetLocationsWriter.write(String.format("# written %s\n", new Date().toString()));
if (additionalComments != null) {
for (String st : additionalComments) {
if (!st.startsWith("
st = "
}
if (!st.endsWith("\n")) {
st = st + "\n";
}
targetLocationsWriter.write(st);
}
}
targetLocationsWriter.write(String.format("# frameNumber timestamp x y targetTypeID width height\n"));
log.info("Opened labeled target locations file " + targetLocationsFile.toString());
} catch (IOException ex) {
Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void openEventsTextFile(File f, String[] additionalComments) {
if (writeDvsEventsToTextFile) {
try {
String s = null;
if (f.toString().lastIndexOf(".") == -1) {
s = f.toString() + EVENTS_SUFFIX;
} else {
s = f.toString().subSequence(0, f.toString().lastIndexOf(".")).toString() + EVENTS_SUFFIX;
}
eventsFile = new File(s);
eventsWriter = new FileWriter(eventsFile);
eventsWriter.write(String.format("# events file\n"));
eventsWriter.write(String.format("# written %s\n", new Date().toString()));
if (additionalComments != null) {
for (String st : additionalComments) {
if (!st.startsWith("
st = "
}
if (!st.endsWith("\n")) {
st = st + "\n";
}
eventsWriter.write(st);
}
}
eventsWriter.write(String.format("# timestamp,x,y,pol\n"));
log.info("Opened events file " + eventsFile.toString());
} catch (IOException ex) {
Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public synchronized void doCloseFile() {
setWriteEnabled(false);
if (eventsWriter != null) {
try {
eventsWriter.close();
log.info("Closed events file " + eventsFile.toString());
eventsWriter = null;
} catch (IOException ex) {
Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (targetLocationsWriter != null) {
try {
targetLocationsWriter.close();
log.info("Closed target locations file " + targetLocationsFile.toString());
targetLocationsWriter = null;
} catch (IOException ex) {
Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex);
} finally {
targetLocationsWriter = null;
}
}
if (timecodeWriter != null) {
try {
timecodeWriter.close();
log.info("Closed timecode file " + timecodeFile.toString());
} catch (IOException ex) {
Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex);
} finally {
timecodeWriter = null;
}
}
super.doCloseFile();
}
private void checkSubsampler() {
}
private BufferedImage toImage(DvsFramerSingleFrame dvsFramer) {
if (aviOutputImage == null) {
throw new RuntimeException("null aviOutputImage; output has not yet been opened");
}
int[] bd = ((DataBufferInt) aviOutputImage.getRaster().getDataBuffer()).getData();
final int dvsOutputImageHeight = dvsFrame.getOutputImageHeight();
final int dvsOutputImageWidth = dvsFrame.getOutputImageWidth();
final int dvsStartingX = getDvsStartingX();
final int outputImageWidth = getOutputImageWidth();
final boolean rg = isWriteAPSDVSToRGChannels();
for (int y = 0; y < dvsOutputImageHeight; y++) {
for (int x = 0; x < dvsOutputImageWidth; x++) {
int g = (int) (255 * dvsFramer.getValueAtPixel(x, y));
int b = rg ? 0 : g;
int r = rg ? 0 : g;
int idx = ((dvsOutputImageHeight - y - 1) * outputImageWidth) + x + dvsStartingX; // DVS image is right half if both on
if (idx >= bd.length) {
throw new RuntimeException(String.format("index %d out of bounds for x=%d y=%d", idx, x, y));
}
if (!rg) {
bd[idx] = (b << 16) | (g << 8) | r | 0xFF000000; // if RG combined output, mask to just overwrite green channel
} else {
bd[idx] &= (~(0xFF << 8)); // clear G channel
bd[idx] |= (g << 8); // just G channel overwritten
}
}
}
return aviOutputImage;
}
private BufferedImage toImage(ApsFrameExtractor frameExtractor) {
if (aviOutputImage == null) {
throw new RuntimeException("aviOutputImage is null, was not initialized");
}
int[] bd = ((DataBufferInt) aviOutputImage.getRaster().getDataBuffer()).getData();
int srcwidth = chip.getSizeX(), srcheight = chip.getSizeY();
final int dvsOutputImageWidth = dvsFrame.getOutputImageWidth();
final int outputImageHeight = dvsFrame.getOutputImageHeight();
final int outputImageWidth = getOutputImageWidth();
float[] frame = frameExtractor.getNewFrame();
final boolean rg = isWriteAPSDVSToRGChannels();
for (int y = 0; y < outputImageHeight; y++) {
for (int x = 0; x < dvsOutputImageWidth; x++) {
int xsrc = (int) Math.floor((x * (float) srcwidth) / dvsOutputImageWidth), ysrc = (int) Math.floor((y * (float) srcheight) / outputImageHeight);
int r = (int) (255 * frame[frameExtractor.getIndex(xsrc, ysrc)]); // TODO simplest possible downsampling, can do better with linear or bilinear interpolation but code more complex
int g = rg ? 0 : r;
int b = rg ? 0 : r;
int idx = ((outputImageHeight - y - 1) * outputImageWidth) + x + 0; // aps image is left half if combined
if (idx >= bd.length) {
throw new RuntimeException(String.format("index %d out of bounds for x=%d y=%d", idx, x, y));
}
if (!rg) {
bd[idx] = (b << 16) | (g << 8) | r | 0xFF000000;
}else{
bd[idx] &= ~0xFF; // clear red channel
bd[idx] |= r | 0xFF000000;
}
}
}
return aviOutputImage;
}
synchronized public void maybeShowOutput(DvsFramerSingleFrame dvsFramer) {
if (!showOutput) {
return;
}
if (frame == null) {
String windowName = "DVS slice";
frame = new JFrame(windowName);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
display = ImageDisplay.createOpenGLCanvas();
display.setBorderSpacePixels(10);
display.setImageSize(dvsFrame.getOutputImageWidth(), dvsFrame.getOutputImageHeight());
display.setSize(200, 200);
panel.add(display);
frame.getContentPane().add(panel);
frame.pack();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowOutput(false);
}
});
}
if (!frame.isVisible()) {
frame.setVisible(true);
}
if ((display.getWidth() != dvsFrame.getOutputImageWidth()) || (display.getHeight() != dvsFrame.getOutputImageHeight())) {
display.setImageSize(dvsFrame.getOutputImageWidth(), dvsFrame.getOutputImageHeight());
}
for (int x = 0; x < dvsFrame.getOutputImageWidth(); x++) {
for (int y = 0; y < dvsFrame.getOutputImageHeight(); y++) {
display.setPixmapGray(x, y, dvsFramer.getValueAtPixel(x, y));
}
}
display.repaint();
}
/**
* @return the showOutput
*/
public boolean isShowOutput() {
return showOutput;
}
/**
* @param showOutput the showOutput to set
*/
public void setShowOutput(boolean showOutput) {
boolean old = this.showOutput;
this.showOutput = showOutput;
putBoolean("showOutput", showOutput);
getSupport().firePropertyChange("showOutput", old, showOutput);
}
/**
* @return the writeDvsSliceImageOnApsFrame
*/
public boolean isWriteDvsSliceImageOnApsFrame() {
return writeDvsSliceImageOnApsFrame;
}
/**
* @param writeDvsSliceImageOnApsFrame the writeDvsSliceImageOnApsFrame to
* set
*/
public void setWriteDvsSliceImageOnApsFrame(boolean writeDvsSliceImageOnApsFrame) {
this.writeDvsSliceImageOnApsFrame = writeDvsSliceImageOnApsFrame;
putBoolean("writeDvsSliceImageOnApsFrame", writeDvsSliceImageOnApsFrame);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt);
if ((evt.getPropertyName() == ApsFrameExtractor.EVENT_NEW_FRAME)) {
endOfFrameTimestamp = frameExtractor.getLastFrameTimestamp();
newApsFrameAvailable = true;
if (isWriteApsFrames() && (getAviOutputStream() != null) && isWriteEnabled()
&& ((chip.getAeViewer() == null) || !chip.getAeViewer().isPaused())) {
BufferedImage bi = toImage(frameExtractor);
try {
writeTimecode(endOfFrameTimestamp);
writeTargetLocation(endOfFrameTimestamp, framesWritten);
getAviOutputStream().writeFrame(bi);
incrementFramecountAndMaybeCloseOutput();
} catch (IOException ex) {
log.warning(ex.toString());
ex.printStackTrace();
setFilterEnabled(false);
}
}
}
}
/**
* @return the frameRateEstimatorTimeConstantMs
*/
public float getFrameRateEstimatorTimeConstantMs() {
return frameRateEstimatorTimeConstantMs;
}
/**
* @param frameRateEstimatorTimeConstantMs the
* frameRateEstimatorTimeConstantMs to set
*/
public void setFrameRateEstimatorTimeConstantMs(float frameRateEstimatorTimeConstantMs) {
this.frameRateEstimatorTimeConstantMs = frameRateEstimatorTimeConstantMs;
lowpassFilter.setTauMs(frameRateEstimatorTimeConstantMs);
putFloat("frameRateEstimatorTimeConstantMs", frameRateEstimatorTimeConstantMs);
}
public static final String USAGE = "java DvsSliceAviWriter \n"
+ " [-aechip=aechipclassname (either shortcut dvs128, davis240c or davis346mini, or fully qualified class name, e.g. eu.seebetter.ini.chips.davis.DAVIS240C)] \n"
+ " [-width=36] [-height=36] [-quality=.9] [-format=PNG|JPG|RLE|RAW] [-framerate=30] [-grayscale=200] \n"
+ " [-writedvssliceonapsframe=false] \n"
+ " [-writetimecodefile=true] \n"
+ " [-writeapsframes=false] \n"
+ " [-writedvsframes=true] \n"
+ " [-writeapstorgchannel=true] \n"
+ " [-writedvseventstotextfile=false] \n"
+ " [-writetargetlocations=false] \n"
+ " [-timeslicemethod=EventCount|TimeIntervalUs] [-numevents=2000] [-framedurationus=10000]\n"
+ " [-rectify=false] [-normalize=true] [-showoutput=true] [-maxframes=0] \n "
+ " [-enablefilters=false] \n"
+ " inputFile.aedat [outputfile.avi]"
+ "\n"
+ "numevents and framedurationus are exclusively possible\n"
+ "Arguments values are assigned with =, not space\n"
+ "If outputfile is not provided its name is generated from the input file with appended .avi";
public static final HashMap<String, String> chipClassesMap = new HashMap();
public static void main(String[] args) {
// make hashmap of common chip classes
boolean enableFilters = false;
chipClassesMap.put("dvs128", "ch.unizh.ini.jaer.chip.retina.DVS128");
chipClassesMap.put("davis240c", "eu.seebetter.ini.chips.davis.DAVIS240C");
chipClassesMap.put("davis346blue", "eu.seebetter.ini.chips.davis.Davis346blue");
chipClassesMap.put("davis346red", "eu.seebetter.ini.chips.davis.Davis346red");
// command line
// uses last settings of everything
// java DvsSliceAviWriter inputFile.aedat outputfile.avi
Options opt = new Options(args, 1, 2);
opt.getSet().addOption("enablefilters", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("aechip", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("width", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("height", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("quality", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("format", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("framerate", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("grayscale", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("writedvssliceonapsframe", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("writedvsframes", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("writeapsframes", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("writeapstorgchannel", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("writedvseventstotextfile", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("writetimecodefile", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("numevents", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("framedurationus", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("timeslicemethod", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("rectify", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("normalize", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("nullhopnormalize", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("showoutput", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("maxframes", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
opt.getSet().addOption("writetargetlocations", Separator.EQUALS, Multiplicity.ZERO_OR_ONE);
if (!opt.check()) {
System.err.println(opt.getCheckErrors());
System.err.println(USAGE);
System.exit(1);
}
if (opt.getSet().getData().isEmpty()) {
System.err.println("no output file specified");
System.exit(1);
}
if (opt.getSet().getData().size() > 2) {
System.err.println("too many input/output file arguments (only one or two allowed)");
System.exit(1);
}
String inpfilename = opt.getSet().getData().get(0);
if (!(inpfilename.toLowerCase().endsWith("aedat"))) {
System.err.println("Warning: Input filename does not end with aedat: " + inpfilename);
}
String outfilename = null;
if (opt.getSet().getData().size() == 2) {
outfilename = opt.getSet().getData().get(1);
} else {
outfilename = inpfilename.substring(0, inpfilename.lastIndexOf(".")) + ".avi";
System.out.println("Writing to output file " + outfilename);
}
AEChip chip = null;
String chipname = null;
if (opt.getSet().isSet("aechip")) {
chipname = opt.getSet().getOption("aechip").getResultValue(0);
} else {
chipname = prefs.get("AEViewer.aeChipClassName", DEFAULT_CHIP_CLASS);
}
try {
String className = chipClassesMap.get(chipname.toLowerCase());
if (className == null) {
className = chipname;
} else {
System.out.println("from " + chipname + " found fully qualified class name " + className);
}
System.out.println("constructing AEChip " + className);
Class chipClass = Class.forName(className);
Constructor<AEChip> constructor = chipClass.getConstructor();
chip = constructor.newInstance((java.lang.Object[]) null);
} catch (Exception ex) {
System.err.println("Could not construct instance of aechip=" + chipname + ": " + ex.toString());
System.exit(1);
}
AEFileInputStream ais = null;
File inpfile = new File(inpfilename);
File outfile = new File(outfilename);
AEPacketRaw aeRaw = null;
final DvsSliceAviWriter writer = new DvsSliceAviWriter(chip);
boolean oldCloseOnRewind = writer.isCloseOnRewind();
writer.setCloseOnRewind(false);
writer.getSupport().addPropertyChangeListener(writer);
// handle options
if (opt.getSet().isSet("width")) {
try {
int n = Integer.parseInt(opt.getSet().getOption("width").getResultValue(0));
writer.getDvsFrame().setOutputImageWidth(n);
} catch (NumberFormatException e) {
System.err.println("Bad width argument: " + e.toString());
System.exit(1);
}
}
if (opt.getSet().isSet("height")) {
try {
int n = Integer.parseInt(opt.getSet().getOption("height").getResultValue(0));
writer.getDvsFrame().setOutputImageHeight(n);
} catch (NumberFormatException e) {
System.err.println("Bad height argument: " + e.toString());
System.exit(1);
}
}
if (opt.getSet().isSet("quality")) {
try {
float f = Float.parseFloat(opt.getSet().getOption("quality").getResultValue(0));
writer.setCompressionQuality(f);
} catch (NumberFormatException e) {
System.err.println("Bad quality argument: " + e.toString());
System.exit(1);
}
}
if (opt.getSet().isSet("format")) {
try {
String type = (opt.getSet().getOption("format").getResultValue(0));
VideoFormat format = VideoFormat.valueOf(type.toUpperCase());
writer.setFormat(format);
} catch (IllegalArgumentException e) {
System.err.println("Bad format argument: " + e.toString() + "; use PNG, JPG, RAW, or RLE");
}
}
if (opt.getSet().isSet("framerate")) {
try {
int n = Integer.parseInt(opt.getSet().getOption("framerate").getResultValue(0));
writer.setFrameRate(n);
} catch (NumberFormatException e) {
System.err.println("Bad framerate argument: " + e.toString());
System.exit(1);
}
}
if (opt.getSet().isSet("grayscale")) {
try {
int n = Integer.parseInt(opt.getSet().getOption("grayscale").getResultValue(0));
writer.getDvsFrame().setDvsGrayScale(n);
} catch (NumberFormatException e) {
System.err.println("Bad grayscale argument: " + e.toString());
System.exit(1);
}
}
if (opt.getSet().isSet("writedvssliceonapsframe")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("writedvssliceonapsframe").getResultValue(0));
writer.setWriteDvsSliceImageOnApsFrame(b);
}
if (opt.getSet().isSet("writetimecodefile")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("writetimecodefile").getResultValue(0));
writer.setWriteDvsSliceImageOnApsFrame(b);
}
if (opt.getSet().isSet("writedvsframes")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("writedvsframes").getResultValue(0));
writer.setWriteDvsFrames(b);
}
if (opt.getSet().isSet("writeapsframes")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("writeapsframes").getResultValue(0));
writer.setWriteApsFrames(b);
}
if (opt.getSet().isSet("writetargetlocations")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("writetargetlocations").getResultValue(0));
writer.setWriteTargetLocations(b);
}
if (opt.getSet().isSet("numevents")) {
try {
int n = Integer.parseInt(opt.getSet().getOption("numevents").getResultValue(0));
writer.getDvsFrame().setDvsEventsPerFrame(n);
} catch (NumberFormatException e) {
System.err.println("Bad numevents argument: " + e.toString());
System.exit(1);
}
}
if (opt.getSet().isSet("framedurationus")) {
try {
int n = Integer.parseInt(opt.getSet().getOption("framedurationus").getResultValue(0));
writer.getDvsFrame().setTimeDurationUsPerFrame(n);
} catch (NumberFormatException e) {
System.err.println("Bad numevents argument: " + e.toString());
System.exit(1);
}
}
if (opt.getSet().isSet("timeslicemethod")) {
try {
String methodName = opt.getSet().getOption("timeslicemethod").getResultValue(0);
TimeSliceMethod method = TimeSliceMethod.valueOf(methodName);
writer.getDvsFrame().setTimeSliceMethod(method);
} catch (Exception e) {
System.err.println("Bad timeslicemethod argument: " + e.toString() + "; use EventCount or TimeIntervalUs");
System.exit(1);
}
}
if (opt.getSet().isSet("rectify")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("rectify").getResultValue(0));
writer.getDvsFrame().setRectifyPolarities(b);
}
if (opt.getSet().isSet("writeapstorgchannel")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("writeapstorgchannel").getResultValue(0));
writer.setWriteAPSDVSToRGChannels(b);
}
if (opt.getSet().isSet("normalize")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("normalize").getResultValue(0));
writer.getDvsFrame().setNormalizeFrame(b);
}
if (opt.getSet().isSet("nullhopnormalize")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("nullhopnormalize").getResultValue(0));
writer.getDvsFrame().setNormalizeDVSForZsNullhop(b);
}
if (opt.getSet().isSet("showoutput")) {
boolean b = Boolean.parseBoolean(opt.getSet().getOption("showoutput").getResultValue(0));
writer.setShowOutput(b);
}
if (opt.getSet().isSet("enablefilters")) {
enableFilters = Boolean.parseBoolean(opt.getSet().getOption("enablefilters").getResultValue(0));
} else {
writer.setMaxFrames(0);
}
if (opt.getSet().isSet("maxframes")) {
try {
int n = Integer.parseInt(opt.getSet().getOption("maxframes").getResultValue(0));
writer.setMaxFrames(n);
} catch (NumberFormatException e) {
System.err.println("Bad maxframes argument: " + e.toString());
System.exit(1);
}
} else {
writer.setMaxFrames(0);
}
writer.openAVIOutputStream(outfile, args);
int lastNumFramesWritten = 0, numPrinted = 0;
try {
ais = new AEFileInputStream(inpfile, chip);
ais.getSupport().addPropertyChangeListener(writer); // get informed about rewind events
} catch (IOException ex) {
System.err.println("Couldn't open file " + inpfile + " from working directory " + System.getProperty("user.dir") + " : " + ex.toString());
System.exit(1);
}
EventExtractor2D extractor = chip.getEventExtractor();
System.out.println(String.format("Frames written: "));
FilterChain filterChain = chip.getFilterChain();
if (filterChain != null && enableFilters) {
for (EventFilter f : filterChain) {
f.setPreferredEnabledState();
}
}
// need an object here to register as propertychange listener for the rewind event
// generated when reading the file and getting to the end,
// since the AEFileInputStream will not generate end of file exceptions
final WriterControl writerControl = new WriterControl();
PropertyChangeListener rewindListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
if (pce.getPropertyName() == AEInputStream.EVENT_EOF) {
writerControl.end();
}
}
};
ais.getSupport().addPropertyChangeListener(rewindListener);
ais.setNonMonotonicTimeExceptionsChecked(false); // to avoid wrap and big wrap exceptions, possibly, in long recordings
while (writerControl.writing) {
try {
aeRaw = ais.readPacketByNumber(writer.getDvsFrame().getDvsEventsPerFrame()); // read at most this many events to avoid writing duplicate frames at end of movie from start of file, which would happen automatically by
EventPacket cooked = extractor.extractPacket(aeRaw);
if (enableFilters && filterChain != null) {
cooked = chip.getFilterChain().filterPacket(cooked);
}
writer.filterPacket(cooked);
int numFramesWritten = writer.getFramesWritten();
if (numFramesWritten >= (lastNumFramesWritten + 500)) {
lastNumFramesWritten = numFramesWritten;
System.out.println(String.format("%d frames", numFramesWritten));
}
if ((writer.getMaxFrames() > 0) && (writer.getFramesWritten() >= writer.getMaxFrames())) {
break;
}
} catch (IOException e) {
e.printStackTrace();
try {
System.err.println("IOException: " + e.getMessage());
if (ais != null) {
ais.close();
}
if (writer != null) {
writer.doCloseFile();
}
System.exit(1);
} catch (Exception e3) {
System.err.println("Exception closing file: " + e3.getMessage());
System.exit(1);
}
}
} // end of loop to read and write file
try {
ais.close();
} catch (IOException ex) {
System.err.println("exception closing file: " + ex.toString());
}
writer.setShowOutput(false);
writer.setCloseOnRewind(oldCloseOnRewind);
writer.doCloseFile();
System.out.println(String.format("Settings: aechip=%s\nwidth=%d height=%d quality=%f format=%s framerate=%d grayscale=%d\n"
+ "writeapsframes=%s writedvsframes=%s\n"
+ "writedvssliceonapsframe=%s writetimecodefile=%s\n"
+ "timeslicemethod=%s numevents=%d framedurationus=%d\n"
+ " rectify=%s normalize=%s nullhopnormalize=%s showoutput=%s maxframes=%d",
chipname, writer.getDvsFrame().getOutputImageWidth(), writer.getDvsFrame().getOutputImageHeight(),
writer.getCompressionQuality(), writer.getFormat().toString(),
writer.getFrameRate(), writer.getDvsFrame().getDvsGrayScale(),
writer.isWriteApsFrames(), writer.isWriteDvsFrames(),
writer.isWriteDvsSliceImageOnApsFrame(),
writer.isWriteTimecodeFile(), writer.getDvsFrame().getTimeSliceMethod().toString(),
writer.getDvsFrame().getDvsEventsPerFrame(), writer.getDvsFrame().getTimeDurationUsPerFrame(),
writer.getDvsFrame().isRectifyPolarities(),
writer.getDvsFrame().isNormalizeFrame(),
writer.getDvsFrame().isNormalizeDVSForZsNullhop(),
writer.isShowOutput(), writer.getMaxFrames()));
System.out.println("Successfully wrote file " + outfile + " with " + writer.getFramesWritten() + " frames");
System.exit(0);
}
public boolean isShowStatistics() {
return showStatistics;
}
public void setShowStatistics(boolean showStatistics) {
this.showStatistics = showStatistics;
putBoolean("showStatistics", showStatistics);
}
/**
* Writes the targets just before the timestamp to the target locations
* file, if writeTargetLocation is true
*
* @param timestamp to search for targets just before timestamp
* @throws IOException
*/
private void writeTargetLocation(int timestamp, int frameNumber) throws IOException {
if (!writeTargetLocations) {
return;
}
if (targetLabeler.hasLocations()) {
ArrayList<TargetLabeler.TargetLocation> targets = targetLabeler.findTargetsBeforeTimestamp(timestamp);
if (targets == null) {
// log.warning(String.format("null labeled target locations for timestamp=%d, frameNumber=%d", timestamp, frameNumber));
targetLocationsWriter.write(String.format("%d %d %d -1 -1 -1 -1 -1\n", framesWritten, 0, timestamp));
} else {
try { // TODO debug
for (TargetLocation l : targets) {
if ((l != null) && (l.location != null)) {
// scale locations and size to AVI output resolution
float scaleX = (float) dvsFrame.getOutputImageWidth() / chip.getSizeX();
float scaleY = (float) dvsFrame.getOutputImageHeight() / chip.getSizeY();
targetLocationsWriter.write(String.format("%d %d %d %d %d %d %d %d\n", framesWritten, 0, timestamp, Math.round(scaleX * l.location.x), Math.round(scaleY * l.location.y), l.targetClassID, l.width, l.height));
} else {
targetLocationsWriter.write(String.format("%d %d %d -1 -1 -1 -1 -1\n", framesWritten, 0, timestamp));
}
break; // skip rest of labels, write only 1 per frame
}
} catch (NullPointerException e) {
log.warning("null pointer " + e);
}
}
}
}
// stupid static class just to control writing and handle rewind event
static class WriterControl {
boolean writing = true;
void end() {
writing = false;
}
}
/**
* @return the writeDvsFrames
*/
public boolean isWriteDvsFrames() {
return writeDvsFrames;
}
/**
* @param writeDvsFrames the writeDvsFrames to set
*/
public void setWriteDvsFrames(boolean writeDvsFrames) {
this.writeDvsFrames = writeDvsFrames;
putBoolean("writeDvsFrames", writeDvsFrames);
}
/**
* @return the writeApsFrames
*/
public boolean isWriteApsFrames() {
return writeApsFrames;
}
/**
* @param writeApsFrames the writeApsFrames to set
*/
public void setWriteApsFrames(boolean writeApsFrames) {
this.writeApsFrames = writeApsFrames;
putBoolean("writeApsFrames", writeApsFrames);
}
/**
* @return the writeAPSDVSToRGChannels
*/
public boolean isWriteAPSDVSToRGChannels() {
return writeAPSDVSToRGChannels;
}
/**
* @param writeAPSDVSToRGChannels the writeAPSDVSToRGChannels to set
*/
public void setWriteAPSDVSToRGChannels(boolean writeAPSDVSToRGChannels) {
this.writeAPSDVSToRGChannels = writeAPSDVSToRGChannels;
putBoolean("writeAPSDVSToRGChannels", writeAPSDVSToRGChannels);
}
// /**
// * @return the writeLatestApsDvsTogether
// */
// public boolean isWriteLatestApsDvsTogether() {
// return writeLatestApsDvsTogether;
// /**
// * @param writeLatestApsDvsTogether the writeLatestApsDvsTogether to set
// */
// public void setWriteLatestApsDvsTogether(boolean writeLatestApsDvsTogether) {
// this.writeLatestApsDvsTogether = writeLatestApsDvsTogether;
// putBoolean("writeLatestApsDvsTogether", writeLatestApsDvsTogether);
/**
* @return the writeDvsEventsToTextFile
*/
public boolean isWriteDvsEventsToTextFile() {
return writeDvsEventsToTextFile;
}
/**
* @param writeDvsEventsToTextFile the writeDvsEventsToTextFile to set
*/
public void setWriteDvsEventsToTextFile(boolean writeDvsEventsToTextFile) {
this.writeDvsEventsToTextFile = writeDvsEventsToTextFile;
putBoolean("writeDvsEventsToTextFile", writeDvsEventsToTextFile);
}
/**
* @return the writeTargetLocations
*/
public boolean isWriteTargetLocations() {
return writeTargetLocations;
}
/**
* @param writeTargetLocations the writeTargetLocations to set
*/
public void setWriteTargetLocations(boolean writeTargetLocations) {
this.writeTargetLocations = writeTargetLocations;
putBoolean("writeTargetLocations", writeTargetLocations);
}
} |
package net.sf.mzmine.project.impl;
import java.util.Hashtable;
import java.util.Vector;
import net.sf.mzmine.data.Parameter;
import net.sf.mzmine.data.PeakList;
import net.sf.mzmine.io.RawDataFile;
import net.sf.mzmine.main.MZmineCore;
import net.sf.mzmine.project.MZmineProject;
import net.sf.mzmine.userinterface.mainwindow.ItemSelector;
import net.sf.mzmine.userinterface.mainwindow.MainWindow;
/**
* This class represents a MZmine project. That includes raw data files,
* processed raw data files, peak lists, alignment results....
*/
public class MZmineProjectImpl implements MZmineProject {
private Vector<RawDataFile> projectFiles;
private Vector<PeakList> projectResults;
//private Vector<Parameter> projectParameters;
private Hashtable<Parameter, Hashtable<RawDataFile, Object>> projectParametersAndValues;
private Hashtable<RawDataFile, PeakList> peakLists;
public void addParameter(Parameter parameter) {
if (projectParametersAndValues.containsKey(parameter)) return;
Hashtable<RawDataFile, Object> parameterValues = new Hashtable<RawDataFile, Object>();
projectParametersAndValues.put(parameter, parameterValues);
}
public void removeParameter(Parameter parameter) {
projectParametersAndValues.remove(parameter);
}
public boolean hasParameter(Parameter parameter) {
if (projectParametersAndValues.containsKey(parameter)) return true; else return false;
}
public Parameter[] getParameters() {
return projectParametersAndValues.keySet().toArray(new Parameter[0]);
}
public void setParameterValue(Parameter parameter, RawDataFile rawDataFile, Object value) {
if (!(hasParameter(parameter))) addParameter(parameter);
Hashtable<RawDataFile, Object> parameterValues = projectParametersAndValues.get(parameter);
parameterValues.put(rawDataFile, value);
}
public Object getParameterValue(Parameter parameter, RawDataFile rawDataFile) {
if (!(hasParameter(parameter))) return null;
Object value = projectParametersAndValues.get(parameter).get(rawDataFile);
if (value == null) return parameter.getDefaultValue();
return value;
}
public void addFile(RawDataFile newFile) {
MainWindow mainWindow = (MainWindow) MZmineCore.getDesktop();
ItemSelector itemSelector = mainWindow.getItemSelector();
projectFiles.add(newFile);
itemSelector.addRawData(newFile);
}
public void removeFile(RawDataFile file) {
MainWindow mainWindow = (MainWindow) MZmineCore.getDesktop();
ItemSelector itemSelector = mainWindow.getItemSelector();
projectFiles.remove(file);
itemSelector.removeRawData(file);
}
public void updateFile(RawDataFile oldFile, RawDataFile newFile) {
MainWindow mainWindow = (MainWindow) MZmineCore.getDesktop();
ItemSelector itemSelector = mainWindow.getItemSelector();
projectFiles.remove(oldFile);
peakLists.remove(oldFile);
projectFiles.add(newFile);
itemSelector.replaceRawData(oldFile, newFile);
}
public RawDataFile[] getDataFiles() {
return projectFiles.toArray(new RawDataFile[0]);
}
public void addAlignedPeakList(PeakList newResult) {
MainWindow mainWindow = (MainWindow) MZmineCore.getDesktop();
ItemSelector itemSelector = mainWindow.getItemSelector();
projectResults.add(newResult);
itemSelector.addAlignmentResult(newResult);
}
public void removeAlignedPeakList(PeakList result) {
MainWindow mainWindow = (MainWindow) MZmineCore.getDesktop();
ItemSelector itemSelector = mainWindow.getItemSelector();
projectResults.remove(result);
itemSelector.removeAlignedPeakList(result);
}
public PeakList[] getAlignedPeakLists() {
return projectResults.toArray(new PeakList[0]);
}
public PeakList getFilePeakList(RawDataFile file) {
return peakLists.get(file);
}
public void setFilePeakList(RawDataFile file, PeakList peakList) {
peakLists.put(file, peakList);
}
public void initModule() {
projectFiles = new Vector<RawDataFile>();
projectResults = new Vector<PeakList>();
//projectParameters = new Vector<Parameter>();
projectParametersAndValues = new Hashtable<Parameter, Hashtable<RawDataFile, Object>>();
peakLists = new Hashtable<RawDataFile, PeakList>();
}
} |
package org.biojava.bio.program.abi;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.biojava.bio.BioError;
import org.biojava.bio.chromatogram.AbstractChromatogram;
import org.biojava.bio.chromatogram.Chromatogram;
import org.biojava.bio.chromatogram.UnsupportedChromatogramFormatException;
import org.biojava.bio.seq.DNATools;
import org.biojava.bio.symbol.AtomicSymbol;
import org.biojava.bio.symbol.IllegalAlphabetException;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojava.bio.symbol.IntegerAlphabet;
import org.biojava.bio.symbol.Symbol;
import org.biojava.utils.SmallMap;
public class ABIFChromatogram extends AbstractChromatogram implements Serializable {
public ABIFChromatogram() {
super();
}
/** Create a new ABIF object from a file.
* <p>
* This method is more efficent than {@link #create(InputStream)}.
* </p>
*/
public static ABIFChromatogram create(File f)
throws IOException, UnsupportedChromatogramFormatException {
ABIFChromatogram newOne = new ABIFChromatogram();
newOne.load(f);
return newOne;
}
/**
* Create a new ABIF object from a stream of bytes.
* <p>
* Due to the non-single-pass design of the ABI format, this method will
* wrap the InputStream in an {@link org.biojava.utils.io.CachingInputStream}.
* For this reason, {@link #create(File)} should be preferred.
* </p>
* @param in the stream from which to read
* @return a new ABIFChromatogram object
* @throws IOException if there is a problem with the underlying stream
*/
public static ABIFChromatogram create(InputStream in)
throws IOException, UnsupportedChromatogramFormatException {
ABIFChromatogram newOne = new ABIFChromatogram();
newOne.load(in);
return newOne;
}
protected ABIFChromatogram load(File f)
throws IOException, UnsupportedChromatogramFormatException {
new Parser(f);
return this;
}
protected ABIFChromatogram load(InputStream in)
throws IOException, UnsupportedChromatogramFormatException {
new Parser(in);
return this;
}
protected AbstractChromatogram reverseComplementInstance() {
return new ABIFChromatogram();
}
/**
* An extension of {@link ABIFParser} that reads the particular fields from
* the ABIF that contain the chromatogram data and initializes the fields
* in its enclosing <code>ABIFChromatogram</code> instance.
*/
protected class Parser extends ABIFParser {
public Parser(InputStream in)
throws IOException, UnsupportedChromatogramFormatException {
super(in);
parse();
}
public Parser(File f)
throws IOException, UnsupportedChromatogramFormatException {
super(f);
parse();
}
private final void parse()
throws IOException, UnsupportedChromatogramFormatException {
// read filter-wheel-order tag
char[] fwo_ = new char[4];
ABIFParser.TaggedDataRecord fwoRec = getDataRecord("FWO_", 1);
if (fwoRec == null)
throw new UnsupportedChromatogramFormatException("No FWO_ (1) record in ABIF file, therefore no trace data");
fwo_[0] = (char) ( (fwoRec.dataRecord >>> 24) & 0xff );
fwo_[1] = (char) ( (fwoRec.dataRecord >>> 16) & 0xff );
fwo_[2] = (char) ( (fwoRec.dataRecord >>> 8 ) & 0xff );
fwo_[3] = (char) ( (fwoRec.dataRecord ) & 0xff );
Symbol sym;
clearTraces();
for (int i = 0 ; i < 4 ; i++) {
try {
sym = ABIFParser.decodeDNAToken(fwo_[i]);
} catch (IllegalSymbolException ise) {
throw new UnsupportedChromatogramFormatException("An unexpected character (" + fwo_[i] +") was found in the FWO_ tag. Parsing cannot continue.");
}
if (!(sym instanceof AtomicSymbol)) {
throw new UnsupportedChromatogramFormatException("An unexpected character (" + fwo_[i] +") was found in the FWO_ tag. Parsing cannot continue.");
}
parseTrace((AtomicSymbol) sym, i+9);
}
parseBaseCalls();
getDataAccess().finishedReading();
}
private void parseTrace(AtomicSymbol sym, int whichData) throws IOException, UnsupportedChromatogramFormatException {
TaggedDataRecord dataPtr = getDataRecord("DATA", whichData);
if (dataPtr.numberOfElements > Integer.MAX_VALUE)
throw new UnsupportedChromatogramFormatException("Chromatogram has more than " + Integer.MAX_VALUE + " trace samples -- can't handle it");
int count = (int) dataPtr.numberOfElements;
int[] trace = new int[count];
int max = -1;
setBits(8*dataPtr.elementLength);
if (dataPtr.elementLength == 2) {
byte[] shortArray = dataPtr.offsetData;
int i = 0;
for (int s = 0; s < shortArray.length; s += 2) {
trace[i] = ((short)((shortArray[s] << 8) | (shortArray[s + 1] & 0xff))) & 0xffff;
max = Math.max(trace[i++], max);
}
}
else if (dataPtr.elementLength == 1) {
byte[] byteArray = dataPtr.offsetData;
for (int i = 0; i < byteArray.length; i++) {
trace[i] = byteArray[i] & 0xff;
max = Math.max(trace[i], max);
}
}
else {
throw new UnsupportedChromatogramFormatException("Only 8- and 16-bit trace samples are supported");
}
try {
setTrace(sym, trace, max);
} catch (IllegalSymbolException ise) {
throw new BioError("Can't happen", ise);
}
}
private void parseBaseCalls() throws IOException, UnsupportedChromatogramFormatException {
// do offsets, then call letters
// offsets are in PLOC1 (we'll use the possibly-edited stream)
TaggedDataRecord offsetsPtr = getDataRecord("PLOC", 1);
// call letters are int PBAS1
TaggedDataRecord basesPtr = getDataRecord("PBAS", 1);
// these should be equal, but just in case...
if (offsetsPtr.numberOfElements != basesPtr.numberOfElements)
throw new BioError("PLOC and PBAS are different lengths. Can't proceed.");
if (offsetsPtr.numberOfElements > Integer.MAX_VALUE)
throw new UnsupportedChromatogramFormatException("Chromatogram has more than " + Integer.MAX_VALUE + " base calls -- can't handle it");
int count = (int) offsetsPtr.numberOfElements;
// the list of called bases
List dna = new ArrayList(count);
// the list of offsets
List offsets = new ArrayList(count);
// start reading offsets, creating SimpleBaseCalls along the way
if (offsetsPtr.elementLength == 2) {
byte[] shortArray = offsetsPtr.offsetData;
IntegerAlphabet integerAlphabet = IntegerAlphabet.getInstance();
for (int s = 0; s < shortArray.length; s += 2) {
offsets.add(integerAlphabet.getSymbol(((short)((shortArray[s] << 8) | (shortArray[s + 1] & 0xff))) & 0xffff));
}
}
else if (offsetsPtr.elementLength == 1) {
byte[] byteArray = offsetsPtr.offsetData;
IntegerAlphabet integerAlphabet = IntegerAlphabet.getInstance();
for (int i = 0 ; i < byteArray.length; i++) {
offsets.add(integerAlphabet.getSymbol(byteArray[i] & 0xff));
}
}
else {
throw new IllegalStateException("Only 8- and 16-bit trace samples are supported");
}
// then read the base calls
try {
byte[] byteArray = basesPtr.offsetData;
for (int i = 0; i < byteArray.length; i++) {
dna.add(ABIFParser.decodeDNAToken((char) byteArray[i]));
}
} catch (IllegalSymbolException ise) {
throw new BioError("Can't happen", ise);
}
// create the base call alignment and set it
try {
Map baseCalls = new SmallMap(2);
baseCalls.put(Chromatogram.DNA, createImmutableSymbolList(DNATools.getDNA(), dna));
baseCalls.put(Chromatogram.OFFSETS, createImmutableSymbolList(IntegerAlphabet.getInstance(), offsets));
setBaseCallAlignment(createImmutableAlignment(baseCalls));
} catch (IllegalAlphabetException iae) {
throw new BioError("Can't happen", iae);
} catch (IllegalSymbolException ise) {
throw new BioError("Can't happen", ise);
}
}
}
} |
package org.concord.data.stream;
import java.io.PrintStream;
import org.concord.framework.data.stream.DataConsumer;
import org.concord.framework.data.stream.DataListener;
import org.concord.framework.data.stream.DataProducer;
import org.concord.framework.data.stream.DataStreamEvent;
/**
* @author scytacki
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class PrintingDataConsumer
implements DataConsumer, DataListener
{
PrintStream output= null;
public PrintingDataConsumer(PrintStream output)
{
this.output = output;
}
/* (non-Javadoc)
* @see org.concord.framework.data.stream.DataConsumer#addDataProducer(org.concord.framework.data.stream.DataProducer)
*/
public void addDataProducer(DataProducer source)
{
// TODO Auto-generated method stub
source.addDataListener(this);
}
/* (non-Javadoc)
* @see org.concord.framework.data.stream.DataConsumer#removeDataProducer(org.concord.framework.data.stream.DataProducer)
*/
public void removeDataProducer(DataProducer source) {
// TODO Auto-generated method stub
source.removeDataListener(this);
}
/* (non-Javadoc)
* @see org.concord.framework.data.stream.DataListener#dataReceived(org.concord.framework.data.stream.DataStreamEvent)
*/
public void dataReceived(DataStreamEvent dataEvent) {
DataProducer dataProducer = (DataProducer)dataEvent.getSource();
int numberOfSamples = dataEvent.getNumSamples();
int sampleOffset = dataProducer.getDataDescription().getDataOffset();
int nextSampleOffset = dataProducer.getDataDescription().getNextSampleOffset();
int numChannelsPerSample = dataProducer.getDataDescription().getChannelsPerSample();
for(int i=0; i<numberOfSamples; i++) {
for(int j=0; j<numChannelsPerSample; j++) {
// should take precision into account here
output.print("" + dataEvent.data[sampleOffset + i*nextSampleOffset + j] + "\t");
}
output.println();
}
}
/* (non-Javadoc)
* @see org.concord.framework.data.stream.DataListener#dataStreamEvent(org.concord.framework.data.stream.DataStreamEvent)
*/
public void dataStreamEvent(DataStreamEvent dataEvent)
{
// TODO maybe print out these events.
}
} |
package org.concord.datagraph.state;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.util.EventObject;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.concord.data.Unit;
import org.concord.data.state.OTDataProducer;
import org.concord.data.ui.DataFlowControlAction;
import org.concord.data.ui.DataFlowControlButton;
import org.concord.data.ui.DataFlowControlToolBar;
import org.concord.data.ui.DataStoreLabel;
import org.concord.datagraph.engine.ControllableDataGraphable;
import org.concord.datagraph.engine.DataGraphable;
import org.concord.datagraph.ui.AddDataPointLabelAction;
import org.concord.datagraph.ui.AddDataPointLabelActionExt;
import org.concord.datagraph.ui.AutoScaleAction;
import org.concord.datagraph.ui.DataAnnotation;
import org.concord.datagraph.ui.DataGraph;
import org.concord.datagraph.ui.SingleDataAxisGrid;
import org.concord.framework.data.DataDimension;
import org.concord.framework.data.DataFlow;
import org.concord.framework.data.stream.DataProducer;
import org.concord.framework.data.stream.DataStore;
import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTControllerService;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.view.OTControllerServiceFactory;
import org.concord.framework.otrunk.view.OTViewContext;
import org.concord.framework.util.CheckedColorTreeModel;
import org.concord.framework.util.Copyable;
import org.concord.graph.engine.Graphable;
import org.concord.graph.engine.GraphableList;
import org.concord.graph.engine.SelectableList;
import org.concord.graph.event.GraphableListListener;
import org.concord.graph.examples.GraphWindowToolBar;
import org.concord.graph.ui.GraphTreeView;
import org.concord.graph.ui.Grid2D;
import org.concord.graph.ui.SingleAxisGrid;
import org.concord.graph.util.control.DrawingAction;
import org.concord.swing.SelectableToggleButton;
import org.concord.view.CheckedColorTreeControler;
/**
* @author scott
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class DataGraphManager
implements OTChangeListener, ChangeListener, CheckedColorTreeModel, DataFlow
{
OTDataCollector dataCollector;
OTDataGraph otDataGraph;
DataGraph dataGraph;
DataGraphable sourceGraphable;
DataStoreLabel valueLabel;
OTObjectList labels;
SelectableList notesLayer;
OTDataAxis xOTAxis;
OTDataAxis yOTAxis;
JPanel bottomPanel;
DataFlowControlToolBar toolBar = null;
boolean isCausingOTChange = false;
boolean isCausingRealObjChange = false;
boolean showDataControls;
DataFlowControlButton bStart;
DataFlowControlButton bStop;
DataFlowControlButton bClear;
Color[] colors = {Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, Color.MAGENTA,
Color.ORANGE, Color.PINK, Color.RED, Color.YELLOW, Color.BLACK};
protected OTControllerService controllerService;
private OTViewContext viewContext;
/**
* @param serviceProvider
*
*/
public DataGraphManager(OTDataGraph pfObject, OTViewContext serviceProvider, boolean showDataControls)
{
this.otDataGraph = pfObject;
if(pfObject instanceof OTDataCollector)
dataCollector = (OTDataCollector)pfObject;
this.showDataControls = showDataControls;
this.viewContext = serviceProvider;
initialize();
}
public Object getViewService(Class serviceClass)
{
return viewContext.getViewService(serviceClass);
}
public OTControllerService getControllerService()
{
return controllerService;
}
public DataProducer getSourceDataProducer()
{
// This will return the potential dataProducer of the
// sourceGraphable, this might be different than the current
// dataProducer. This is because of how the producerDataStores
// interact with dataDescriptions coming from their data Producer
OTDataGraphable otSourceGraphable =
(OTDataGraphable) controllerService.getOTObject(sourceGraphable);
if(otSourceGraphable == null){
return null;
}
return getDataProducer(otSourceGraphable);
}
public float getLastValue()
{
if(valueLabel == null) {
return Float.NaN;
}
return valueLabel.getValue();
}
/**
* @return
*/
public JPanel getBottomPanel()
{
return bottomPanel;
}
public DataGraph getDataGraph()
{
return dataGraph;
}
protected OTDataGraph getOTDataGraph()
{
return otDataGraph;
}
public DataFlowControlToolBar getFlowToolBar()
{
return toolBar;
}
public DataFlowControlToolBar createFlowToolBar()
{
DataFlowControlToolBar toolbar =
new DataFlowControlToolBar(false);
bStart = new DataFlowControlButton(DataFlowControlAction.FLOW_CONTROL_START);
toolbar.add(bStart);
bStop = new DataFlowControlButton(DataFlowControlAction.FLOW_CONTROL_STOP);
bStop.setEnabled(false);
toolbar.add(bStop);
bClear = new DataFlowControlButton(DataFlowControlAction.FLOW_CONTROL_RESET);
bClear.setText("Clear");
toolbar.add(bClear);
// The below wrapper is to fix the problem where the dataGraph was reset all of the graphables
// because the datagraph doesn't know which is the selected graphable the DataGraphManager
// needs to take care of the reset. However DataGraphManager already implements DataFlow so
// so it can be used in the case of multiple graph panels.
// FIXME: this should be cleaned up so that DataGraphManager's implementation of DataFlow can be used
// both in the case of the multiple graphs and single graph.
toolbar.addDataFlowObject(new DataFlow(){
public void reset() {
// We bypass the normal dataGraph reset method so only the selected graphable is cleared.
if(sourceGraphable != null){
sourceGraphable.reset();
}
}
public void start() {
dataGraph.start();
}
public void stop() {
dataGraph.stop();
}
});
bStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bClear.setEnabled(true);
bStart.setEnabled(false);
bStop.setEnabled(true);
}
});
bStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bClear.setEnabled(true);
bStart.setEnabled(false);
bStop.setEnabled(false);
}
});
bClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bClear.setEnabled(false);
bStart.setEnabled(true);
bStop.setEnabled(false);
}
});
return toolbar;
}
public void setToolBarEnabled(boolean enabled) {
if(bStart != null) bStart.setEnabled(enabled);
if(bStop != null) bStop.setEnabled(enabled);
if(bClear != null) bClear.setEnabled(enabled);
}
public void setToolbarVisible(boolean visible)
{
GraphWindowToolBar gwToolbar = dataGraph.getToolBar();
if(gwToolbar != null) {
// FIXME
gwToolbar.setVisible(visible);
}
}
public void updateState(Object obj)
{
//If the change was due to the graph area or coordinate system
if (obj == dataGraph.getGraphArea() || obj == dataGraph.getGraphArea().getCoordinateSystem()){
Grid2D grid = dataGraph.getGrid();
xOTAxis.setDoNotifyChangeListeners(false);
yOTAxis.setDoNotifyChangeListeners(false);
xOTAxis.setMin((float)dataGraph.getMinXAxisWorld());
xOTAxis.setMax((float)dataGraph.getMaxXAxisWorld());
yOTAxis.setMin((float)dataGraph.getMinYAxisWorld());
yOTAxis.setMax((float)dataGraph.getMaxYAxisWorld());
SingleAxisGrid sXAxis = grid.getXGrid();
if(sXAxis.getAxisLabel() != null){
xOTAxis.setLabel(sXAxis.getAxisLabel());
}
SingleAxisGrid sYAxis = grid.getYGrid();
if(sYAxis.getAxisLabel() != null){
yOTAxis.setLabel(sYAxis.getAxisLabel());
}
isCausingOTChange = true;
// This is a general notification of a change, not one specific to a property
xOTAxis.notifyOTChange(null, null, null, null);
yOTAxis.notifyOTChange(null, null, null, null);
isCausingOTChange = false;
}
/*
if(obj instanceof DataGraphable) {
OTDataGraphable source = dataCollector.getSource();
source.saveObject(obj);
}
*/
}
/**
* @see org.concord.framework.otrunk.OTChangeListener#stateChanged(org.concord.framework.otrunk.OTChangeEvent)
*/
public void stateChanged(OTChangeEvent e)
{
System.err.println("---- OT state changed "+e.getSource() + " - " + isCausingOTChange+" "+this);
//System.out.println(e.getOperation() +" "+e.getValue());
if(isCausingOTChange) {
// we are the cause of this change
return;
}
if(e.getSource() == xOTAxis || e.getSource() == yOTAxis) {
dataGraph.setLimitsAxisWorld(xOTAxis.getMin(), xOTAxis.getMax(),
yOTAxis.getMin(), yOTAxis.getMax());
}
else if (e.getSource() == otDataGraph){
//OT Data Graph has changed. We need to update the real DataGraph
//Find out what kind of change it is and whether it was a data graphable or a label
if (e.getOperation() == OTChangeEvent.OP_ADD ||
e.getOperation() == OTChangeEvent.OP_REMOVE){
//Graphable added or removed
OTObject otGraphable = (OTObject)e.getValue();
if (e.getProperty().equals("graphables")){
initNewGraphable(otGraphable);
}
else if (e.getProperty().equals("labels")){
initNewLabel(otGraphable);
}
}
}
else if (e.getSource() instanceof OTDataGraphable){
//A OT data graphable changed (not implemented anymore)
/*
if (e.getOperation() == OTChangeEvent.OP_SET){
OTObject otGraphable = (OTObject)e.getSource();
updateGraphable(otGraphable);
}
*/
}
}
/**
* Event triggered by the graph area changing
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
public void stateChanged(ChangeEvent e)
{
//System.out.println("state changed "+e.getSource());
Object source = e.getSource();
updateState(source);
}
public void setSelectedItem(Object item, boolean checked)
{
setSelectedDataGraphable((DataGraphable)item, checked);
}
protected void setSelectedDataGraphable(DataGraphable dg, boolean visible)
{
if(dg == null) {
setToolBarEnabled(false);
return;
}
DataGraphable oldGraphable = sourceGraphable;
sourceGraphable = dg;
updateBottomPanel(oldGraphable, sourceGraphable);
dg.setVisible(visible);
if(dg.isLocked()) {
setToolBarEnabled(false);
} else {
setToolBarEnabled(visible);
}
}
private void removeLabelsFrom(DataGraphable dataGraphable, GraphableList graphables) {
for(int i=0; i<graphables.size(); i++){
Object graphable = graphables.get(i);
if(graphable instanceof DataAnnotation){
if(((DataAnnotation)graphable).getDataGraphable() == dataGraphable){
graphables.remove(i);
continue;
}
}
}
}
public static void setupAxisLabel(SingleDataAxisGrid sAxis, OTDataAxis axis)
{
if(axis.getLabel() != null) {
sAxis.setAxisLabel(axis.getLabel());
}
if(axis.getUnits() != null) {
String unitStr = axis.getUnits();
Unit unit = Unit.findUnit(unitStr);
if(unit == null) {
System.err.println("Can't find unit: " + unitStr);
sAxis.setUnit(new UnknownUnit(unitStr));
}
else {
sAxis.setUnit(unit);
}
}
if (axis.isResourceSet("intervalWorld")){
sAxis.setIntervalFixedWorld(axis.getIntervalWorld());
}
}
public void initialize()
{
OTControllerServiceFactory controllerServiceFactory =
(OTControllerServiceFactory) getViewService(OTControllerServiceFactory.class);
controllerService = controllerServiceFactory.createControllerService();
controllerService.addService(OTViewContext.class, viewContext);
dataGraph = new DataGraph();
if (otDataGraph.isResourceSet("showToolbar") && !otDataGraph.getShowToolbar()){
dataGraph.setToolBar(null);
}
else{
dataGraph.changeToDataGraphToolbar();
}
initGraphables();
dataGraph.setAutoFitMode(DataGraph.AUTO_SCROLL_RUNNING_MODE);
dataGraph.setFocusable(true);
notesLayer = new SelectableList();
dataGraph.getGraph().add(notesLayer);
if (dataGraph.getToolBar() != null){
SelectableToggleButton addNoteButton = new SelectableToggleButton(new AddDataPointLabelAction(notesLayer, dataGraph.getObjList(), dataGraph.getToolBar()));
dataGraph.getToolBar().addButton(addNoteButton, "Add a note to a point in the graph");
//DataPointRuler need to be explicitly enabled to show per Brad's request.
if(dataCollector != null && dataCollector.getRulerEnabled()) {
SelectableToggleButton addNoteButton2 = new SelectableToggleButton(new AddDataPointLabelActionExt(notesLayer, dataGraph.getObjList(), dataGraph.getToolBar()));
dataGraph.getToolBar().addButton(addNoteButton2, "Add a ruler to a point in the graph");
}
//AutoScale need to be explicitly enabled to show per Brad's request.
if(dataCollector != null && dataCollector.getAutoScaleEnabled()) {
JButton autoScaleButton = new JButton(new AutoScaleAction(dataGraph));
JButton autoScaleXButton = new JButton(new AutoScaleAction(AutoScaleAction.AUTOSCALE_X, dataGraph));
JButton autoScaleYButton = new JButton(new AutoScaleAction(AutoScaleAction.AUTOSCALE_Y, dataGraph));
dataGraph.getToolBar().addButton(autoScaleButton, "Autoscale the graph");
dataGraph.getToolBar().addButton(autoScaleXButton, "Autoscale X axis");
dataGraph.getToolBar().addButton(autoScaleYButton, "Autoscale Y axis");
}
KeyStroke keyStroke = KeyStroke.getKeyStroke(new Character('T'), InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK);
dataGraph.getToolBar().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "ShowTree");
dataGraph.getToolBar().getActionMap().put("ShowTree", new AbstractAction(){
/**
* First version of action
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
System.out.println("Got event: " + e);
GraphTreeView gtv = new GraphTreeView();
gtv.setGraph(dataGraph.getGraph());
GraphTreeView.showAsDialog(gtv, "graph tree");
}
});
}
xOTAxis = otDataGraph.getXDataAxis();
xOTAxis.addOTChangeListener(this);
yOTAxis = otDataGraph.getYDataAxis();
yOTAxis.addOTChangeListener(this);
dataGraph.setLimitsAxisWorld(xOTAxis.getMin(), xOTAxis.getMax(),
yOTAxis.getMin(), yOTAxis.getMax());
Grid2D grid = dataGraph.getGrid();
SingleDataAxisGrid sXAxis = (SingleDataAxisGrid)grid.getXGrid();
//DataGraphStateManager.setupAxisLabel(sXAxis, xOTAxis);
setupAxisLabel(sXAxis, xOTAxis);
SingleDataAxisGrid sYAxis = (SingleDataAxisGrid)grid.getYGrid();
//DataGraphStateManager.setupAxisLabel(sYAxis, yOTAxis);
setupAxisLabel(sYAxis, yOTAxis);
dataGraph.setPreferredSize(new Dimension(400,320));
dataGraph.getGraphArea().addChangeListener(this);
otDataGraph.addOTChangeListener(this);
initLabels();
}
protected void initGraphables() {
OTObjectList pfGraphables = otDataGraph.getGraphables();
Vector realGraphables = new Vector();
// for each list item get the data producer object
// add it to the data graph
for(int i=0; i<pfGraphables.size(); i++) {
DataGraphable realGraphable = initNewGraphable((OTObject)pfGraphables.get(i));
realGraphables.add(realGraphable);
}
OTDataGraphable source = null;
if(dataCollector != null){
source = dataCollector.getSource();
}
if(source != null) {
String title = dataCollector.getTitle();
if(title == null) {
title = source.getName();
}
if(title != null) {
dataGraph.setTitle(title);
}
sourceGraphable = (DataGraphable)controllerService.getRealObject(source);
// dProducer.getDataDescription().setDt(0.1f);
if(sourceGraphable instanceof ControllableDataGraphable) {
bottomPanel = new JPanel(new FlowLayout());
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dataGraph.reset();
}
});
DrawingAction a = new DrawingAction();
a.setDrawingObject((ControllableDataGraphable)sourceGraphable);
GraphWindowToolBar gwToolbar = dataGraph.getToolBar();
if (gwToolbar != null){
gwToolbar.addButton(new SelectableToggleButton(a), "Draw a function", 0, false, true);
}
bottomPanel.add(clearButton);
//bottomPanel.add(about);
dataGraph.add(bottomPanel, BorderLayout.SOUTH);
} else if(showDataControls) {
bottomPanel = new JPanel(new FlowLayout());
toolBar = createFlowToolBar();
updateBottomPanel(null, sourceGraphable);
dataGraph.add(bottomPanel, BorderLayout.SOUTH);
}
if(sourceGraphable != null) {
realGraphables.insertElementAt(sourceGraphable, 0);
dataGraph.addDataGraphable(sourceGraphable);
}
}
// If the enabled is not set then the multiple graphable control is
// shown if there is more than one graphable
// If the enabled is set to false then the multiple graphable control
// is not shown even if there is more than one.
// This whole logic should be re-worked
boolean multiAllowed = true;
boolean multiEnabled = false;
if(dataCollector != null) {
boolean multiEnabledSet = dataCollector.isResourceSet("multipleGraphableEnabled");
multiEnabled = dataCollector.getMultipleGraphableEnabled();
if(multiEnabledSet) {
multiAllowed = multiEnabled;
}
}
else{
boolean multiEnabledSet = otDataGraph.isResourceSet("showGraphableList");
if(multiEnabledSet) {
multiEnabled = otDataGraph.getShowGraphableList();
multiAllowed = multiEnabled;
}
}
if(multiEnabled || (multiAllowed && realGraphables.size() > 1 )){
CheckedColorTreeControler dataSetTree = new CheckedColorTreeControler();
JComponent treeComponent = dataSetTree.setup(this, true);
// The source should be the last item because it was setup that
// way above. We want it selected
// This works but there is some strange behavior here.
// the dataSetTree.setup changes the sourceGraphable. because it sets the
// selected to be the first realGraphable.
if(source != null){
dataSetTree.setSelectedRow(realGraphables.size() - 1);
}
dataGraph.add(treeComponent, BorderLayout.WEST);
}
//Listen to the graphable list
GraphableList graphableList = dataGraph.getObjList();
graphableList.addGraphableListListener(new MainLayerGraphableListener());
}
protected void updateBottomPanel(DataGraphable oldSourceGraphable,
DataGraphable newSourceGraphable)
{
if(toolBar == null){
return;
}
Dimension labelSize = null;
Point labelLocation = null;
if(oldSourceGraphable != null) {
// disconnect toolBar from the last data producer
// getting the data producer from the graphable is not always safe
// the graphable stores the dataproducer in its datastore, so
// if the datastore hasn't been updated to use the correct producer
// then this will return the wrong thing
DataProducer oldSourceDataProducer =
oldSourceGraphable.findDataProducer();
toolBar.removeDataFlowObject(oldSourceDataProducer);
labelSize = valueLabel.getSize();
labelLocation = valueLabel.getLocation();
bottomPanel.remove(valueLabel);
bottomPanel.remove(toolBar);
}
// It isn't good to call newSourceGraphable.findDataProducer()
// because the producer might not be set data store of the
// real graphable yet. This setting is delay so previous data stored
// in the datastore does not get messed up.
OTDataGraphable newOTSourceGraphable =
(OTDataGraphable) controllerService.getOTObject(newSourceGraphable);
DataProducer newSourceDataProducer =
getDataProducer(newOTSourceGraphable);
toolBar.addDataFlowObject(newSourceDataProducer);
DataStore dataStore = newSourceGraphable.getDataStore();
if(dataStore.getTotalNumSamples() > 0){
bStart.setEnabled(false);
}
// TODO we need a way to check if the datastore is running or not
// if it is not running then the stop button shoudl be disabled.
valueLabel = new DataStoreLabel(newSourceGraphable, 1);
valueLabel.setColumns(8);
bottomPanel.setLayout(new FlowLayout());
if(oldSourceGraphable != null){
valueLabel.setSize(labelSize);
valueLabel.setLocation(labelLocation);
}
bottomPanel.add(valueLabel);
bottomPanel.add(toolBar);
}
/**
* Called when a new OT graphable was added and we need to create
* a real graphable object for it and add it to the Data Graph
* @param object
* @return the new DataGraphable just added to the Data Graph
*/
protected DataGraphable initNewGraphable(OTObject otGraphable)
{
isCausingRealObjChange = true;
DataGraphable realGraphable =
(DataGraphable)controllerService.getRealObject(otGraphable);
if (realGraphable == null){
System.err.println("Unable to get realGraphable from controllerService");
return null;
}if (realGraphable.getDataProducer() != null){
System.err.println("Trying to display a background graphable with a data producer");
}
dataGraph.addDataGraphable(realGraphable);
//Listen to OT graphable changes (not anymore! the Graphable controller takes care of this)
//((OTDataGraphable)otGraphable).addOTChangeListener(this);
isCausingRealObjChange = false;
return realGraphable;
}
/**
* Called when an OT graphable is changed and we need to update
* the real graphable object too
* @param otGraphable
*/
protected void updateGraphable(OTObject otGraphable)
{
isCausingRealObjChange = true;
DataGraphable realGraphable =
(DataGraphable)controllerService.getRealObject(otGraphable);
//Call loadRealObject on the controller
controllerService.loadRealObject(otGraphable, realGraphable);
isCausingRealObjChange = false;
}
protected void initLabels() {
OTObjectList pfDPLabels = otDataGraph.getLabels();
//Load the data point labels
for (int i=0; i<pfDPLabels.size(); i++){
OTObject obj = pfDPLabels.get(i);
initNewLabel(obj);
}
//Listen to the graphable list
notesLayer.addGraphableListListener(new NotesLayerGraphableListener());
}
/**
* @param obj
*/
private Graphable initNewLabel(OTObject obj)
{
Graphable label = (Graphable)controllerService.getRealObject(obj);
if(label instanceof DataAnnotation) {
((DataAnnotation)label).setGraphableList(dataGraph.getObjList());
}
notesLayer.add(label);
return label;
}
public static class UnknownUnit implements DataDimension
{
String unit;
public UnknownUnit(String unit)
{
this.unit = unit;
}
/* (non-Javadoc)
* @see org.concord.framework.data.DataDimension#getDimension()
*/
public String getDimension()
{
return unit;
}
/* (non-Javadoc)
* @see org.concord.framework.data.DataDimension#setDimension(java.lang.String)
*/
public void setDimension(String dimension)
{
unit = dimension;
}
}
/**
* This should work with Graphable protoypes not
* OTGraphable prototypes that would make it more generally
* useful.
*
* @param name
* @param color
* @param prototype
* @return
* @throws Exception
*/
protected DataGraphable addGraphable(String name, Color color,
OTDataGraphable prototype)
throws Exception
{
OTObjectService service = getOTDataGraph().getOTObjectService();
OTDataGraphable otGraphable = null;
if(prototype == null) {
otGraphable = (OTDataGraphable)service.createObject(OTDataGraphable.class);
DataProducer sourceDataProducer = getSourceDataProducer();
if(sourceDataProducer != null) {
// copy the the producer,
// TODO there might be some way to use the same producer on 2 datastores
// that would be a fall back for un copyable data producers
if(sourceDataProducer instanceof Copyable) {
DataProducer producer =
(DataProducer)((Copyable)sourceDataProducer).getCopy();
setDataProducer(otGraphable, producer);
} else {
System.err.println("Cannot copy the source data producer:\n" +
" " + sourceDataProducer + "\n" +
" It doesn't implement the Copyable interface");
}
}
otGraphable.setDrawMarks(false);
// Might need to set default values for color
// and the name.
} else {
otGraphable = (OTDataGraphable)service.copyObject(prototype, -1);
}
DataGraphable graphable =
(DataGraphable)controllerService.getRealObject(otGraphable);
// I don't know if this should be done or not
if(name != null) {
// This doesn't fire a graphable changed event it should
graphable.setLabel(name);
}
if(color != null) {
graphable.setColor(color);
}
dataGraph.addDataGraphable(graphable);
// adding the graphable to the dataGraph will cause an event to
// be thrown so the ot graphable is added to the ot data graph
// otDataGraph.getGraphables().add(otGraphable);
return graphable;
}
/* (non-Javadoc)
* @see org.concord.framework.util.CheckedColorTreeModel#addItem(java.lang.Object, java.lang.String, java.awt.Color)
*/
public Object addItem(Object parent, String name, Color color)
{
DataGraphable newGraphable = null;
OTObjectList prototypes =
getOTDataGraph().getPrototypeGraphables();
try {
if(prototypes == null || prototypes.size() == 0) {
newGraphable = addGraphable(name, color, null);
} else {
for(int i=0; i<prototypes.size(); i++){
newGraphable = addGraphable(name, color,
(OTDataGraphable)prototypes.get(i));
}
}
} catch(Exception e){
e.printStackTrace();
}
return newGraphable;
}
public Object removeItem(Object parent, Object item)
{
DataGraphable dataGraphable = (DataGraphable)item;
dataGraph.removeDataGraphable(dataGraphable);
// remove any graphables that reference this one in
// either of the 2 graphable lists
removeLabelsFrom(dataGraphable, dataGraph.getObjList());
removeLabelsFrom(dataGraphable, notesLayer);
return null;
}
public void updateItems()
{
getDataGraph().repaint();
}
public Color getItemColor(Object item)
{
return ((DataGraphable)item).getColor();
}
public String getItemLabel(Object item)
{
return ((DataGraphable)item).getLabel();
}
public void setItemLabel(Object item, String label)
{
((DataGraphable)item).setLabel(label);
}
public void setItemChecked(Object item, boolean checked)
{
((DataGraphable)item).setVisible(checked);
}
public String getItemTypeName()
{
return "Data Set";
}
public Vector getItems(Object parent)
{
return (Vector)(dataGraph.getObjList().clone());
}
/**
* This method and the other DataFlow methods are used when there
* are multiple datagraphs.
*/
public void reset()
{
DataProducer sourceDataProducer = getSourceDataProducer();
if(sourceDataProducer == null) {
return;
}
sourceDataProducer.reset();
}
public void stop()
{
DataProducer sourceDataProducer = getSourceDataProducer();
if(sourceDataProducer == null) {
return;
}
sourceDataProducer.stop();
}
public void start()
{
DataProducer sourceDataProducer = getSourceDataProducer();
if(sourceDataProducer == null) {
return;
}
sourceDataProducer.start();
}
public Color getNewColor() {
Color color = null;
Vector graphables = dataGraph.getObjList();
for(int i = 0; i < colors.length; i++) {
color = colors[i];
boolean uniqueColor = true;
for(int j=0; j<graphables.size(); j++) {
Color graphableColor = getItemColor(graphables.get(j));
if(graphableColor.equals(colors[i])){
uniqueColor = false;
break;
}
}
if(uniqueColor) {
break;
}
}
if(color == null) color = Color.BLACK;
return color;
}
public void viewClosed()
{
//Remove all the OT listeners
xOTAxis.removeOTChangeListener(this);
yOTAxis.removeOTChangeListener(this);
otDataGraph.removeOTChangeListener(this);
// This should call dispose on all the controllers that are syncing
// the real objects with the ot objects.
controllerService.dispose();
//Not anymore!
//OTObjectList pfGraphables = otDataGraph.getGraphables();
//for(int i=0; i<pfGraphables.size(); i++) {
// OTChangeNotifying pfGraphable = (OTChangeNotifying)pfGraphables.get(i);
// pfGraphable.removeOTChangeListener(this);
}
class NotesLayerGraphableListener implements GraphableListListener
{
public void listGraphableAdded(EventObject e) {
//Verify we are not triggering this change ourselves
if (!isCausingRealObjChange){
isCausingOTChange = true;
Object obj = e.getSource();
OTObject otObject = controllerService.getOTObject(obj);
otDataGraph.getLabels().add(otObject);
isCausingOTChange = false;
}
}
public void listGraphableChanged(EventObject e) {
// TODO verify this is necessary
// this is just copied from the old code
//Verify we are not triggering this change ourselves
if (!isCausingRealObjChange){
isCausingOTChange = true;
updateState(e.getSource());
isCausingOTChange = false;
}
}
public void listGraphableRemoved(EventObject e) {
//Verify we are not triggering this change ourselves
if (!isCausingRealObjChange){
isCausingOTChange = true;
Object obj = e.getSource();
OTObject otObject = controllerService.getOTObject(obj);
otDataGraph.getLabels().remove(otObject);
isCausingOTChange = false;
}
}
}
class MainLayerGraphableListener implements GraphableListListener
{
public void listGraphableAdded(EventObject e) {
// TODO verify this is doesn't screw up things
//Verify we are not triggering this change ourselves
if (!isCausingRealObjChange){
isCausingOTChange = true;
Object obj = e.getSource();
OTObject otObject = controllerService.getOTObject(obj);
otDataGraph.getGraphables().add(otObject);
isCausingOTChange = false;
}
}
public void listGraphableChanged(EventObject e) {
// TODO verify this is necessary
// this is just copied from the old code
//Verify we are not triggering this change ourselves
if (!isCausingRealObjChange){
isCausingOTChange = true;
updateState(e.getSource());
isCausingOTChange = false;
}
}
public void listGraphableRemoved(EventObject e) {
// TODO verify this is doesn't screw up things
//Verify we are not triggering this change ourselves
if (!isCausingRealObjChange){
isCausingOTChange = true;
Object obj = e.getSource();
OTObject otObject = controllerService.getOTObject(obj);
otDataGraph.getGraphables().remove(otObject);
isCausingOTChange = false;
}
}
}
DataProducer getDataProducer(OTDataGraphable model)
{
OTDataProducer otDataProducer = model.getDataProducer();
return (DataProducer) controllerService.getRealObject(otDataProducer);
}
void setDataProducer(OTDataGraphable model, DataProducer dp)
{
OTDataProducer otDataProducer =
(OTDataProducer) controllerService.getOTObject(dp);
model.setDataProducer(otDataProducer);
}
} |
package org.concord.framework.otrunk;
import java.util.ArrayList;
import org.concord.framework.otrunk.otcore.OTClass;
import org.concord.framework.otrunk.otcore.OTClassProperty;
/**
* This class can be used to create more complex OTObjects.
* The OTObject interface can be used for simple interfaces
* that adhere to the current conventions of the OTrunk.
* If there is an interface that doesn't follow these conventions
* you can extend this class and make an OTResourceSchema
* interface to store the state. The OTrunk will create a
* proxy class that implements this OTResourceSchema.
*
* TODO provide some pointers to examples.
*
* @author scott
*
*/
public class DefaultOTObject
implements OTObject, OTChangeNotifying
{
private OTResourceSchema resources;
public DefaultOTObject(OTResourceSchema resources)
{
this.resources = resources;
}
//public DefaultOTObject(Vector userList) {
// this.userList = userList;
public OTID getGlobalId()
{
return resources.getGlobalId();
}
public String getName()
{
return resources.getName();
}
public void setName(String name)
{
resources.setName(name);
}
/**
* This method can be used by an object to get the object service
* associated with this object. This service can be used for creating
* new objects, and getting objects from ids.
* @return
*/
public OTObjectService getOTObjectService()
{
return resources.getOTObjectService();
}
public void init()
{
}
public OTObject getReferencedObject(String id)
{
OTObjectService objService = resources.getOTObjectService();
OTID linkId = objService.getOTID(id);
if(linkId == null) {
return null;
}
return getReferencedObject(linkId);
}
public OTID getReferencedId(String id)
{
OTObjectService objService = resources.getOTObjectService();
return objService.getOTID(id);
}
public OTObject getReferencedObject(OTID id)
{
try {
OTObjectService objService = resources.getOTObjectService();
return objService.getOTObject(id);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int hashCode()
{
String str = getClass().getName() + "@" + getGlobalId().hashCode();
return str.hashCode();
}
public boolean equals(Object other)
{
if(!(other instanceof OTObject)){
return false;
}
if(this == other) {
return true;
}
if(((OTObject)other).getGlobalId().equals(getGlobalId())) {
System.err.println("compared two ot objects with the same ID but different instances");
return true;
}
return false;
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTChangeNotifying#addOTChangeListener(org.concord.framework.otrunk.OTChangeListener)
*/
public void addOTChangeListener(OTChangeListener listener)
{
resources.addOTChangeListener(listener);
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTChangeNotifying#removeOTChangeListener(org.concord.framework.otrunk.OTChangeListener)
*/
public void removeOTChangeListener(OTChangeListener listener)
{
resources.removeOTChangeListener(listener);
}
public OTClass otClass() {
return resources.otClass();
}
public Object otGet(OTClassProperty property) {
return resources.otGet(property);
}
public boolean otIsSet(OTClassProperty property) {
return resources.otIsSet(property);
}
public void otSet(OTClassProperty property, Object newValue) {
resources.otSet(property, newValue);
}
public void otUnSet(OTClassProperty property) {
resources.otUnSet(property);
}
public String otExternalId()
{
return getOTObjectService().getExternalID(this);
}
public ArrayList getOTChangeListeners() {
return resources.getOTChangeListeners();
}
/**
* This method is mainly for internal use. The ot prefix
* is used so it doesn't conflict with existing methods
* of the same name.
*
* @return
*/
public OTResourceSchema otResourceSchema()
{
return resources;
}
} |
package org.concord.sensor.view;
import javax.swing.JComponent;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.view.AbstractOTView;
import org.concord.framework.otrunk.view.OTActionView;
import org.concord.framework.otrunk.view.OTJComponentView;
import org.concord.framework.otrunk.view.OTViewFactory;
import org.concord.sensor.state.OTLoggingRequest;
import org.concord.sensor.state.OTSetupLogger;
public class OTLoggingRequestView extends AbstractOTView
implements OTJComponentView
{
protected OTLoggingRequest request;
/**
* This should be replaced by a facility
* for creating views from otrunk objects. This would
* be a new type of OTViewEntry that instead of taking
* view class it would take an OTObject and a perhaps a
* path to set a part of that object with the input object
*/
public JComponent getComponent(OTObject otObject, boolean editable)
{
OTViewFactory viewFactory =
(OTViewFactory)getViewService(OTViewFactory.class);
request = (OTLoggingRequest)otObject;
try {
OTObjectService otService = request.getOTObjectService();
ClassLoader cLoader = getClass().getClassLoader();
Class otButtonClass =
cLoader.loadClass("org.concord.otrunk.control.OTButton");
OTObject buttonObj = otService.createObject(otButtonClass);
OTSetupLogger setupObj = (OTSetupLogger)
otService.createObject(OTSetupLogger.class);
setupObj.setRequest(request);
((OTActionView)buttonObj).setAction(setupObj);
return viewFactory.getComponent(buttonObj, null, editable);
} catch (Exception e){
}
return null;
}
public void viewClosed()
{
// TODO Auto-generated method stub
}
} |
package org.eclipse.imp.pdb.facts.impl.fast;
import java.util.Iterator;
import org.eclipse.imp.pdb.facts.IRelation;
import org.eclipse.imp.pdb.facts.ISet;
import org.eclipse.imp.pdb.facts.ITuple;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.exceptions.IllegalOperationException;
import org.eclipse.imp.pdb.facts.impl.util.collections.ShareableValuesHashSet;
import org.eclipse.imp.pdb.facts.impl.util.collections.ShareableValuesList;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.util.RotatingQueue;
import org.eclipse.imp.pdb.facts.util.ShareableHashMap;
import org.eclipse.imp.pdb.facts.util.ValueIndexedHashMap;
import org.eclipse.imp.pdb.facts.visitors.IValueVisitor;
import org.eclipse.imp.pdb.facts.visitors.VisitorException;
/**
* Implementation of IRelation.
*
* @author Arnold Lankamp
*/
/*package*/ class Relation extends Set implements IRelation{
/*package*/ Relation(Type tupleType, ShareableValuesHashSet data){
super(typeFactory.relTypeFromTuple(tupleType), tupleType, data);
}
public Type getFieldTypes(){
return elementType;
}
public int arity(){
return elementType.getArity();
}
public <T> T accept(IValueVisitor<T> v) throws VisitorException{
return v.visitRelation(this);
}
public ISet insert(IValue value){
ShareableValuesHashSet newData = new ShareableValuesHashSet(data);
if(newData.add(value)) {
Type type = elementType.lub(value.getType());
return createSetWriter(type, newData).done();
} else {
return this;
}
}
public IRelation delete(IValue value){
ShareableValuesHashSet newData = new ShareableValuesHashSet(data);
if(newData.remove(value)) {
Type newElementType = TypeFactory.getInstance().voidType();
for(IValue el : newData)
newElementType = newElementType.lub(el.getType());
return new RelationWriter(newElementType, newData).done();
}
else {
return this;
}
}
public IRelation subtract(ISet set){
ShareableValuesHashSet newData = new ShareableValuesHashSet(data);
Iterator<IValue> setIterator = set.iterator();
while(setIterator.hasNext()){
newData.remove(setIterator.next());
}
Type newElementType = TypeFactory.getInstance().voidType();
for(IValue el : newData)
newElementType = newElementType.lub(el.getType());
return new RelationWriter(newElementType, newData).done();
}
private ShareableValuesHashSet computeCarrier(){
ShareableValuesHashSet newData = new ShareableValuesHashSet();
Iterator<IValue> relationIterator = data.iterator();
while(relationIterator.hasNext()){
ITuple tuple = (ITuple) relationIterator.next();
Iterator<IValue> tupleIterator = tuple.iterator();
while(tupleIterator.hasNext()){
newData.add(tupleIterator.next());
}
}
return newData;
}
public ISet carrier(){
ShareableValuesHashSet newData = computeCarrier();
Type type = determainMostGenericTypeInTuple();
return createSetWriter(type, newData).done();
}
public ISet domain(){
ShareableValuesHashSet newData = new ShareableValuesHashSet();
Iterator<IValue> relationIterator = data.iterator();
while(relationIterator.hasNext()){
ITuple tuple = (ITuple) relationIterator.next();
newData.add(tuple.get(0));
}
Type type = elementType.getFieldType(0);
return createSetWriter(type, newData).done();
}
public ISet range(){
ShareableValuesHashSet newData = new ShareableValuesHashSet();
int last = elementType.getArity() - 1;
Iterator<IValue> relationIterator = data.iterator();
while(relationIterator.hasNext()){
ITuple tuple = (ITuple) relationIterator.next();
newData.add(tuple.get(last));
}
Type type = elementType.getFieldType(last);
return createSetWriter(type, newData).done();
}
public IRelation compose(IRelation other){
Type otherTupleType = other.getFieldTypes();
if(elementType == voidType) return this;
if(otherTupleType == voidType) return other;
if(elementType.getArity() != 2 || otherTupleType.getArity() != 2) throw new IllegalOperationException("compose", elementType, otherTupleType);
if(!elementType.getFieldType(1).comparable(otherTupleType.getFieldType(0))) throw new IllegalOperationException("compose", elementType, otherTupleType);
// Index
ShareableHashMap<IValue, ShareableValuesList> rightSides = new ShareableHashMap<IValue, ShareableValuesList>();
Iterator<IValue> otherRelationIterator = other.iterator();
while(otherRelationIterator.hasNext()){
ITuple tuple = (ITuple) otherRelationIterator.next();
IValue key = tuple.get(0);
ShareableValuesList values = rightSides.get(key);
if(values == null){
values = new ShareableValuesList();
rightSides.put(key, values);
}
values.append(tuple.get(1));
}
// Compute
ShareableValuesHashSet newData = new ShareableValuesHashSet();
Type[] newTupleFieldTypes = new Type[]{elementType.getFieldType(0), otherTupleType.getFieldType(1)};
Type tupleType = typeFactory.tupleType(newTupleFieldTypes);
Iterator<IValue> relationIterator = data.iterator();
while(relationIterator.hasNext()){
ITuple thisTuple = (ITuple) relationIterator.next();
IValue key = thisTuple.get(1);
ShareableValuesList values = rightSides.get(key);
if(values != null){
Iterator<IValue> valuesIterator = values.iterator();
do{
IValue value = valuesIterator.next();
IValue[] newTupleData = new IValue[]{thisTuple.get(0), value};
newData.add(new Tuple(tupleType, newTupleData));
}while(valuesIterator.hasNext());
}
}
return new RelationWriter(tupleType, newData).done();
}
private ShareableValuesHashSet computeClosure(Type tupleType){
ShareableValuesHashSet allData = new ShareableValuesHashSet(data);
RotatingQueue<IValue> iLeftKeys = new RotatingQueue<IValue>();
RotatingQueue<RotatingQueue<IValue>> iLefts = new RotatingQueue<RotatingQueue<IValue>>();
ValueIndexedHashMap<RotatingQueue<IValue>> interestingLeftSides = new ValueIndexedHashMap<RotatingQueue<IValue>>();
ValueIndexedHashMap<ShareableValuesHashSet> potentialRightSides = new ValueIndexedHashMap<ShareableValuesHashSet>();
// Index
Iterator<IValue> allDataIterator = allData.iterator();
while(allDataIterator.hasNext()){
ITuple tuple = (ITuple) allDataIterator.next();
IValue key = tuple.get(0);
IValue value = tuple.get(1);
RotatingQueue<IValue> leftValues = interestingLeftSides.get(key);
ShareableValuesHashSet rightValues;
if(leftValues != null){
rightValues = potentialRightSides.get(key);
}else{
leftValues = new RotatingQueue<IValue>();
iLeftKeys.put(key);
iLefts.put(leftValues);
interestingLeftSides.put(key, leftValues);
rightValues = new ShareableValuesHashSet();
potentialRightSides.put(key, rightValues);
}
leftValues.put(value);
rightValues.add(value);
}
int size = potentialRightSides.size();
int nextSize = 0;
// Compute
do{
ValueIndexedHashMap<ShareableValuesHashSet> rightSides = potentialRightSides;
potentialRightSides = new ValueIndexedHashMap<ShareableValuesHashSet>();
for(; size > 0; size
IValue leftKey = iLeftKeys.get();
RotatingQueue<IValue> leftValues = iLefts.get();
RotatingQueue<IValue> interestingLeftValues = null;
IValue rightKey;
while((rightKey = leftValues.get()) != null){
ShareableValuesHashSet rightValues = rightSides.get(rightKey);
if(rightValues != null){
Iterator<IValue> rightValuesIterator = rightValues.iterator();
while(rightValuesIterator.hasNext()){
IValue rightValue = rightValuesIterator.next();
if(allData.add(new Tuple(tupleType, new IValue[]{leftKey, rightValue}))){
if(interestingLeftValues == null){
nextSize++;
iLeftKeys.put(leftKey);
interestingLeftValues = new RotatingQueue<IValue>();
iLefts.put(interestingLeftValues);
}
interestingLeftValues.put(rightValue);
ShareableValuesHashSet potentialRightValues = potentialRightSides.get(rightKey);
if(potentialRightValues == null){
potentialRightValues = new ShareableValuesHashSet();
potentialRightSides.put(rightKey, potentialRightValues);
}
potentialRightValues.add(rightValue);
}
}
}
}
}
size = nextSize;
nextSize = 0;
}while(size > 0);
return allData;
}
public IRelation closure(){
if(elementType == voidType) return this;
if(!isBinary()) {
throw new IllegalOperationException("closure", setType);
}
Type tupleElementType = elementType.getFieldType(0).lub(elementType.getFieldType(1));
Type tupleType = typeFactory.tupleType(tupleElementType, tupleElementType);
return new RelationWriter(elementType, computeClosure(tupleType)).done();
}
public IRelation closureStar(){
if (elementType == voidType) {
return this;
}
if (!isBinary()) {
throw new IllegalOperationException("closureStar", setType);
}
Type tupleElementType = elementType.getFieldType(0).lub(elementType.getFieldType(1));
Type tupleType = typeFactory.tupleType(tupleElementType, tupleElementType);
ShareableValuesHashSet closure = computeClosure(tupleType);
ShareableValuesHashSet carrier = computeCarrier();
Iterator<IValue> carrierIterator = carrier.iterator();
while(carrierIterator.hasNext()){
IValue element = carrierIterator.next();
closure.add(new Tuple(tupleType, new IValue[]{element, element}));
}
return new RelationWriter(elementType, closure).done();
}
public ISet select(int... indexes){
ShareableValuesHashSet newData = new ShareableValuesHashSet();
Iterator<IValue> dataIterator = data.iterator();
while(dataIterator.hasNext()){
ITuple tuple = (ITuple) dataIterator.next();
newData.add(tuple.select(indexes));
}
Type type = getFieldTypes().select(indexes);
return createSetWriter(type, newData).done();
}
public ISet selectByFieldNames(String... fields){
if(!elementType.hasFieldNames()) throw new IllegalOperationException("select with field names", setType);
ShareableValuesHashSet newData = new ShareableValuesHashSet();
Iterator<IValue> dataIterator = data.iterator();
while(dataIterator.hasNext()){
ITuple tuple = (ITuple) dataIterator.next();
newData.add(tuple.selectByFieldNames(fields));
}
Type type = getFieldTypes().select(fields);
return createSetWriter(type, newData).done();
}
public int hashCode(){
return data.hashCode();
}
public boolean equals(Object o){
if(o == this) return true;
if(o == null) return false;
if (isEmpty() && o instanceof Set && ((Set) o).isEmpty()) {
return true;
}
if(o.getClass() == getClass()){
Relation otherRelation = (Relation) o;
if((setType != otherRelation.setType)) return false;
return data.equals(otherRelation.data);
}
return false;
}
private Type determainMostGenericTypeInTuple(){
Type result = elementType.getFieldType(0);
for(int i = elementType.getArity() - 1; i > 0; i
result = result.lub(elementType.getFieldType(i));
}
return result;
}
private boolean isBinary(){
return elementType.getArity() == 2;
}
} |
package com.impossibl.postgres.jdbc;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.TimeZone;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/*
* Tests for time and date types with calendars involved.
* TimestampTest was melting my brain, so I started afresh. -O
*
* Conversions that this code tests:
*
* setTimestamp -> timestamp, timestamptz, date, time, timetz
* setDate -> timestamp, timestamptz, date
* setTime -> time, timetz
*
* getTimestamp <- timestamp, timestamptz, date, time, timetz
* getDate <- timestamp, timestamptz, date
* getTime <- timestamp, timestamptz, time, timetz
*
* (this matches what we must support per JDBC 3.0, tables B-5 and B-6)
*/
@RunWith(JUnit4.class)
public class TimezoneTest {
private static final int DAY = 24 * 3600 * 1000;
private static final TimeZone saveTZ = TimeZone.getDefault();;
private Connection con;
// We set up everything in different timezones to try to exercise many cases:
// default JVM timezone: GMT+0100
// server timezone: GMT+0300
// test timezones: GMT+0000 GMT+0100 GMT+0300 GMT+1300 GMT-0500
private Calendar cUTC;
private Calendar cGMT03;
private Calendar cGMT05;
private Calendar cGMT13;
@Before
public void before() throws Exception {
TimeZone UTC = TimeZone.getTimeZone("UTC"); // +0000 always
TimeZone GMT03 = TimeZone.getTimeZone("GMT+03"); // +0300 always
TimeZone GMT05 = TimeZone.getTimeZone("GMT-05"); // -0500 always
TimeZone GMT13 = TimeZone.getTimeZone("GMT+13"); // +1000 always
cUTC = Calendar.getInstance(UTC);
cGMT03 = Calendar.getInstance(GMT03);
cGMT05 = Calendar.getInstance(GMT05);
cGMT13 = Calendar.getInstance(GMT13);
// We must change the default TZ before establishing the connection.
TimeZone arb = TimeZone.getTimeZone("GMT+01"); // Arbitrary timezone
// that doesn't match
// our test timezones
TimeZone.setDefault(arb);
con = TestUtil.openDB();
TestUtil.createTable(con, "testtimezone", "seq int4, tstz timestamp with time zone, ts timestamp without time zone, t time without time zone, tz time with time zone, d date");
// This is not obvious, but the "gmt-3" timezone is actually 3 hours *ahead*
// of GMT
// so will produce +03 timestamptz output
try (Statement stmt = con.createStatement()) {
stmt.executeUpdate("set timezone = 'GMT-3'");
}
// System.err.println("++++++ TESTS START (" + getName() + ") ++++++");
}
@After
public void after() throws Exception {
// System.err.println("++++++ TESTS END (" + getName() + ") ++++++");
TimeZone.setDefault(saveTZ);
TestUtil.dropTable(con, "testtimezone");
TestUtil.closeDB(con);
}
@Test
public void testGetTimestamp() throws Exception {
try (Statement stmt = con.createStatement()) {
stmt.executeUpdate("INSERT INTO testtimezone(tstz,ts,t,tz,d) VALUES('2005-01-01 15:00:00 +0300', '2005-01-01 15:00:00', '15:00:00', '15:00:00 +0300', '2005-01-01')");
try (ResultSet rs = stmt.executeQuery("SELECT tstz,ts,t,tz,d from testtimezone")) {
assertTrue(rs.next());
checkDatabaseContents("SELECT tstz::text,ts::text,t::text,tz::text,d::text from testtimezone", new String[] {
"2005-01-01 12:00:00+00",
"2005-01-01 15:00:00",
"15:00:00",
"15:00:00+03",
"2005-01-01"});
Timestamp ts;
// timestamptz: 2005-01-01 15:00:00+03
ts = rs.getTimestamp(1); // Represents an instant in time, timezone is irrelevant.
assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
ts = rs.getTimestamp(1, cUTC); // Represents an instant in time, timezone is irrelevant.
assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
ts = rs.getTimestamp(1, cGMT03); // Represents an instant in time, timezone is irrelevant.
assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
ts = rs.getTimestamp(1, cGMT05); // Represents an instant in time, timezone is irrelevant.
assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
ts = rs.getTimestamp(1, cGMT13); // Represents an instant in time, timezone is irrelevant.
assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
// timestamp: 2005-01-01 15:00:00
ts = rs.getTimestamp(2); // Convert timestamp to +0100
assertEquals(1104588000000L, ts.getTime()); // 2005-01-01 15:00:00 +0100
ts = rs.getTimestamp(2, cUTC); // Convert timestamp to UTC
assertEquals(1104591600000L, ts.getTime()); // 2005-01-01 15:00:00 +0000
ts = rs.getTimestamp(2, cGMT03); // Convert timestamp to +0300
assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 15:00:00 +0300
ts = rs.getTimestamp(2, cGMT05); // Convert timestamp to -0500
assertEquals(1104609600000L, ts.getTime()); // 2005-01-01 15:00:00 -0500
ts = rs.getTimestamp(2, cGMT13); // Convert timestamp to +1300
assertEquals(1104544800000L, ts.getTime()); // 2005-01-01 15:00:00 +1300
// time: 15:00:00
ts = rs.getTimestamp(3);
assertEquals(50400000L, ts.getTime()); // 1970-01-01 15:00:00 +0100
ts = rs.getTimestamp(3, cUTC);
assertEquals(54000000L, ts.getTime()); // 1970-01-01 15:00:00 +0000
ts = rs.getTimestamp(3, cGMT03);
assertEquals(43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300
ts = rs.getTimestamp(3, cGMT05);
assertEquals(72000000L, ts.getTime()); // 1970-01-01 15:00:00 -0500
ts = rs.getTimestamp(3, cGMT13);
assertEquals(7200000L, ts.getTime()); // 1970-01-01 15:00:00 +1300
// timetz: 15:00:00+03
ts = rs.getTimestamp(4);
assertEquals(43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 13:00:00 +0100
ts = rs.getTimestamp(4, cUTC);
assertEquals(43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 12:00:00 +0000
ts = rs.getTimestamp(4, cGMT03);
assertEquals(43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 15:00:00 +0300
ts = rs.getTimestamp(4, cGMT05);
assertEquals(43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 07:00:00 -0500
ts = rs.getTimestamp(4, cGMT13);
assertEquals(43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-02 01:00:00 +1300 (CHECK ME)
ts = rs.getTimestamp(5);
assertEquals(1104534000000L, ts.getTime()); // 2005-01-01 00:00:00 +0100
ts = rs.getTimestamp(5, cUTC);
assertEquals(1104537600000L, ts.getTime()); // 2005-01-01 00:00:00 +0000
ts = rs.getTimestamp(5, cGMT03);
assertEquals(1104526800000L, ts.getTime()); // 2005-01-01 00:00:00 +0300
ts = rs.getTimestamp(5, cGMT05);
assertEquals(1104555600000L, ts.getTime()); // 2005-01-01 00:00:00 -0500
ts = rs.getTimestamp(5, cGMT13);
assertEquals(1104490800000L, ts.getTime()); // 2005-01-01 00:00:00 +1300
assertTrue(!rs.next());
}
}
}
@Test
public void testGetDate() throws Exception {
try (Statement stmt = con.createStatement()) {
stmt.executeUpdate("INSERT INTO testtimezone(tstz,ts,d) VALUES('2005-01-01 15:00:00 +0300', '2005-01-01 15:00:00', '2005-01-01')");
try (ResultSet rs = stmt.executeQuery("SELECT tstz,ts,d from testtimezone")) {
assertTrue(rs.next());
checkDatabaseContents("SELECT tstz::text,ts::text,d::text from testtimezone", new String[] {"2005-01-01 12:00:00+00", "2005-01-01 15:00:00", "2005-01-01"});
Date d;
// timestamptz: 2005-01-01 15:00:00+03
d = rs.getDate(1); // 2005-01-01 13:00:00 +0100 -> 2005-01-01 00:00:00 +0100
assertEquals(1104534000000L, d.getTime());
d = rs.getDate(1, cUTC); // 2005-01-01 12:00:00 +0000 -> 2005-01-01 00:00:00 +0000
assertEquals(1104537600000L, d.getTime());
d = rs.getDate(1, cGMT03); // 2005-01-01 15:00:00 +0300 -> 2005-01-01 00:00:00 +0300
assertEquals(1104526800000L, d.getTime());
d = rs.getDate(1, cGMT05); // 2005-01-01 07:00:00 -0500 -> 2005-01-01 00:00:00 -0500
assertEquals(1104555600000L, d.getTime());
d = rs.getDate(1, cGMT13); // 2005-01-02 01:00:00 +1300 -> 2005-01-02 00:00:00 +1300
assertEquals(1104577200000L, d.getTime());
// timestamp: 2005-01-01 15:00:00
d = rs.getDate(2); // 2005-01-01 00:00:00 +0100
assertEquals(1104534000000L, d.getTime());
d = rs.getDate(2, cUTC); // 2005-01-01 00:00:00 +0000
assertEquals(1104537600000L, d.getTime());
d = rs.getDate(2, cGMT03); // 2005-01-01 00:00:00 +0300
assertEquals(1104526800000L, d.getTime());
d = rs.getDate(2, cGMT05); // 2005-01-01 00:00:00 -0500
assertEquals(1104555600000L, d.getTime());
d = rs.getDate(2, cGMT13); // 2005-01-01 00:00:00 +1300
assertEquals(1104490800000L, d.getTime());
d = rs.getDate(3); // 2005-01-01 00:00:00 +0100
assertEquals(1104534000000L, d.getTime());
d = rs.getDate(3, cUTC); // 2005-01-01 00:00:00 +0000
assertEquals(1104537600000L, d.getTime());
d = rs.getDate(3, cGMT03); // 2005-01-01 00:00:00 +0300
assertEquals(1104526800000L, d.getTime());
d = rs.getDate(3, cGMT05); // 2005-01-01 00:00:00 -0500
assertEquals(1104555600000L, d.getTime());
d = rs.getDate(3, cGMT13); // 2005-01-01 00:00:00 +1300
assertEquals(1104490800000L, d.getTime());
assertTrue(!rs.next());
}
}
}
@Test
public void testGetTime() throws Exception {
try (Statement stmt = con.createStatement()) {
stmt.executeUpdate("INSERT INTO testtimezone(tstz,ts,t,tz) VALUES('2005-01-01 15:00:00 +0300', '2005-01-01 15:00:00', '15:00:00', '15:00:00 +0300')");
try (ResultSet rs = con.createStatement().executeQuery("SELECT tstz,ts,t,tz from testtimezone")) {
assertTrue(rs.next());
checkDatabaseContents("SELECT tstz::text,ts::text,t::text,tz::text,d::text from testtimezone", new String[] {
"2005-01-01 12:00:00+00",
"2005-01-01 15:00:00",
"15:00:00",
"15:00:00+03"});
Time t;
// timestamptz: 2005-01-01 15:00:00+03
t = rs.getTime(1);
assertEquals(43200000L, t.getTime()); // 2005-01-01 13:00:00 +0100 -> 1970-01-01 13:00:00 +0100
t = rs.getTime(1, cUTC);
assertEquals(43200000L, t.getTime()); // 2005-01-01 12:00:00 +0000 -> 1970-01-01 12:00:00 +0000
t = rs.getTime(1, cGMT03);
assertEquals(43200000L, t.getTime()); // 2005-01-01 15:00:00 +0300 -> 1970-01-01 15:00:00 +0300
t = rs.getTime(1, cGMT05);
assertEquals(43200000L, t.getTime()); // 2005-01-01 07:00:00 -0500 -> 1970-01-01 07:00:00 -0500
t = rs.getTime(1, cGMT13);
assertEquals(-43200000L, t.getTime()); // 2005-01-02 01:00:00 +1300 -> 1970-01-01 01:00:00 +1300
// timestamp: 2005-01-01 15:00:00
t = rs.getTime(2);
assertEquals(50400000L, t.getTime()); // 1970-01-01 15:00:00 +0100
t = rs.getTime(2, cUTC);
assertEquals(54000000L, t.getTime()); // 1970-01-01 15:00:00 +0000
t = rs.getTime(2, cGMT03);
assertEquals(43200000L, t.getTime()); // 1970-01-01 15:00:00 +0300
t = rs.getTime(2, cGMT05);
assertEquals(72000000L, t.getTime()); // 1970-01-01 15:00:00 -0500
t = rs.getTime(2, cGMT13);
assertEquals(7200000L, t.getTime()); // 1970-01-01 15:00:00 +1300
// time: 15:00:00
t = rs.getTime(3);
assertEquals(50400000L, t.getTime()); // 1970-01-01 15:00:00 +0100
t = rs.getTime(3, cUTC);
assertEquals(54000000L, t.getTime()); // 1970-01-01 15:00:00 +0000
t = rs.getTime(3, cGMT03);
assertEquals(43200000L, t.getTime()); // 1970-01-01 15:00:00 +0300
t = rs.getTime(3, cGMT05);
assertEquals(72000000L, t.getTime()); // 1970-01-01 15:00:00 -0500
t = rs.getTime(3, cGMT13);
assertEquals(7200000L, t.getTime()); // 1970-01-01 15:00:00 +1300
// timetz: 15:00:00+03
t = rs.getTime(4);
assertEquals(43200000L, t.getTime()); // 1970-01-01 13:00:00 +0100
t = rs.getTime(4, cUTC);
assertEquals(43200000L, t.getTime()); // 1970-01-01 12:00:00 +0000
t = rs.getTime(4, cGMT03);
assertEquals(43200000L, t.getTime()); // 1970-01-01 15:00:00 +0300
t = rs.getTime(4, cGMT05);
assertEquals(43200000L, t.getTime()); // 1970-01-01 07:00:00 -0500
t = rs.getTime(4, cGMT13);
assertEquals(43200000L, t.getTime()); // 1970-01-01 01:00:00 +1300
}
}
}
/**
* This test is broken off from testSetTimestamp because it does not work for
* pre-7.4 servers and putting tons of conditionals in that test makes it
* largely unreadable. The time data type does not accept timestamp with time
* zone style input on these servers.
*/
@Test
public void testSetTimestampOnTime() throws Exception {
Timestamp instant = new Timestamp(1104580800000L); // 2005-01-01 12:00:00
// UTC
Timestamp instantTime = new Timestamp(instant.getTime() % DAY);
try (PreparedStatement insertTimestamp = con.prepareStatement("INSERT INTO testtimezone(seq,t) VALUES (?,?)")) {
int seq = 1;
// +0100 (JVM default)
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant); // 13:00:00
insertTimestamp.executeUpdate();
// UTC
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cUTC); // 12:00:00
insertTimestamp.executeUpdate();
// +0300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cGMT03); // 15:00:00
insertTimestamp.executeUpdate();
// -0500
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cGMT05); // 07:00:00
insertTimestamp.executeUpdate();
// +1300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cGMT13); // 01:00:00
insertTimestamp.executeUpdate();
}
checkDatabaseContents("SELECT seq::text,t::text from testtimezone ORDER BY seq", new String[][] {
new String[] {"1", "13:00:00"},
new String[] {"2", "12:00:00"},
new String[] {"3", "15:00:00"},
new String[] {"4", "07:00:00"},
new String[] {"5", "01:00:00"}});
try (Statement stmt = con.createStatement()) {
try (ResultSet rs = stmt.executeQuery("SELECT seq,t FROM testtimezone ORDER BY seq")) {
int seq = 1;
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instantTime, rs.getTimestamp(2));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instantTime, rs.getTimestamp(2, cUTC));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instantTime, rs.getTimestamp(2, cGMT03));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instantTime, rs.getTimestamp(2, cGMT05));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(normalizeTimeOfDayPart(instantTime, cGMT13), rs.getTimestamp(2, cGMT13));
assertTrue(!rs.next());
}
}
}
@Test
public void testSetTimestamp() throws Exception {
Timestamp instant = new Timestamp(1104580800000L); // 2005-01-01 12:00:00
// UTC
Timestamp instantTime = new Timestamp(instant.getTime() % DAY);
Timestamp instantDateJVM = new Timestamp(instant.getTime() - (instant.getTime() % DAY) - TimeZone.getDefault().getRawOffset());
Timestamp instantDateUTC = new Timestamp(instant.getTime() - (instant.getTime() % DAY) - cUTC.getTimeZone().getRawOffset());
Timestamp instantDateGMT03 = new Timestamp(instant.getTime() - (instant.getTime() % DAY) - cGMT03.getTimeZone().getRawOffset());
Timestamp instantDateGMT05 = new Timestamp(instant.getTime() - (instant.getTime() % DAY) - cGMT05.getTimeZone().getRawOffset());
Timestamp instantDateGMT13 = new Timestamp(instant.getTime() - (instant.getTime() % DAY) - cGMT13.getTimeZone().getRawOffset() + DAY);
try (PreparedStatement insertTimestamp = con.prepareStatement("INSERT INTO testtimezone(seq,tstz,ts,tz,d) VALUES (?,?,?,?,?)")) {
int seq = 1;
// +0100 (JVM default)
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant); // 2005-01-01 13:00:00 +0100
insertTimestamp.setTimestamp(3, instant); // 2005-01-01 13:00:00
insertTimestamp.setTimestamp(4, instant); // 13:00:00 +0100
insertTimestamp.setTimestamp(5, instant); // 2005-01-01
insertTimestamp.executeUpdate();
// UTC
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cUTC); // 2005-01-01 12:00:00 +0000
insertTimestamp.setTimestamp(3, instant, cUTC); // 2005-01-01 12:00:00
insertTimestamp.setTimestamp(4, instant, cUTC); // 12:00:00 +0000
insertTimestamp.setTimestamp(5, instant, cUTC); // 2005-01-01
insertTimestamp.executeUpdate();
// +0300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cGMT03); // 2005-01-01 15:00:00 +0300
insertTimestamp.setTimestamp(3, instant, cGMT03); // 2005-01-01 15:00:00
insertTimestamp.setTimestamp(4, instant, cGMT03); // 15:00:00 +0300
insertTimestamp.setTimestamp(5, instant, cGMT03); // 2005-01-01
insertTimestamp.executeUpdate();
// -0500
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cGMT05); // 2005-01-01 07:00:00 -0500
insertTimestamp.setTimestamp(3, instant, cGMT05); // 2005-01-01 07:00:00
insertTimestamp.setTimestamp(4, instant, cGMT05); // 07:00:00 -0500
insertTimestamp.setTimestamp(5, instant, cGMT05); // 2005-01-01
insertTimestamp.executeUpdate();
// +1300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTimestamp(2, instant, cGMT13); // 2005-01-02 01:00:00 +1300
insertTimestamp.setTimestamp(3, instant, cGMT13); // 2005-01-02 01:00:00
insertTimestamp.setTimestamp(4, instant, cGMT13); // 01:00:00 +1300
insertTimestamp.setTimestamp(5, instant, cGMT13); // 2005-01-02
insertTimestamp.executeUpdate();
}
// check that insert went correctly by parsing the raw contents in UTC
checkDatabaseContents("SELECT seq::text,tstz::text,ts::text,tz::text,d::text from testtimezone ORDER BY seq", new String[][] {
new String[] {"1", "2005-01-01 12:00:00+00", "2005-01-01 13:00:00", "13:00:00+01", "2005-01-01"},
new String[] {"2", "2005-01-01 12:00:00+00", "2005-01-01 12:00:00", "12:00:00+00", "2005-01-01"},
new String[] {"3", "2005-01-01 12:00:00+00", "2005-01-01 15:00:00", "15:00:00+03", "2005-01-01"},
new String[] {"4", "2005-01-01 12:00:00+00", "2005-01-01 07:00:00", "07:00:00-05", "2005-01-01"},
new String[] {"5", "2005-01-01 12:00:00+00", "2005-01-02 01:00:00", "01:00:00+13", "2005-01-02"} });
// check results
try (Statement stmt = con.createStatement()) {
try (ResultSet rs = stmt.executeQuery("SELECT seq,tstz,ts,tz,d FROM testtimezone ORDER BY seq")) {
int seq = 1;
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instant, rs.getTimestamp(2));
assertEquals(instant, rs.getTimestamp(3));
assertEquals(instantTime, rs.getTimestamp(4));
assertEquals(instantDateJVM, rs.getTimestamp(5));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instant, rs.getTimestamp(2, cUTC));
assertEquals(instant, rs.getTimestamp(3, cUTC));
assertEquals(instantTime, rs.getTimestamp(4, cUTC));
assertEquals(instantDateUTC, rs.getTimestamp(5, cUTC));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instant, rs.getTimestamp(2, cGMT03));
assertEquals(instant, rs.getTimestamp(3, cGMT03));
assertEquals(instantTime, rs.getTimestamp(4, cGMT03));
assertEquals(instantDateGMT03, rs.getTimestamp(5, cGMT03));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instant, rs.getTimestamp(2, cGMT05));
assertEquals(instant, rs.getTimestamp(3, cGMT05));
assertEquals(instantTime, rs.getTimestamp(4, cGMT05));
assertEquals(instantDateGMT05, rs.getTimestamp(5, cGMT05));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(instant, rs.getTimestamp(2, cGMT13));
assertEquals(instant, rs.getTimestamp(3, cGMT13));
assertEquals(normalizeTimeOfDayPart(instantTime, cGMT13), rs.getTimestamp(4, cGMT13));
assertEquals(instantDateGMT13, rs.getTimestamp(5, cGMT13));
assertTrue(!rs.next());
}
}
}
@Test
public void testSetDate() throws Exception {
Date dJVM, dUTC, dGMT03, dGMT05, dGMT13 = null;
try (PreparedStatement insertTimestamp = con.prepareStatement("INSERT INTO testtimezone(seq,tstz,ts,d) VALUES (?,?,?,?)")) {
int seq = 1;
// +0100 (JVM default)
dJVM = new Date(1104534000000L); // 2005-01-01 00:00:00 +0100
insertTimestamp.setInt(1, seq++);
insertTimestamp.setDate(2, dJVM); // 2005-01-01 00:00:00 +0100
insertTimestamp.setDate(3, dJVM); // 2005-01-01 00:00:00
insertTimestamp.setDate(4, dJVM); // 2005-01-01
insertTimestamp.executeUpdate();
// UTC
dUTC = new Date(1104537600000L); // 2005-01-01 00:00:00 +0000
insertTimestamp.setInt(1, seq++);
insertTimestamp.setDate(2, dUTC, cUTC); // 2005-01-01 00:00:00 +0000
insertTimestamp.setDate(3, dUTC, cUTC); // 2005-01-01 00:00:00
insertTimestamp.setDate(4, dUTC, cUTC); // 2005-01-01
insertTimestamp.executeUpdate();
// +0300
dGMT03 = new Date(1104526800000L); // 2005-01-01 00:00:00 +0300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setDate(2, dGMT03, cGMT03); // 2005-01-01 00:00:00 +0300
insertTimestamp.setDate(3, dGMT03, cGMT03); // 2005-01-01 00:00:00
insertTimestamp.setDate(4, dGMT03, cGMT03); // 2005-01-01
insertTimestamp.executeUpdate();
// -0500
dGMT05 = new Date(1104555600000L); // 2005-01-01 00:00:00 -0500
insertTimestamp.setInt(1, seq++);
insertTimestamp.setDate(2, dGMT05, cGMT05); // 2005-01-01 00:00:00 -0500
insertTimestamp.setDate(3, dGMT05, cGMT05); // 2005-01-01 00:00:00
insertTimestamp.setDate(4, dGMT05, cGMT05); // 2005-01-01
insertTimestamp.executeUpdate();
// +1300
dGMT13 = new Date(1104490800000L); // 2005-01-01 00:00:00 +1300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setDate(2, dGMT13, cGMT13); // 2005-01-01 00:00:00 +1300
insertTimestamp.setDate(3, dGMT13, cGMT13); // 2005-01-01 00:00:00
insertTimestamp.setDate(4, dGMT13, cGMT13); // 2005-01-01
insertTimestamp.executeUpdate();
}
// check that insert went correctly by parsing the raw contents in UTC
checkDatabaseContents("SELECT seq::text,tstz::text,ts::text,d::text from testtimezone ORDER BY seq", new String[][] {
new String[] {"1", "2004-12-31 23:00:00+00", "2005-01-01 00:00:00", "2005-01-01"},
new String[] {"2", "2005-01-01 00:00:00+00", "2005-01-01 00:00:00", "2005-01-01"},
new String[] {"3", "2004-12-31 21:00:00+00", "2005-01-01 00:00:00", "2005-01-01"},
new String[] {"4", "2005-01-01 05:00:00+00", "2005-01-01 00:00:00", "2005-01-01"},
new String[] {"5", "2004-12-31 11:00:00+00", "2005-01-01 00:00:00", "2005-01-01"}});
// check results
try (Statement stmt = con.createStatement()) {
try (ResultSet rs = stmt.executeQuery("SELECT seq,tstz,ts,d FROM testtimezone ORDER BY seq")) {
int seq = 1;
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(dJVM, rs.getDate(2));
assertEquals(dJVM, rs.getDate(3));
assertEquals(dJVM, rs.getDate(4));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(dUTC, rs.getDate(2, cUTC));
assertEquals(dUTC, rs.getDate(3, cUTC));
assertEquals(dUTC, rs.getDate(4, cUTC));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(dGMT03, rs.getDate(2, cGMT03));
assertEquals(dGMT03, rs.getDate(3, cGMT03));
assertEquals(dGMT03, rs.getDate(4, cGMT03));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(dGMT05, rs.getDate(2, cGMT05));
assertEquals(dGMT05, rs.getDate(3, cGMT05));
assertEquals(dGMT05, rs.getDate(4, cGMT05));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(dGMT13, rs.getDate(2, cGMT13));
assertEquals(dGMT13, rs.getDate(3, cGMT13));
assertEquals(dGMT13, rs.getDate(4, cGMT13));
assertTrue(!rs.next());
}
}
}
@Test
public void testSetTime() throws Exception {
Time tJVM, tUTC, tGMT03, tGMT05, tGMT13;
try (PreparedStatement insertTimestamp = con.prepareStatement("INSERT INTO testtimezone(seq,t,tz) VALUES (?,?,?)")) {
int seq = 1;
// +0100 (JVM default)
tJVM = new Time(50400000L); // 1970-01-01 15:00:00 +0100
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTime(2, tJVM); // 15:00:00
insertTimestamp.setTime(3, tJVM); // 15:00:00+03
insertTimestamp.executeUpdate();
// UTC
tUTC = new Time(54000000L); // 1970-01-01 15:00:00 +0000
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTime(2, tUTC, cUTC); // 15:00:00
insertTimestamp.setTime(3, tUTC, cUTC); // 15:00:00+00
insertTimestamp.executeUpdate();
// +0300
tGMT03 = new Time(43200000L); // 1970-01-01 15:00:00 +0300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTime(2, tGMT03, cGMT03); // 15:00:00
insertTimestamp.setTime(3, tGMT03, cGMT03); // 15:00:00+03
insertTimestamp.executeUpdate();
// -0500
tGMT05 = new Time(72000000L); // 1970-01-01 15:00:00 -0500
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTime(2, tGMT05, cGMT05); // 15:00:00
insertTimestamp.setTime(3, tGMT05, cGMT05); // 15:00:00-05
insertTimestamp.executeUpdate();
// +1300
tGMT13 = new Time(7200000L); // 1970-01-01 15:00:00 +1300
insertTimestamp.setInt(1, seq++);
insertTimestamp.setTime(2, tGMT13, cGMT13); // 15:00:00
insertTimestamp.setTime(3, tGMT13, cGMT13); // 15:00:00+13
insertTimestamp.executeUpdate();
}
// check that insert went correctly by parsing the raw contents in UTC
checkDatabaseContents("SELECT seq::text,t::text,tz::text from testtimezone ORDER BY seq", new String[][] {
new String[] {"1", "15:00:00", "15:00:00+01", },
new String[] {"2", "15:00:00", "15:00:00+00", },
new String[] {"3", "15:00:00", "15:00:00+03", },
new String[] {"4", "15:00:00", "15:00:00-05", },
new String[] {"5", "15:00:00", "15:00:00+13", }});
// check results
try (Statement stmt = con.createStatement()) {
try (ResultSet rs = stmt.executeQuery("SELECT seq,t,tz FROM testtimezone ORDER BY seq")) {
int seq = 1;
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(tJVM, rs.getTime(2));
assertEquals(tJVM, rs.getTime(3));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(tUTC, rs.getTime(2, cUTC));
assertEquals(tUTC, rs.getTime(2, cUTC));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(tGMT03, rs.getTime(2, cGMT03));
assertEquals(tGMT03, rs.getTime(2, cGMT03));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(tGMT05, rs.getTime(2, cGMT05));
assertEquals(tGMT05, rs.getTime(2, cGMT05));
assertTrue(rs.next());
assertEquals(seq++, rs.getInt(1));
assertEquals(tGMT13, rs.getTime(2, cGMT13));
assertEquals(tGMT13, rs.getTime(2, cGMT13));
assertTrue(!rs.next());
}
}
}
@Test
public void testHalfHourTimezone() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("SET TimeZone = 'GMT+3:30'");
ResultSet rs = stmt.executeQuery("SELECT '1969-12-31 20:30:00'::timestamptz");
assertTrue(rs.next());
assertEquals(0L, rs.getTimestamp(1).getTime());
}
@Test
public void testTimezoneWithSeconds() throws SQLException {
Statement stmt = con.createStatement();
stmt.execute("SET TimeZone = 'Europe/Paris'");
ResultSet rs = stmt.executeQuery("SELECT '1920-01-01'::timestamptz");
rs.next();
// select extract(epoch from '1920-01-01'::timestamptz -
// 'epoch'::timestamptz) * 1000;
assertEquals(-1577923200000L, rs.getTimestamp(1).getTime());
}
/**
* Does a query in UTC time zone to database to check that the inserted values
* are correct.
*
* @param query
* The query to run.
* @param correct
* The correct answers in UTC time zone as formatted by backend.
*/
private void checkDatabaseContents(String query, String[] correct) throws Exception {
checkDatabaseContents(query, new String[][] {correct});
}
private void checkDatabaseContents(String query, String[][] correct) throws Exception {
Connection con2 = TestUtil.openDB();
Statement s = con2.createStatement();
assertFalse(s.execute("set time zone 'UTC'"));
assertTrue(s.execute(query));
ResultSet rs = s.getResultSet();
for (int j = 0; j < correct.length; ++j) {
assertTrue(rs.next());
for (int i = 0; i < correct[j].length; ++i) {
assertEquals("On row " + (j + 1), correct[j][i], rs.getString(i + 1));
}
}
assertFalse(rs.next());
rs.close();
s.close();
con2.close();
}
/**
* Converts the given time
*
* @param t
* The time of day. Must be within -24 and + 24 hours of epoc.
* @param tz
* The timezone to normalize to.
* @return the Time nomralized to 0 to 24 hours of epoc adjusted with given
* timezone.
*/
private Timestamp normalizeTimeOfDayPart(Timestamp t, Calendar tz) {
return new Timestamp(normalizeTimeOfDayPart(t.getTime(), tz.getTimeZone()));
}
private long normalizeTimeOfDayPart(long t, TimeZone tz) {
long millis = t;
long low = -tz.getOffset(millis);
long high = low + DAY;
if (millis < low) {
do {
millis += DAY;
}
while(millis < low);
}
else if (millis >= high) {
do {
millis -= DAY;
}
while(millis > high);
}
return millis;
}
} |
package com.opengamma.sesame.config;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collections;
import org.testng.annotations.Test;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.ImmutableMap;
import com.opengamma.util.test.TestGroup;
@Test(groups = TestGroup.UNIT)
public class InjectorTest {
/* package */ static final String VALUE_NAME = "ValueName";
private static final String INFRASTRUCTURE_COMPONENT = "some pretend infrastructure";
@Test
public void defaultImpl() {
Injector injector = new Injector();
TestFunction fn = injector.create(TestFunction.class);
assertTrue(fn instanceof Default);
}
@Test
public void overriddenImpl() {
Injector injector = new Injector();
FunctionConfig requirement = config(TestFunction.class, Alternative.class);
TestFunction fn = injector.create(TestFunction.class, requirement);
assertTrue(fn instanceof Alternative);
}
@Test
public void infrastructure() {
Injector injector = new Injector(ImmutableMap.<Class<?>, Object>of(String.class, INFRASTRUCTURE_COMPONENT));
FunctionConfig requirement = config(TestFunction.class, Infrastructure.class);
TestFunction fn = injector.create(TestFunction.class, requirement);
assertTrue(fn instanceof Infrastructure);
//noinspection ConstantConditions
assertEquals(INFRASTRUCTURE_COMPONENT, ((Infrastructure) fn)._infrastructureComponent);
}
@Test
public void defaultUserParams() {
Injector injector = new Injector();
FunctionConfig requirement = config(TestFunction.class, UserParameters.class);
TestFunction fn = injector.create(TestFunction.class, requirement);
assertTrue(fn instanceof UserParameters);
//noinspection ConstantConditions
assertEquals(9, ((UserParameters) fn)._i);
//noinspection ConstantConditions
assertEquals(ZonedDateTime.of(2011, 3, 8, 2, 18, 0, 0, ZoneOffset.UTC), ((UserParameters) fn)._dateTime);
}
@Test
public void overriddenUserParam() {
Injector injector = new Injector();
FunctionArguments args = new FunctionArguments(ImmutableMap.<String, Object>of("i", 12));
FunctionConfig requirement =
new FunctionConfig(ImmutableMap.<Class<?>, Class<?>>of(TestFunction.class, UserParameters.class),
ImmutableMap.<Class<?>, FunctionArguments>of(UserParameters.class, args));
TestFunction fn = injector.create(TestFunction.class, requirement);
assertTrue(fn instanceof UserParameters);
//noinspection ConstantConditions
assertEquals(12, ((UserParameters) fn)._i);
//noinspection ConstantConditions
assertEquals(ZonedDateTime.of(2011, 3, 8, 2, 18, 0, 0, ZoneOffset.UTC), ((UserParameters) fn)._dateTime);
}
@Test
public void functionCallingOtherFunction() {
Injector injector = new Injector();
FunctionConfig requirement = config(TestFunction.class, CallsOtherFunction.class);
TestFunction fn = injector.create(TestFunction.class, requirement);
assertTrue(fn instanceof CallsOtherFunction);
//noinspection ConstantConditions
assertTrue(((CallsOtherFunction) fn)._collaborator instanceof Collaborator);
}
@Test
public void concreteFunctionType() {
}
@Test
public void noVisibleConstructors() {
}
@Test
public void multipleInjectableConstructors() {
}
@Test
public void infrastructureNotFound() {
}
@Test
public void noDefaultImpl() {
}
@Test
public void cyclicDependency() {
}
private static FunctionConfig config(Class<?> fnType, Class<?> implType) {
return new FunctionConfig(ImmutableMap.<Class<?>, Class<?>>of(fnType, implType),
Collections.<Class<?>, FunctionArguments>emptyMap());
}
}
@EngineFunction(InjectorTest.VALUE_NAME)
@DefaultImplementation(Default.class)
/* package */ interface TestFunction { }
/* package */ class Default implements TestFunction { }
/* package */ class Alternative implements TestFunction { }
/* package */ class Infrastructure implements TestFunction {
/* package */ final String _infrastructureComponent;
/* package */ Infrastructure(String infrastructureComponent) {
_infrastructureComponent = infrastructureComponent;
}
}
/* package */ class UserParameters implements TestFunction {
/* package */ final int _i;
/* package */ final ZonedDateTime _dateTime;
/* package */ UserParameters(@UserParam(name = "i", defaultValue = "9") int i,
@UserParam(name = "dateTime", defaultValue = "2011-03-08T02:18Z") ZonedDateTime dateTime) {
_i = i;
_dateTime = dateTime;
}
}
/* package */ class CallsOtherFunction implements TestFunction {
/* package */ final CollaboratorFunction _collaborator;
/* package */ CallsOtherFunction(CollaboratorFunction collaborator) {
_collaborator = collaborator;
}
}
@DefaultImplementation(Collaborator.class)
/* package */ interface CollaboratorFunction { }
/* package */ class Collaborator implements CollaboratorFunction { } |
package com.pm.server.player;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.pm.server.TestTemplate;
import com.pm.server.datatype.Coordinate;
import com.pm.server.datatype.CoordinateImpl;
public class GhostRepositoryTest extends TestTemplate {
private Ghost ghost1;
private Ghost ghost2;
private Ghost ghost3;
@Autowired
private GhostRepository ghostRepository;
private static final double DELTA = 1e-15;
private static final Logger log =
LogManager.getLogger(GhostRepositoryTest.class.getName());
@Before
public void setUp() {
Integer ghost1_id = 12345;
Coordinate ghost1_location = new CoordinateImpl(1.0, 0.1);
ghost1 = new GhostImpl();
ghost1.setId(ghost1_id);
ghost1.setLocation(ghost1_location);
Integer ghost2_id = 23456;
Coordinate ghost2_location = new CoordinateImpl(2.0, 0.2);
ghost2 = new GhostImpl();
ghost2.setId(ghost2_id);
ghost2.setLocation(ghost2_location);
Integer ghost3_id = 34567;
Coordinate ghost3_location = new CoordinateImpl(3.0, 0.3);
ghost3 = new GhostImpl();
ghost3.setId(ghost3_id);
ghost3.setLocation(ghost3_location);
List<Ghost> ghostList = ghostRepository.getAllGhosts();
for(Integer i = 0; i < ghostList.size(); i++) {
try {
ghostRepository.deleteGhostById(ghostList.get(i).getId());
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
}
assertTrue(ghostRepository.getAllGhosts().isEmpty());
}
@Test
public void unitTest_addGhost() {
// Given
// When
addGhost_failUponException(ghost1);
// Then
Ghost ghostFromRepository = ghostRepository.getGhostById(ghost1.getId());
assertTrue(ghostFromRepository != null);
assertEquals(ghostFromRepository.getId(), ghost1.getId());
assertEquals(
ghostFromRepository.getLocation().getLatitude(),
ghost1.getLocation().getLatitude(),
DELTA
);
assertEquals(
ghostFromRepository.getLocation().getLongitude(),
ghost1.getLocation().getLongitude(),
DELTA
);
}
@Test(expected = IllegalArgumentException.class)
public void unitTest_addGhost_conflictId() throws Exception {
// Given
addGhost_failUponException(ghost1);
// When
ghostRepository.addGhost(ghost1);
// Then
// Exception thrown above
}
@Test
public void unitTest_deleteGhostById() {
// Given
addGhost_failUponException(ghost1);
// When
deleteGhostById_failUponException(ghost1.getId());
// Then
assertTrue(ghostRepository.getGhostById(ghost1.getId()) == null);
}
@Test
public void unitTest_numOfGhosts() {
// Given
assertEquals(Integer.valueOf(0), ghostRepository.numOfGhosts());
assert(ghostRepository.getAllGhosts().isEmpty());
// When
addGhost_failUponException(ghost1);
// Then
assertEquals(Integer.valueOf(1), ghostRepository.numOfGhosts());
// When
deleteGhostById_failUponException(ghost1.getId());
// Then
assertEquals(Integer.valueOf(0), ghostRepository.numOfGhosts());
}
private void addGhost_failUponException(Ghost ghost) {
try {
ghostRepository.addGhost(ghost);
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
}
private void deleteGhostById_failUponException(Integer id) {
try {
ghostRepository.deleteGhostById(id);
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
}
} |
package org.objectweb.proactive.p2p.api.core;
import java.io.Serializable;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.InitActive;
import org.objectweb.proactive.ProActive;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.descriptor.data.VirtualNodeImpl;
import org.objectweb.proactive.core.event.NodeCreationEvent;
import org.objectweb.proactive.core.event.NodeCreationEventListener;
import org.objectweb.proactive.core.group.ExceptionInGroup;
import org.objectweb.proactive.core.group.ExceptionListException;
import org.objectweb.proactive.core.group.Group;
import org.objectweb.proactive.core.group.ProActiveGroup;
import org.objectweb.proactive.core.mop.ClassNotReifiableException;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.p2p.api.core.queue.TaskQueue;
public class Manager implements Serializable, InitActive,
NodeCreationEventListener {
private static final boolean enableRealloc = false; // TODO turn it configurable
private static Logger logger = ProActiveLogger.getLogger(Loggers.P2P_SKELETONS_MANAGER);
private Task rootTask = null;
private Node[] nodes = null;
private Worker workerGroup = null;
private ListIterator workerGroupListIt = null;
private TaskQueue taskProvider = null;
private Vector futureTaskList = new Vector();
private Vector pendingTaskList = new Vector();
private Vector workingWorkerList = new Vector();
private Vector freeWorkerList = new Vector();
private Vector allResults = new Vector();
private String queueType = null;
private VirtualNode virtualNode = null;
/**
* The no args constructor for ProActive.
*/
public Manager() {
// nothing to do
}
private Manager(Task root, Node myNode, String queueType) {
try {
this.rootTask = (Task) ProActive.turnActive(root, myNode);
} catch (ActiveObjectCreationException e) {
logger.fatal("Problem with the turn active of the root task", e);
throw new RuntimeException(e);
} catch (NodeException e) {
logger.fatal("Problem with the node of the root task", e);
throw new RuntimeException(e);
}
this.queueType = queueType;
}
public Manager(Task root, Node[] nodes, Node myNode, String queueType) {
this(root, myNode, queueType);
this.nodes = nodes;
}
public Manager(Task root, VirtualNode virtualNode, Node myNode,
String queueType) {
this(root, myNode, queueType);
this.virtualNode = virtualNode;
}
public void initActivity(Body body) {
if (this.virtualNode != null) {
((VirtualNodeImpl) this.virtualNode).addNodeCreationEventListener(this);
this.virtualNode.activate();
}
try {
this.taskProvider = (TaskQueue) ProActive.newActive(this.queueType,
null, body.getNodeURL());
} catch (ActiveObjectCreationException e1) {
logger.fatal("Couldn't create the Task Provider", e1);
throw new ProActiveRuntimeException(e1);
} catch (NodeException e1) {
logger.fatal("Couldn't create the Task Provider", e1);
throw new ProActiveRuntimeException(e1);
}
// Group of Worker
try {
if (this.nodes != null) {
Object[][] args = new Object[this.nodes.length][1];
for (int i = 0; i < args.length; i++) {
args[i][0] = this.taskProvider;
}
this.workerGroup = (Worker) ProActiveGroup.newGroup(Worker.class.getName(),
args, this.nodes);
} else {
this.workerGroup = (Worker) ProActiveGroup.newGroup(Worker.class.getName());
}
this.workerGroupListIt = ProActiveGroup.getGroup(this.workerGroup)
.listIterator();
} catch (ClassNotReifiableException e) {
logger.fatal("The Worker is not reifiable", e);
throw new ProActiveRuntimeException(e);
} catch (ActiveObjectCreationException e) {
logger.fatal("Problem with active objects creation", e);
throw new ProActiveRuntimeException(e);
} catch (NodeException e) {
logger.fatal("Problem with a node", e);
} catch (ClassNotFoundException e) {
logger.fatal("The class for worker was not found", e);
throw new ProActiveRuntimeException(e);
}
Group groupOfWorkers = ProActiveGroup.getGroup(this.workerGroup);
try {
this.workerGroup.setWorkerGroup(this.workerGroup);
} catch (ExceptionListException e) {
logger.debug("Some workers are down", e);
Iterator it = e.iterator();
while (it.hasNext()) {
groupOfWorkers.remove(((ExceptionInGroup) it.next()).getObject());
}
}
// Spliting
logger.info("Compute the lower bound for the root task");
this.rootTask.initLowerBound();
logger.info("Compute the upper bound for the root task");
this.rootTask.initUpperBound();
logger.info("Calling for the first time split on the root task");
Vector subTaskList = this.rootTask.split();
String taskTag = this.rootTask.getTag();
if (taskTag == null) {
taskTag = 0 + "";
}
logger.info("The ROOT task sends " + subTaskList.size() +
" with group tag " + taskTag);
for (int i = 0; i < subTaskList.size(); i++) {
Task current = (Task) subTaskList.get(i);
current.setTag(taskTag + "-" + i);
}
this.taskProvider.addAll(subTaskList);
}
public Result start() {
logger.info("Starting computation");
// Nothing to do if the manager is not actived
if (!ProActive.getBodyOnThis().isActive()) {
logger.fatal("The manager is not active");
throw new ProActiveRuntimeException("The manager is not active");
}
// Serving requests and waiting for results
while (this.taskProvider.hasNext().booleanValue() ||
(this.pendingTaskList.size() != 0)) {
if (this.taskProvider.hasNext().booleanValue()) {
boolean hasAddedTask = false;
if (this.workerGroupListIt.hasNext()) {
this.assignTaskToWorker((Worker) this.workerGroupListIt.next(),
this.taskProvider.next());
hasAddedTask = true;
} else if ((this.freeWorkerList.size() > 0)) {
this.assignTaskToWorker((Worker) this.freeWorkerList.remove(
0), this.taskProvider.next());
hasAddedTask = true;
} else if (this.futureTaskList.size() == 0) {
// Waiting workers
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
continue;
}
if (hasAddedTask && logger.isInfoEnabled()) {
logger.info("Pending tasks: " +
this.pendingTaskList.size() + " - Achivied tasks: " +
this.allResults.size() + " - Not calculated tasks: " +
this.taskProvider.size());
continue;
}
}
try {
int index = ProActive.waitForAny(this.futureTaskList, 1000);
this.allResults.add(this.futureTaskList.remove(index));
this.pendingTaskList.remove(index);
Worker freeWorker = (Worker) this.workingWorkerList.remove(index);
if (this.taskProvider.hasNext().booleanValue()) {
this.assignTaskToWorker(freeWorker, this.taskProvider.next());
} else {
this.freeWorkerList.add(freeWorker);
}
logger.info("Pending tasks: " + this.pendingTaskList.size() +
" - Achivied tasks: " + this.allResults.size() +
" - Not calculated tasks: " + this.taskProvider.size());
} catch (ProActiveException e) {
if (enableRealloc && (this.freeWorkerList.size() > 0)) {
// Reallocating tasks
// TODO
}
continue;
}
}
logger.info("Total of results = " + this.allResults.size());
logger.info("Total of tasks = " + this.taskProvider.size());
// Set the final result
if (this.virtualNode != null) {
this.virtualNode.killAll(false);
}
return this.rootTask.gather((Result[]) this.allResults.toArray(
new Result[this.allResults.size()]));
}
/**
* Assign a task to a worker.
* @param worker the worker.
* @param task the task.
*/
private void assignTaskToWorker(Worker worker, Task task) {
this.futureTaskList.add(worker.execute(task));
this.pendingTaskList.add(task);
this.workingWorkerList.add(worker);
}
public void nodeCreated(NodeCreationEvent event) {
logger.info(">>>> New Node");
Object[] args = new Object[] { this.taskProvider };
Node createdNode = event.getNode();
Worker newWorker = null;
try {
newWorker = (Worker) ProActive.newActive(Worker.class.getName(),
args, createdNode);
} catch (ActiveObjectCreationException e) {
logger.warn("Couldn't create a worker", e);
return;
} catch (NodeException e) {
logger.warn("Couldn't create a worker, this caused by a node failure",
e);
return;
}
this.workerGroup.addMember(newWorker);
this.workerGroupListIt.add(newWorker);
newWorker.setWorkerGroup(this.workerGroup);
this.freeWorkerList.add(newWorker);
}
} |
package org.opencms.file.collectors;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.search.solr.CmsSolrIndex;
import org.opencms.search.solr.CmsSolrQuery;
import org.opencms.util.CmsRequestUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* A Solr collector.<p>
*
* @since 8.5.0
*/
public class CmsSolrCollector extends A_CmsResourceCollector {
/** Constant array of the collectors implemented by this class. */
private static final String[] COLLECTORS = {"byQuery", "byContext"};
/** Array list for fast collector name lookup. */
private static final List<String> COLLECTORS_LIST = Collections.unmodifiableList(Arrays.asList(COLLECTORS));
/**
* @see org.opencms.file.collectors.I_CmsResourceCollector#getCollectorNames()
*/
public List<String> getCollectorNames() {
return COLLECTORS_LIST;
}
/**
* @see org.opencms.file.collectors.I_CmsResourceCollector#getCreateLink(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
*/
public String getCreateLink(CmsObject cms, String collectorName, String param) {
return null;
}
/**
* @see org.opencms.file.collectors.I_CmsResourceCollector#getCreateParam(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
*/
public String getCreateParam(CmsObject cms, String collectorName, String param) {
return null;
}
/**
* @see org.opencms.file.collectors.I_CmsResourceCollector#getResults(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
*/
public List<CmsResource> getResults(CmsObject cms, String collectorName, String param) throws CmsException {
// if action is not set use default
collectorName = collectorName == null ? COLLECTORS[1] : collectorName;
Map<String, String[]> pm = CmsRequestUtil.createParameterMap(param);
CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(pm);
CmsSolrQuery q = COLLECTORS_LIST.indexOf(collectorName) == 0 ? new CmsSolrQuery(pm) : new CmsSolrQuery(cms, pm);
return new ArrayList<CmsResource>(index.search(cms, q));
}
} |
package com.shinemo.mpush.client;
import com.shinemo.mpush.api.Client;
import com.shinemo.mpush.api.ClientListener;
import com.shinemo.mpush.util.DefaultLogger;
import org.junit.Test;
import java.util.concurrent.locks.LockSupport;
import static org.junit.Assert.*;
public class MPushClientTest {
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcNLVG4noMfOIvKfV0eJAcADO4nr0hqoj42swL8DWY8CujpUGutw7Qk5LEn6i037wlF5CwIzJ7ix2xK+IcxEonOANtlS1NKbUXOCgUtA5mdZTnvAUByN0tzGp4BGywYNiXFQmLMXG5uxN0ZfcaoRKVqLzbcMnLB7VzS4L3OxzxqwIDAQAB";
private static final String allocServer = "http://allot.mupsh.com/";
public static void main(String[] args) throws Exception {
Client client = ClientConfig
.build()
.setPublicKey(publicKey)
.setAllotServer(allocServer)
.setDeviceId("1111111111")
.setOsName("Android")
.setOsVersion("6.0")
.setClientVersion("2.0")
.setUserId("doctor43test")
.setSessionStorageDir(MPushClientTest.class.getResource("/").getFile())
.setLogger(new DefaultLogger())
.setLogEnabled(true)
.setEnableHttpProxy(false)
.setClientListener(new L())
.create();
client.start();
LockSupport.park();
}
public static class L implements ClientListener {
Thread thread;
boolean flag = true;
@Override
public void onConnected(Client client) {
flag = true;
}
@Override
public void onDisConnected(Client client) {
flag = false;
}
@Override
public void onHandshakeOk(final Client client, final int heartbeat) {
thread = new Thread(new Runnable() {
@Override
public void run() {
while (flag && client.isRunning()) {
try {
Thread.sleep(heartbeat);
} catch (InterruptedException e) {
break;
}
client.healthCheck();
}
}
});
thread.start();
}
@Override
public void onReceivePush(Client client, String content) {
}
@Override
public void onKickUser(String deviceId, String userId) {
}
}
} |
package org.opencms.workplace.explorer;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypePlain;
import org.opencms.i18n.CmsEncoder;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.CmsWorkplaceException;
import org.opencms.xml.CmsXmlException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
/**
* The new resource upload dialog handles the upload of cvs files. They are converted in a first step to xml
* and in a second step transformed via a xsl stylesheet.<p>
*
* The following files use this class:
* <ul>
* <li>/commons/newcvsfile_upload.jsp
* </ul>
* <p>
*
* @author Jan Baudisch
*
* @version $Revision: 1.28 $
*
* @since 6.0.0
*/
public class CmsNewCsvFile extends CmsNewResourceUpload {
/** Constant for automatically selecting the best fitting delimiter. */
public static final String BEST_DELIMITER = "best";
/** Constant for the height of the dialog frame. */
public static final String FRAMEHEIGHT = "450";
/** Request parameter name for the CSV content. */
public static final String PARAM_CSVCONTENT = "csvcontent";
/** Request parameter name for the delimiter. */
public static final String PARAM_DELIMITER = "delimiter";
/** Request parameter name for the XSLT file. */
public static final String PARAM_XSLTFILE = "xsltfile";
/** Constant for the xslt file suffix for table transformations. */
public static final String TABLE_XSLT_SUFFIX = ".table.xslt";
/** Constant for the tab-value inside delimiter the select. */
public static final String TABULATOR = "tab";
/** The delimiter to separate the text. */
public static final char TEXT_DELIMITER = '"';
/** The delimiter to start a tag */
public static final String TAG_START_DELIMITER = "<";
/** The delimiter to end a tag */
public static final String TAG_END_DELIMITER = ">";
/** the delimiters, the csv data can be separated with.*/
static final String[] DELIMITERS = {";", ",", "\t"};
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsNewCsvFile.class);
/** The pasted CSV content. */
private String m_paramCsvContent;
/** The delimiter to separate the CSV values. */
private String m_paramDelimiter;
/** The XSLT File to transform the table with. */
private String m_paramXsltFile;
/**
* Public constructor with JSP action element.<p>
*
* @param jsp an initialized JSP action element
*/
public CmsNewCsvFile(CmsJspActionElement jsp) {
super(jsp);
}
/**
* Public constructor with JSP variables.<p>
*
* @param context the JSP page context
* @param req the JSP request
* @param res the JSP response
*/
public CmsNewCsvFile(PageContext context, HttpServletRequest req, HttpServletResponse res) {
this(new CmsJspActionElement(context, req, res));
}
/**
* Converts a delimiter separated format string int o colgroup html fragment.<p>
* @param formatString the formatstring to convert
* @param delimiter the delimiter the formats (l,r or c) are delimited with
*
* @return the resulting colgroup HTML
*/
private static String getColGroup(String formatString, String delimiter) {
StringBuffer colgroup = new StringBuffer(128);
String[] formatStrings = formatString.split(delimiter);
colgroup.append("<colgroup>");
for (int i = 0; i < formatStrings.length; i++) {
colgroup.append("<col align=\"");
char align = formatStrings[i].trim().charAt(0);
switch (align) {
case 'l':
colgroup.append("left");
break;
case 'c':
colgroup.append("center");
break;
case 'r':
colgroup.append("right");
break;
default:
throw new RuntimeException("invalid format option");
}
colgroup.append("\"/>");
}
return colgroup.append("</colgroup>").toString();
}
/**
* Tests if the given string is a <code>delimiter</code> separated list of Formatting Information.<p>
*
* @param formatString the string to check
* @param delimiter the list separators
*
* @return true if the string is a <code>delimiter</code> separated list of Formatting Information
*/
private static boolean isFormattingInformation(String formatString, String delimiter) {
String[] formatStrings = formatString.split(delimiter);
for (int i = 0; i < formatStrings.length; i++) {
if (!formatStrings[i].trim().matches("[lcr]")) {
return false;
}
}
return true;
}
/**
* Removes the string delimiters from a key (as well as any white space
* outside the delimiters).<p>
*
* @param key the key (including delimiters)
*
* @return the key without delimiters
*/
private static String removeStringDelimiters(String key) {
String k = key.trim();
if (CmsStringUtil.isNotEmpty(k)) {
if (k.charAt(0) == TEXT_DELIMITER) {
k = k.substring(1);
}
if (k.charAt(k.length() - 1) == TEXT_DELIMITER) {
k = k.substring(0, k.length() - 1);
}
}
// replace excel protected quotations marks ("") by single quotation marks
k = CmsStringUtil.substitute(k, "\"\"", "\"");
return k;
}
/**
* Embeds the given content as cdata if neccessary.<p>
* Contents starting with "<" and ending with ">" are NOT embedded in order to allow content with tags.
*
* @param content the content
* @return the embedded content
*/
static String toXmlBody(String content) {
StringBuffer xmlBody = new StringBuffer(1024);
content = content.trim();
if (content.startsWith("<") && content.endsWith(">")) {
return content;
} else {
xmlBody.append("<![CDATA[");
xmlBody.append(content);
xmlBody.append("]]>");
}
return xmlBody.toString();
}
/**
* Uploads the specified file and transforms it to HTML.<p>
*
* @throws JspException if inclusion of error dialog fails
*/
public void actionUpload() throws JspException {
String newResname = "";
try {
if (CmsStringUtil.isNotEmpty(getParamCsvContent())) {
// csv content is pasted in the textarea
newResname = "csvcontent.html";
setParamNewResourceName("");
} else {
setParamCsvContent(new String(getFileContentFromUpload(), CmsEncoder.ENCODING_ISO_8859_1));
newResname = getCms().getRequestContext().getFileTranslator().translateResource(
CmsResource.getName(getParamResource().replace('\\', '/')));
newResname = CmsStringUtil.changeFileNameSuffixTo(newResname, "html");
setParamNewResourceName(newResname);
}
setParamResource(newResname);
setParamResource(computeFullResourceName());
int resTypeId = OpenCms.getResourceManager().getDefaultTypeForName(newResname).getTypeId();
CmsProperty styleProp = CmsProperty.getNullProperty();
// set the delimiter
String delimiter = getParamDelimiter();
if (TABULATOR.equals(delimiter)) {
delimiter = "\t";
} else if (BEST_DELIMITER.equals(delimiter)) {
delimiter = getPreferredDelimiter(getParamCsvContent());
}
setParamDelimiter(delimiter);
// transform csv to html
String xmlContent = "";
try {
xmlContent = getTableHtml();
} catch (IOException e) {
throw new CmsXmlException(Messages.get().container(Messages.ERR_CSV_XML_TRANSFORMATION_FAILED_0));
}
// if xslt file parameter is set, transform the raw html and set the css stylesheet property
// of the converted file to that of the stylesheet
if (CmsStringUtil.isNotEmpty(getParamXsltFile())) {
xmlContent = applyXslTransformation(getParamXsltFile(), xmlContent);
styleProp = getCms().readPropertyObject(
getParamXsltFile(),
CmsPropertyDefinition.PROPERTY_STYLESHEET,
true);
}
byte[] content = xmlContent.getBytes();
try {
// create the resource
getCms().createResource(getParamResource(), resTypeId, content, Collections.EMPTY_LIST);
} catch (CmsException e) {
// resource was present, overwrite it
getCms().lockResource(getParamResource());
getCms().replaceResource(getParamResource(), resTypeId, content, null);
}
// copy xslt stylesheet-property to the new resource
if (!styleProp.isNullProperty()) {
getCms().writePropertyObject(getParamResource(), styleProp);
}
} catch (Throwable e) {
// error uploading file, show error dialog
setParamMessage(Messages.get().getBundle(getLocale()).key(Messages.ERR_TABLE_IMPORT_FAILED_0));
includeErrorpage(this, e);
}
}
/**
* Applies a XSLT Transformation to the xmlContent.<p>
*
* The method does not use DOM4J, because iso-8859-1 code ist not transformed correctly.
*
* @param xsltFile the XSLT transformation file
* @param xmlContent the XML content to transform
*
* @return the transformed xml
*
* @throws Exception if something goes wrong
*/
public String applyXslTransformation(String xsltFile, String xmlContent) throws Exception {
// JAXP reads data
Source xmlSource = new StreamSource(new StringReader(xmlContent));
String xsltString = new String(getCms().readFile(xsltFile).getContents());
Source xsltSource = new StreamSource(new StringReader(xsltString));
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
StringWriter writer = new StringWriter();
trans.transform(xmlSource, new StreamResult(writer));
String result = writer.toString();
// cut of the prefacing declaration '<?xml version="1.0" encoding="UTF-8"?>'
if (result.startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")) {
return result.substring(38);
} else {
return result;
}
}
/**
* Builds a html select for Delimiters.
*
* @return html select code with the possible available xslt files
*/
public String buildDelimiterSelect() {
Object[] optionStrings = new Object[] {
key("input.bestmatching"),
key("input.semicolon"),
key("input.comma"),
key("input.tab")};
List options = new ArrayList(Arrays.asList(optionStrings));
List values = new ArrayList(Arrays.asList(new Object[] {"best", ";", ",", "tab"}));
String parameters = "name=\"" + PARAM_DELIMITER + "\" class=\"maxwidth\"";
return buildSelect(parameters, options, values, 0);
}
/**
* Builds a html select for the XSLT files.
*
* @return html select code with the possible available xslt files
*/
public String buildXsltSelect() {
// read all xslt files
List xsltFiles = getXsltFiles();
if (xsltFiles.size() > 0) {
List options = new ArrayList();
List values = new ArrayList();
options.add(key("input.nostyle"));
values.add("");
CmsResource resource;
CmsProperty titleProp = null;
Iterator i = xsltFiles.iterator();
while (i.hasNext()) {
resource = (CmsResource)i.next();
try {
titleProp = getCms().readPropertyObject(
resource.getRootPath(),
CmsPropertyDefinition.PROPERTY_TITLE,
false);
} catch (CmsException e) {
if (LOG.isWarnEnabled()) {
LOG.warn(e);
}
}
values.add(resource.getRootPath());
// display the title if set or otherwise the filename
if (titleProp.isNullProperty()) {
options.add("[" + resource.getName() + "]");
} else {
options.add(titleProp.getValue());
}
}
StringBuffer result = new StringBuffer(512);
// build a select box and a table row around
result.append("<tr><td style=\"white-space: nowrap;\" unselectable=\"on\">");
result.append(key("input.xsltfile"));
result.append("</td><td class=\"maxwidth\">");
String parameters = "class=\"maxwidth\" name=\"" + PARAM_XSLTFILE + "\"";
result.append(buildSelect(parameters, options, values, 0));
result.append("</td><tr>");
return result.toString();
} else {
return "";
}
}
/**
* Returns the content of the file upload and sets the resource name.<p>
*
* @return the byte content of the uploaded file
* @throws CmsWorkplaceException if the filesize if greater that maxFileSizeBytes or if the upload file cannot be found
*/
public byte[] getFileContentFromUpload() throws CmsWorkplaceException {
byte[] content;
// get the file item from the multipart request
Iterator i = getMultiPartFileItems().iterator();
FileItem fi = null;
while (i.hasNext()) {
fi = (FileItem)i.next();
if (fi.getName() != null) {
// found the file object, leave iteration
break;
} else {
// this is no file object, check next item
continue;
}
}
if (fi != null) {
long size = fi.getSize();
if (size == 0) {
throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
}
long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
// check file size
if (maxFileSizeBytes > 0 && size > maxFileSizeBytes) {
throw new CmsWorkplaceException(Messages.get().container(
Messages.ERR_UPLOAD_FILE_SIZE_TOO_HIGH_1,
new Long(maxFileSizeBytes / 1024)));
}
content = fi.get();
fi.delete();
setParamResource(fi.getName());
} else {
throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
}
return content;
}
/**
* Returns the height of the head frameset.<p>
*
* @return the height of the head frameset
*/
public String getHeadFrameSetHeight() {
return FRAMEHEIGHT;
}
/**
* Returns the pasted csv content.<p>
*
* @return the csv content
*/
public String getParamCsvContent() {
return m_paramCsvContent;
}
/**
* Returns the delimiter to separate the CSV values.<p>
*
* @return the delimiter to separate the CSV values
*/
public String getParamDelimiter() {
return m_paramDelimiter;
}
/**
* Returns the xslt file to transform the xml with.<p>
*
* @return the path to the xslt file to transform the xml with or null if it is not set
*/
public String getParamXsltFile() {
return m_paramXsltFile;
}
/**
* returns the Delimiter that most often occures in the CSV content.<p>
*
* @param csvData the comma separated values
*
* @return the delimiter, that is best applicable for the csvData
*/
public String getPreferredDelimiter(String csvData) {
String bestMatch = "";
int bestMatchCount = 0;
// find for each delimiter, how often it occures in the String csvData
for (int i = 0; i < DELIMITERS.length; i++) {
int currentCount = csvData.split(DELIMITERS[i]).length;
if (currentCount > bestMatchCount) {
bestMatch = DELIMITERS[i];
bestMatchCount = currentCount;
}
}
return bestMatch;
}
/**
* Returns a list of CmsResources with the xslt files in the modules folder.<p>
*
* @return a list of the available xslt files
*/
public List getXsltFiles() {
List result = new ArrayList();
try {
// find all files of generic xmlcontent in the modules folder
Iterator xmlFiles = getCms().readResources(CmsWorkplace.VFS_PATH_MODULES,
CmsResourceFilter.DEFAULT_FILES.addRequireType(CmsResourceTypePlain.getStaticTypeId()),
true).iterator();
while (xmlFiles.hasNext()) {
CmsResource xmlFile = (CmsResource)xmlFiles.next();
// filter all files with the suffix .table.xml
if (xmlFile.getName().endsWith(TABLE_XSLT_SUFFIX)) {
result.add(xmlFile);
}
}
} catch (CmsException e) {
LOG.error(e);
}
return result;
}
/**
* Sets the pasted csv content.<p>
*
* @param csvContent the csv content to set
*/
public void setParamCsvContent(String csvContent) {
m_paramCsvContent = csvContent;
}
/**
* Sets the delimiter to separate the CSV values.<p>
*
* @param delimiter the delimiter to separate the CSV values.
*/
public void setParamDelimiter(String delimiter) {
m_paramDelimiter = delimiter;
}
/**
* Sets the path to the xslt file.<p>
*
* @param xsltFile the file to transform the xml with.
*/
public void setParamXsltFile(String xsltFile) {
m_paramXsltFile = xsltFile;
}
/**
* Converts CSV data to xml.<p>
*
* @return a XML representation of the csv data
*
* @param csvData the csv data to convert
* @param colGroup the format definitions for the table columns, can be null
* @param delimiter the delimiter to separate the values with
*
* @throws IOException if there is an IO problem
*/
private String getTableHtml() throws IOException {
String csvData = getParamCsvContent();
String lineSeparator = System.getProperty("line.separator");
String formatString = csvData.substring(0, csvData.indexOf(lineSeparator));
String delimiter = getParamDelimiter();
StringBuffer xml = new StringBuffer("<table>");
if (isFormattingInformation(formatString, delimiter)) {
// transform formatting to HTML colgroup
xml.append(getColGroup(formatString, delimiter));
// cut of first line
csvData = csvData.substring(formatString.length() + lineSeparator.length());
}
String line;
BufferedReader br = new BufferedReader(new StringReader(csvData));
while ((line = br.readLine()) != null) {
xml.append("<tr>\n");
// must use tokenizer with delimiters include in order to handle empty cells appropriately
StringTokenizer t = new StringTokenizer(line, delimiter, true);
boolean hasValue = false;
while (t.hasMoreElements()) {
String item = (String)t.nextElement();
if (!hasValue) {
xml.append("\t<td>");
hasValue = true;
}
if (!item.equals(delimiter)) {
// remove enclosing delimiters
item = removeStringDelimiters(item);
// in order to allow links, lines starting and ending with tag delimiters (< ...>) remains unescaped
if (item.startsWith(TAG_START_DELIMITER) && item.endsWith(TAG_END_DELIMITER)) {
xml.append(item);
} else {
xml.append(CmsStringUtil.escapeHtml(item));
}
} else {
xml.append("</td>\n");
hasValue = false;
}
}
if (hasValue) {
xml.append("</td>\n");
} else {
xml.append("<td></td>\n");
}
xml.append("</tr>\n");
}
return xml.append("</table>").toString();
}
} |
package com.treasure_data.client;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.json.simple.JSONValue;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.treasure_data.auth.TreasureDataCredentials;
import com.treasure_data.model.CreateItemTableRequest;
import com.treasure_data.model.CreateLogTableRequest;
import com.treasure_data.model.CreateTableRequest;
import com.treasure_data.model.CreateTableResult;
import com.treasure_data.model.DataType;
import com.treasure_data.model.Database;
public class TestCreateTable extends
PostMethodTestUtil<CreateTableRequest, CreateTableResult, DefaultClientAdaptorImpl> {
private String databaseName;
private String tableName;
private CreateTableRequest request;
@Override
public DefaultClientAdaptorImpl createClientAdaptorImpl(Config conf) {
return new DefaultClientAdaptorImpl(conf);
}
@Before
public void createResources() throws Exception {
super.createResources();
databaseName = "testdb";
tableName = "testtbl";
request = new CreateTableRequest(new Database(databaseName), tableName);
}
@After
public void deleteResources() throws Exception {
super.deleteResources();
databaseName = null;
tableName = null;
request = null;
}
@Test @Ignore
public void testCreateTable00() throws Exception {
Properties props = new Properties();
props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties"));
Config conf = new Config();
conf.setCredentials(new TreasureDataCredentials(props));
DefaultClientAdaptorImpl clientAdaptor = new DefaultClientAdaptorImpl(conf);
String databaseName = "mugadb";
Database database = new Database(databaseName);
try {
CreateTableRequest request = new CreateTableRequest(database, "test01");
CreateTableResult result = clientAdaptor.createTable(request);
System.out.println(result.getTable().getName());
} catch (ClientException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
// delete database
//clientAdaptor.deleteDatabase(new DeleteDatabaseRequest(databaseName));
}
}
@Test @Ignore
public void testCreateTable01() throws Exception {
Properties props = new Properties();
props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties"));
Config conf = new Config();
conf.setCredentials(new TreasureDataCredentials(props));
DefaultClientAdaptorImpl clientAdaptor = new DefaultClientAdaptorImpl(conf);
String databaseName = "mugadb";
Database database = new Database(databaseName);
try {
//CreateTableRequest request = new CreateItemTableRequest(database, "test01", "key", DataType.STRING);
CreateTableRequest request = new CreateLogTableRequest(database, "test02");
CreateTableResult result = clientAdaptor.createTable(request);
System.out.println(result.getTable().getName());
} catch (ClientException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
// delete database
//clientAdaptor.deleteDatabase(new DeleteDatabaseRequest(databaseName));
}
}
@Override
public void checkNormalBehavior0() throws Exception {
CreateTableResult result = doBusinessLogic();
assertEquals(databaseName, result.getDatabase().getName());
}
@Override
public String getJSONTextForChecking() {
Map<String, String> map = new HashMap<String, String>();
map.put("database", "testdb");
map.put("table", "testtbl");
map.put("type", "log");
return JSONValue.toJSONString(map);
}
@Override
public CreateTableResult doBusinessLogic() throws Exception {
return clientAdaptor.createTable(request);
}
} |
package com.zaxxer.hikari.performance;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import javax.sql.DataSource;
import com.jolbox.bonecp.BoneCPConfig;
import com.jolbox.bonecp.BoneCPDataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class Benchmarks
{
private static final int THREADS = Integer.getInteger("threads", 100);
private DataSource ds;
public static void main(String... args)
{
if (args.length == 0)
{
System.err.println("Start with one of: hikari, bone, c3p0, dbcp");
System.exit(0);
}
Benchmarks benchmarks = new Benchmarks();
if (args[0].equals("hikari"))
{
benchmarks.ds = benchmarks.setupHikari();
System.out.println("Benchmarking HikariCP");
}
else if (args[0].equals("bone"))
{
benchmarks.ds = benchmarks.setupBone();
System.out.println("Benchmarking BoneCP");
}
System.out.println("\nMixedBench");
System.out.println(" Warming up JIT");
benchmarks.startMixedBench();
benchmarks.startMixedBench();
System.out.println(" MixedBench Final Timing Runs");
benchmarks.startMixedBench();
benchmarks.startMixedBench();
benchmarks.startMixedBench();
System.out.println("\nBoneBench");
System.out.println(" Warming up JIT");
benchmarks.startSillyBench();
System.out.println(" BoneBench Final Timing Run");
benchmarks.startSillyBench();
benchmarks.startSillyBench();
benchmarks.startSillyBench();
}
private DataSource setupHikari()
{
HikariConfig config = new HikariConfig();
config.setAcquireIncrement(5);
config.setMinimumPoolSize(20);
config.setMaximumPoolSize(200);
config.setConnectionTimeoutMs(5000);
config.setJdbc4ConnectionTest(true);
config.setDataSourceClassName("com.zaxxer.hikari.performance.StubDataSource");
config.setProxyFactoryType(System.getProperty("testProxy", "javassist"));
HikariDataSource ds = new HikariDataSource();
ds.setConfiguration(config);
return ds;
}
private DataSource setupBone()
{
try
{
Class.forName("com.zaxxer.hikari.performance.StubDriver");
}
catch (ClassNotFoundException e)
{
throw new RuntimeException(e);
}
BoneCPConfig config = new BoneCPConfig();
config.setAcquireIncrement(5);
config.setMinConnectionsPerPartition(20);
config.setMaxConnectionsPerPartition(200);
config.setConnectionTimeoutInMs(5000);
config.setConnectionTestStatement("VALUES 1");
config.setCloseOpenStatements(true);
config.setDisableConnectionTracking(true);
config.setJdbcUrl("jdbc:stub");
config.setUsername("nobody");
config.setPassword("nopass");
BoneCPDataSource ds = new BoneCPDataSource(config);
return ds;
}
private void startMixedBench()
{
CyclicBarrier barrier = new CyclicBarrier(THREADS);
CountDownLatch latch = new CountDownLatch(THREADS);
Measurable[] runners = new Measurable[THREADS];
for (int i = 0; i < THREADS; i++)
{
runners[i] = new MixedRunner(barrier, latch);
}
runAndMeasure(runners, latch, "ms");
}
private void startSillyBench()
{
CyclicBarrier barrier = new CyclicBarrier(THREADS);
CountDownLatch latch = new CountDownLatch(THREADS);
Measurable[] runners = new Measurable[THREADS];
for (int i = 0; i < THREADS; i++)
{
runners[i] = new SillyRunner(barrier, latch);
}
runAndMeasure(runners, latch, "ns");
}
private void runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < THREADS; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[THREADS];
long min = Integer.MAX_VALUE, max = 0;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
track[i++] = elapsed;
min = Math.min(min, elapsed);
max = Math.max(max, elapsed);
}
long avg = min + ((max - min) / 2);
Arrays.sort(track);
long med = track[THREADS / 2];
System.out.printf(" max=%d%4$s, avg=%d%4$s, med=%d%4$s\n", max, avg, med, timeUnit);
}
private class MixedRunner implements Measurable
{
private CyclicBarrier barrier;
private CountDownLatch latch;
private long start;
private long finish;
private int counter;
public MixedRunner(CyclicBarrier barrier, CountDownLatch latch)
{
this.barrier = barrier;
this.latch = latch;
}
public void run()
{
try
{
barrier.await();
start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++)
{
Connection connection = ds.getConnection();
for (int j = 0; j < 100; j++)
{
PreparedStatement statement = connection.prepareStatement("INSERT INTO test (column) VALUES (?)");
for (int k = 0; k < 100; k++)
{
statement.setInt(1, i);
statement.setInt(1, j);
statement.setInt(1, k);
statement.addBatch();
}
statement.executeBatch();
statement.close();
statement = connection.prepareStatement("SELECT * FROM test WHERE foo=?");
ResultSet resultSet = statement.executeQuery();
for (int k = 0; k < 100; k++)
{
resultSet.next();
counter += resultSet.getInt(1); // ensures the JIT doesn't optimize this loop away
}
resultSet.close();
statement.close();
}
connection.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
finish = System.currentTimeMillis();
latch.countDown();
}
}
public long getElapsed()
{
return finish - start;
}
public long getCounter()
{
return counter;
}
}
private class SillyRunner implements Measurable
{
private CyclicBarrier barrier;
private CountDownLatch latch;
private long start;
private long finish;
public SillyRunner(CyclicBarrier barrier, CountDownLatch latch)
{
this.barrier = barrier;
this.latch = latch;
}
public void run()
{
try
{
barrier.await();
start = System.nanoTime();
for (int i = 0; i < 100; i++)
{
Connection connection = ds.getConnection();
connection.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
finish = System.nanoTime();
latch.countDown();
}
}
public long getElapsed()
{
return finish - start;
}
}
private interface Measurable extends Runnable
{
long getElapsed();
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in th future.
package org.usfirst.frc330.Beachbot2013Java;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
import edu.wpi.first.wpilibj.DigitalOutput;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Encoder.PIDSourceParameter;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static SpeedController chassisLeftDriveJaguar1;
public static SpeedController chassisLeftDriveJaguar2;
public static SpeedController chassisRightDriveJaguar1;
public static SpeedController chassisRightDriveJaguar2;
public static RobotDrive chassisRobotDrive;
public static Gyro chassisGyro;
public static Encoder chassisLeftDriveEncoder;
public static Encoder chassisRightDriveEncoder;
public static Compressor chassisCompressor;
public static DoubleSolenoid chassisShiftSolenoid;
public static SpeedController frisbeePickupFrisbeePickupController;
public static DoubleSolenoid frisbeePickupPickupSolenoid;
public static SpeedController shooterHighShooterHighController;
public static Encoder shooterHighShooterHighEncoder;
public static DoubleSolenoid shooterLowShooterLoadSolenoid;
public static SpeedController shooterLowShooterLowController;
public static Encoder shooterLowShooterLowEncoder;
public static DigitalOutput visionHighShooterLED;
public static DigitalOutput visionLowShooterLED;
public static SpeedController armArmSpeedController;
public static AnalogChannel armPotentiometer;
public static DoubleSolenoid armBrakeArmSolenoid;
public static DigitalOutput lCDmosi;
public static DigitalOutput lCDcs;
public static DigitalOutput lCDclk;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static void init() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
chassisLeftDriveJaguar1 = new Jaguar(1, 1);
LiveWindow.addActuator("Chassis", "LeftDriveJaguar1", (Jaguar) chassisLeftDriveJaguar1);
chassisLeftDriveJaguar2 = new Jaguar(1, 2);
LiveWindow.addActuator("Chassis", "LeftDriveJaguar2", (Jaguar) chassisLeftDriveJaguar2);
chassisRightDriveJaguar1 = new Jaguar(1, 3);
LiveWindow.addActuator("Chassis", "RightDriveJaguar1", (Jaguar) chassisRightDriveJaguar1);
chassisRightDriveJaguar2 = new Jaguar(1, 4);
LiveWindow.addActuator("Chassis", "RightDriveJaguar2", (Jaguar) chassisRightDriveJaguar2);
chassisRobotDrive = new RobotDrive(chassisLeftDriveJaguar1, chassisLeftDriveJaguar2,
chassisRightDriveJaguar1, chassisRightDriveJaguar2);
chassisRobotDrive.setSafetyEnabled(true);
chassisRobotDrive.setExpiration(0.1);
chassisRobotDrive.setSensitivity(0.5);
chassisRobotDrive.setMaxOutput(1.0);
chassisGyro = new Gyro(1, 1);
LiveWindow.addSensor("Chassis", "Gyro", chassisGyro);
chassisGyro.setSensitivity(0.007);
chassisLeftDriveEncoder = new Encoder(1, 5, 1, 6, true, EncodingType.k4X);
LiveWindow.addSensor("Chassis", "LeftDriveEncoder", chassisLeftDriveEncoder);
chassisLeftDriveEncoder.setDistancePerPulse(0.07539822368615504);
chassisLeftDriveEncoder.setPIDSourceParameter(PIDSourceParameter.kDistance);
chassisLeftDriveEncoder.start();
chassisRightDriveEncoder = new Encoder(1, 7, 1, 8, true, EncodingType.k4X);
LiveWindow.addSensor("Chassis", "RightDriveEncoder", chassisRightDriveEncoder);
chassisRightDriveEncoder.setDistancePerPulse(0.07539822368615504);
chassisRightDriveEncoder.setPIDSourceParameter(PIDSourceParameter.kDistance);
chassisRightDriveEncoder.start();
chassisCompressor = new Compressor(1, 14, 1, 8);
chassisShiftSolenoid = new DoubleSolenoid(1, 3, 4);
frisbeePickupFrisbeePickupController = new Victor(1, 8);
LiveWindow.addActuator("FrisbeePickup", "FrisbeePickupController", (Victor) frisbeePickupFrisbeePickupController);
frisbeePickupPickupSolenoid = new DoubleSolenoid(1, 1, 2);
shooterHighShooterHighController = new Talon(1, 5);
LiveWindow.addActuator("Shooter High", "ShooterHighController", (Talon) shooterHighShooterHighController);
shooterHighShooterHighEncoder = new Encoder(1, 1, 1, 2, false, EncodingType.k1X);
LiveWindow.addSensor("Shooter High", "ShooterHighEncoder", shooterHighShooterHighEncoder);
shooterHighShooterHighEncoder.setDistancePerPulse(1.0);
shooterHighShooterHighEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
shooterHighShooterHighEncoder.start();
shooterLowShooterLoadSolenoid = new DoubleSolenoid(1, 5, 6);
shooterLowShooterLowController = new Talon(1, 6);
LiveWindow.addActuator("Shooter Low", "ShooterLowController", (Talon) shooterLowShooterLowController);
shooterLowShooterLowEncoder = new Encoder(1, 3, 1, 4, false, EncodingType.k1X);
LiveWindow.addSensor("Shooter Low", "ShooterLowEncoder", shooterLowShooterLowEncoder);
shooterLowShooterLowEncoder.setDistancePerPulse(1.0);
shooterLowShooterLowEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
shooterLowShooterLowEncoder.start();
visionHighShooterLED = new DigitalOutput(1, 9);
visionLowShooterLED = new DigitalOutput(1, 10);
armArmSpeedController = new Jaguar(1, 7);
LiveWindow.addActuator("Arm", "ArmSpeedController", (Jaguar) armArmSpeedController);
armPotentiometer = new AnalogChannel(1, 3);
LiveWindow.addSensor("Arm", "Potentiometer", armPotentiometer);
armBrakeArmSolenoid = new DoubleSolenoid(1, 7, 8);
lCDmosi = new DigitalOutput(1, 11);
lCDcs = new DigitalOutput(1, 12);
lCDclk = new DigitalOutput(1, 13);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
LiveWindow.addActuator("Chassis", "chassisShiftSolenoid", chassisShiftSolenoid);
LiveWindow.addActuator("FrisbeePickup", "frisbeePickupPickupSolenoid", frisbeePickupPickupSolenoid);
LiveWindow.addActuator("ShooterLow", "shooterLowShooterLoadSolenoid", shooterLowShooterLoadSolenoid);
LiveWindow.addActuator("Arm", "armBrakeArmSolenoid", armBrakeArmSolenoid);
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc692.AerialAssist2014;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
import edu.wpi.first.wpilibj.PIDSource.PIDSourceParameter;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import java.util.Vector;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static SpeedController driveTrainlefttDriveVictor1;
public static SpeedController driveTrainleftDriveVictor2;
public static SpeedController driveTrainrightDriveVictor1;
public static SpeedController driveTrainrightDriveVictor2;
public static RobotDrive driveTrainRobotDrive;
public static Encoder driveTrainleftEncoder;
public static Encoder driveTrainrightEncoder;
public static SpeedController shootershooterMotor1;
public static DigitalInput shootershooterLimit;
public static SpeedController gatherergathererMotor;
public static DoubleSolenoid gathererupAndDownGatherer;
public static DoubleSolenoid pneumaticsForDrivehighAndLowShift;
public static DoubleSolenoid pneumaticsForPasserPusherpasserPusher;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static void init() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
driveTrainlefttDriveVictor1 = new Victor(1, 4);
LiveWindow.addActuator("DriveTrain", "lefttDriveVictor1", (Victor) driveTrainlefttDriveVictor1);
driveTrainleftDriveVictor2 = new Victor(1, 3);
LiveWindow.addActuator("DriveTrain", "leftDriveVictor2", (Victor) driveTrainleftDriveVictor2);
driveTrainrightDriveVictor1 = new Victor(1, 1);
LiveWindow.addActuator("DriveTrain", "rightDriveVictor1", (Victor) driveTrainrightDriveVictor1);
driveTrainrightDriveVictor2 = new Victor(1, 7);
LiveWindow.addActuator("DriveTrain", "rightDriveVictor2", (Victor) driveTrainrightDriveVictor2);
driveTrainRobotDrive = new RobotDrive(driveTrainlefttDriveVictor1, driveTrainleftDriveVictor2,
driveTrainrightDriveVictor1, driveTrainrightDriveVictor2);
driveTrainRobotDrive.setSafetyEnabled(true);
driveTrainRobotDrive.setExpiration(0.1);
driveTrainRobotDrive.setSensitivity(0.5);
driveTrainRobotDrive.setMaxOutput(1.0);
driveTrainleftEncoder = new Encoder(1, 2, 1, 3, false, EncodingType.k4X);
LiveWindow.addSensor("DriveTrain", "leftEncoder", driveTrainleftEncoder);
driveTrainleftEncoder.setDistancePerPulse(1.0);
driveTrainleftEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
driveTrainleftEncoder.start();
driveTrainrightEncoder = new Encoder(1, 4, 1, 5, false, EncodingType.k4X);
LiveWindow.addSensor("DriveTrain", "rightEncoder", driveTrainrightEncoder);
driveTrainrightEncoder.setDistancePerPulse(1.0);
driveTrainrightEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
driveTrainrightEncoder.start();
shootershooterMotor1 = new Victor(1, 5);
LiveWindow.addActuator("Shooter", "shooterMotor1", (Victor) shootershooterMotor1);
shootershooterLimit = new DigitalInput(1, 9);
LiveWindow.addSensor("Shooter", "shooterLimit", shootershooterLimit);
gatherergathererMotor = new Victor(1, 8);
LiveWindow.addActuator("Gatherer", "gathererMotor", (Victor) gatherergathererMotor);
gathererupAndDownGatherer = new DoubleSolenoid(1, 3, 4);
pneumaticsForDrivehighAndLowShift = new DoubleSolenoid(1, 5, 8);
pneumaticsForPasserPusherpasserPusher = new DoubleSolenoid(1, 7, 6);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
/*
* THINGS THAT NEED TO GET WORKED ON:
* - camera image
* - pneumatics (electrical)
* - limit switch
*/
}
} |
package eu.project.ttc.test.func;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.AbstractIterableAssert;
import org.assertj.core.util.Lists;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import eu.project.ttc.models.Term;
import eu.project.ttc.models.TermIndex;
import eu.project.ttc.models.TermVariation;
import eu.project.ttc.models.VariationType;
public class TermIndexAssert extends AbstractAssert<TermIndexAssert, TermIndex> {
protected TermIndexAssert(TermIndex actual) {
super(actual, TermIndexAssert.class);
}
public TermIndexAssert containsVariation(String baseGroupingKey, VariationType type, String variantGroupingKey) {
if(failToFindTerms(baseGroupingKey, variantGroupingKey))
return this;
List<TermVariation> potentialVariations = Lists.newArrayList();
Set<TermVariation> sameType = Sets.newHashSet();
for(TermVariation tv:getVariations()) {
if(tv.getBase().getGroupingKey().equals(baseGroupingKey)
&& tv.getVariant().getGroupingKey().equals(variantGroupingKey)) {
potentialVariations.add(tv);
if(tv.getVariationType() == type)
return this;
}
if(type == tv.getVariationType())
sameType.add(tv);
}
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(baseGroupingKey).getVariations(type)));
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(variantGroupingKey).getBases(type)));
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(baseGroupingKey).getVariations()));
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(variantGroupingKey).getBases()));
potentialVariations.addAll(sameType);
failWithMessage("No such variation <%s--%s--%s> found in term index. Closed variations: <%s>",
baseGroupingKey, type, variantGroupingKey,
Joiner.on(", ").join(potentialVariations.subList(0, Ints.min(10, potentialVariations.size())))
);
return this;
}
private boolean failToFindTerms(String... groupingKeys) {
boolean failed = false;
for(String gKey:groupingKeys) {
if(actual.getTermByGroupingKey(gKey) == null) {
failed = true;
failWithMessage("Could not find term <%s> in termIndex", gKey);
}
}
return failed;
}
public TermIndexAssert containsVariation(String baseGroupingKey, VariationType type, String variantGroupingKey, Object info) {
if(failToFindTerms(baseGroupingKey, variantGroupingKey))
return this;
List<TermVariation> potentialVariations = Lists.newArrayList();
Set<TermVariation> sameType = Sets.newHashSet();
for(TermVariation tv:getVariations()) {
if(tv.getBase().getGroupingKey().equals(baseGroupingKey)
&& tv.getVariant().getGroupingKey().equals(variantGroupingKey)) {
potentialVariations.add(tv);
if(tv.getVariationType() == type && Objects.equal(info, tv.getInfo()))
return this;
}
if(type == tv.getVariationType())
sameType.add(tv);
}
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(baseGroupingKey).getVariations(type)));
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(variantGroupingKey).getBases(type)));
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(baseGroupingKey).getVariations()));
potentialVariations.addAll(Sets.newHashSet(actual.getTermByGroupingKey(variantGroupingKey).getBases()));
potentialVariations.addAll(sameType);
failWithMessage("No such variation <%s--%s[%s]--%s> found in term index. Closed variations: <%s>",
baseGroupingKey, type,
info,
variantGroupingKey,
Joiner.on(", ").join(potentialVariations)
);
return this;
}
private Collection<TermVariation> getVariations() {
Set<TermVariation> termVariations = Sets.newHashSet();
for(Term t:actual.getTerms()) {
for(TermVariation v:t.getVariations())
termVariations.add(v);
}
return termVariations;
}
public TermIndexAssert hasNVariationsOfType(int expected, VariationType type) {
int cnt = 0;
for(TermVariation tv:getVariations()) {
if(tv.getVariationType() == type)
cnt++;
}
if(cnt != expected)
failWithMessage("Expected <%s> variations of type <%s>. Got: <%s>", expected, type, cnt);
return this;
}
public AbstractIterableAssert<?, ? extends Iterable<? extends TermVariation>, TermVariation> getVariationsHavingObject(Object object) {
Set<TermVariation> variations = Sets.newHashSet();
for(TermVariation v:getVariations())
if(Objects.equal(v.getInfo(), object))
variations.add(v);
return assertThat(variations);
}
} |
package org.jcodec.codecs.mpeg12;
import static org.jcodec.common.ArrayUtil.toByteArrayShifted;
import static org.jcodec.common.ArrayUtil.toByteArrayShifted2;
import static org.jcodec.common.ArrayUtil.toIntArray;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
public class MPEGPredOctTest {
static byte[] padded = toByteArrayShifted(new int[] {
10, 10, 10, 20, 30, 40, 40, 40, 40,
10, 10, 10, 20, 30, 40, 40, 40, 40,
10, 10, 10, 20, 30, 40, 40, 40, 40,
50, 50, 50, 60, 70, 80, 80, 80, 80,
90, 90, 90, 100, 110, 120, 120, 120, 120,
130, 130, 130, 140, 150, 160, 160, 160, 160,
130, 130, 130, 140, 150, 160, 160, 160, 160,
130, 130, 130, 140, 150, 160, 160, 160, 160,
130, 130, 130, 140, 150, 160, 160, 160, 160
});
static byte[] unpadded = toByteArrayShifted(new int[] {
10, 20, 30, 40,
50, 60, 70, 80,
90, 100, 110, 120,
130, 140, 150, 160
});
static int[][] interp = new int[][] {
/* 0-7,0 */
{ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160 },
{ 11, 21, 31, 40, 51, 61, 71, 80, 91, 101, 111, 120, 131, 141, 151, 160 },
{ 12, 22, 33, 41, 52, 62, 73, 81, 92, 102, 113, 121, 132, 142, 153, 161 },
{ 13, 24, 34, 41, 53, 64, 74, 81, 93, 104, 114, 121, 133, 144, 154, 161 },
{ 14, 25, 36, 41, 54, 65, 76, 81, 94, 105, 116, 121, 134, 145, 156, 161 },
{ 16, 26, 37, 40, 56, 66, 77, 80, 96, 106, 117, 120, 136, 146, 157, 160 },
{ 17, 28, 38, 40, 57, 68, 78, 80, 97, 108, 118, 120, 137, 148, 158, 160 },
{ 19, 29, 39, 40, 59, 69, 79, 80, 99, 109, 119, 120, 139, 149, 159, 160 },
/* 0-7,1 */
{ 13, 23, 33, 43, 55, 65, 75, 85, 95, 105, 115, 125, 132, 142, 152, 162 },
{ 14, 24, 34, 44, 56, 66, 76, 85, 96, 107, 117, 126, 133, 143, 153, 162 },
{ 15, 26, 36, 44, 57, 67, 78, 86, 97, 108, 118, 126, 134, 144, 155, 162 },
{ 16, 27, 37, 44, 58, 69, 79, 86, 98, 109, 119, 126, 135, 146, 156, 163 },
{ 17, 28, 39, 44, 59, 70, 81, 86, 100, 110, 121, 126, 136, 147, 158, 163 },
{ 19, 29, 40, 44, 61, 71, 82, 85, 101, 112, 122, 126, 138, 148, 159, 162 },
{ 20, 31, 41, 44, 62, 73, 83, 85, 103, 113, 124, 126, 139, 149, 160, 162 },
{ 22, 32, 42, 43, 64, 74, 84, 85, 104, 114, 125, 125, 141, 151, 161, 162 },
/* 0-7,2 */
{ 17, 27, 37, 47, 60, 70, 80, 90, 101, 111, 121, 131, 132, 142, 152, 162 },
{ 18, 28, 39, 48, 60, 71, 81, 90, 102, 113, 123, 132, 133, 143, 154, 163 },
{ 19, 30, 40, 48, 61, 72, 83, 90, 103, 114, 124, 132, 134, 145, 155, 163 },
{ 20, 31, 41, 48, 63, 73, 84, 90, 104, 115, 125, 132, 135, 146, 156, 163 },
{ 21, 32, 43, 48, 64, 75, 85, 90, 105, 116, 127, 132, 136, 147, 158, 163 },
{ 23, 34, 44, 48, 66, 76, 87, 90, 107, 118, 128, 132, 138, 149, 159, 163 },
{ 24, 35, 45, 48, 67, 77, 88, 90, 108, 119, 129, 132, 139, 150, 160, 163 },
{ 26, 36, 46, 47, 68, 78, 89, 90, 110, 120, 130, 131, 141, 151, 161, 162 },
/* 0-7,3 */
{ 22, 32, 42, 52, 65, 75, 85, 95, 107, 117, 127, 137, 133, 143, 153, 163 },
{ 23, 33, 43, 52, 65, 76, 86, 95, 107, 118, 128, 137, 134, 144, 154, 163 },
{ 24, 34, 45, 52, 66, 77, 88, 95, 108, 119, 129, 137, 135, 145, 156, 163 },
{ 25, 36, 46, 53, 68, 78, 89, 95, 110, 120, 131, 137, 136, 146, 157, 164 },
{ 26, 37, 48, 53, 69, 80, 90, 95, 111, 122, 132, 137, 137, 148, 159, 164 },
{ 28, 38, 49, 52, 71, 81, 92, 95, 112, 123, 134, 137, 139, 149, 160, 163 },
{ 29, 39, 50, 52, 72, 82, 93, 95, 114, 124, 135, 137, 140, 150, 161, 163 },
{ 31, 41, 51, 52, 73, 83, 94, 95, 115, 125, 136, 137, 141, 152, 162, 163 },
/* 0-7,4 */
{ 27, 37, 47, 57, 70, 80, 90, 100, 113, 123, 133, 143, 133, 143, 153, 163 },
{ 28, 38, 48, 57, 71, 81, 91, 100, 114, 124, 134, 144, 134, 144, 154, 164 },
{ 29, 39, 50, 57, 72, 82, 93, 101, 115, 126, 136, 144, 135, 146, 156, 164 },
{ 30, 41, 51, 58, 73, 84, 94, 101, 116, 127, 137, 144, 136, 147, 157, 164 },
{ 31, 42, 53, 58, 74, 85, 96, 101, 117, 128, 139, 144, 137, 148, 159, 164 },
{ 33, 43, 54, 57, 76, 86, 97, 100, 119, 129, 140, 144, 139, 149, 160, 164 },
{ 34, 44, 55, 57, 77, 88, 98, 100, 120, 131, 141, 144, 140, 151, 161, 164 },
{ 36, 46, 56, 57, 79, 89, 99, 100, 122, 132, 142, 143, 142, 152, 162, 163 },
/* 0-7,5 */
{ 33, 43, 53, 63, 75, 85, 95, 105, 118, 128, 138, 148, 132, 142, 152, 162 },
{ 34, 45, 55, 64, 76, 87, 97, 106, 119, 129, 139, 149, 133, 143, 153, 162 },
{ 35, 46, 56, 64, 77, 88, 98, 106, 120, 131, 141, 149, 134, 144, 155, 162 },
{ 36, 47, 58, 64, 78, 89, 99, 106, 121, 132, 142, 149, 135, 146, 156, 163 },
{ 38, 48, 59, 64, 80, 90, 101, 106, 122, 133, 144, 149, 136, 147, 158, 163 },
{ 39, 50, 60, 64, 81, 92, 102, 106, 124, 134, 145, 149, 138, 148, 159, 162 },
{ 41, 51, 62, 64, 83, 93, 104, 106, 125, 136, 146, 149, 139, 149, 160, 162 },
{ 42, 52, 63, 64, 84, 94, 105, 105, 127, 137, 147, 148, 141, 151, 161, 162 },
/* 0-7,6 */
{ 39, 49, 59, 69, 80, 90, 100, 110, 123, 133, 143, 153, 132, 142, 152, 162 },
{ 40, 50, 60, 69, 81, 92, 102, 111, 124, 134, 144, 153, 133, 143, 153, 162 },
{ 41, 51, 62, 69, 82, 93, 103, 111, 125, 135, 146, 153, 134, 144, 155, 162 },
{ 42, 52, 63, 69, 83, 94, 104, 111, 126, 136, 147, 154, 135, 146, 156, 163 },
{ 43, 54, 65, 70, 85, 95, 106, 111, 127, 138, 149, 154, 136, 147, 158, 163 },
{ 45, 55, 66, 69, 86, 97, 107, 111, 129, 139, 150, 153, 138, 148, 159, 162 },
{ 46, 56, 67, 69, 88, 98, 109, 111, 130, 140, 151, 153, 139, 149, 160, 162 },
{ 47, 58, 68, 69, 89, 99, 110, 110, 131, 142, 152, 153, 141, 151, 161, 162 },
/* 0-7,7 */
{ 45, 55, 65, 75, 85, 95, 105, 115, 127, 137, 147, 157, 130, 140, 150, 160 },
{ 45, 56, 66, 75, 86, 96, 106, 115, 128, 138, 148, 157, 131, 142, 152, 161 },
{ 46, 57, 68, 75, 87, 97, 108, 116, 129, 139, 150, 157, 132, 143, 153, 161 },
{ 48, 58, 69, 75, 88, 99, 109, 116, 130, 141, 151, 158, 133, 144, 154, 161 },
{ 49, 60, 70, 75, 89, 100, 111, 116, 131, 142, 153, 158, 135, 145, 156, 161 },
{ 51, 61, 72, 75, 91, 101, 112, 115, 133, 143, 154, 157, 136, 147, 157, 161 },
{ 52, 62, 73, 75, 92, 103, 113, 115, 134, 144, 155, 157, 138, 148, 159, 161 },
{ 53, 63, 74, 75, 94, 104, 114, 115, 136, 146, 156, 157, 139, 149, 160, 160 } };
public static int[] topFieldInt(int[] pix, int w, int h) {
int[] result = new int[pix.length * 2];
for (int i = 0, soff = 0, roff = 0; i < h; i++) {
for (int j = 0; j < w; j++, soff++, roff++) {
result[roff] = pix[soff];
}
for (int j = 0; j < w; j++, roff++) {
result[roff] = 0;
}
}
return result;
}
public static int[] bottomFieldInt(int[] pix, int w, int h) {
int[] result = new int[pix.length * 2];
for (int i = 0, soff = 0, roff = 0; i < h; i++) {
for (int j = 0; j < w; j++, roff++) {
result[roff] = 0;
}
for (int j = 0; j < w; j++, soff++, roff++) {
result[roff] = pix[soff];
}
}
return result;
}
public static byte[] topField(byte[] pix, int w, int h) {
byte[] result = new byte[pix.length * 2];
for (int i = 0, soff = 0, roff = 0; i < h; i++) {
for (int j = 0; j < w; j++, soff++, roff++) {
result[roff] = pix[soff];
}
for (int j = 0; j < w; j++, roff++) {
result[roff] = 0;
}
}
return result;
}
public static byte[] bottomField(byte[] pix, int w, int h) {
byte[] result = new byte[pix.length * 2];
for (int i = 0, soff = 0, roff = 0; i < h; i++) {
for (int j = 0; j < w; j++, roff++) {
result[roff] = 0;
}
for (int j = 0; j < w; j++, soff++, roff++) {
result[roff] = pix[soff];
}
}
return result;
}
@Test
public void testSafe() {
MPEGPredOct pred = new MPEGPredOct(new MPEGPred(new int[][] {}, 0, true));
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
int[] result = new int[16];
pred.predictPlane(padded, (2 << 3) + x, (2 << 3) + y, 9, 9, 0, 0, result, 0, 32, 32, 0);
Assert.assertArrayEquals("@ " + x + "," + y, interp[(y << 3) + x], result);
int[] result32 = new int[32];
pred.predictPlane(topField(padded, 9, 9), (2 << 3) + x, (2 << 3) + y, 9, 18, 1, 0, result32, 0, 32, 32,
1);
Assert.assertArrayEquals("@ " + x + "," + y + ":tff", topFieldInt(interp[(y << 3) + x], 4, 4),
result32);
Arrays.fill(result32, 0);
pred.predictPlane(bottomField(padded, 9, 9), (2 << 3) + x, (2 << 3) + y, 9, 18, 1, 1, result32, 1, 32,
32, 1);
Assert.assertArrayEquals("@ " + x + "," + y + ":bff",
bottomFieldInt(interp[(y << 3) + x], 4, 4), result32);
}
}
}
@Test
public void testUnsafe() {
MPEGPredOct pred = new MPEGPredOct(new MPEGPred(new int[][] {}, 0, true));
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
int[] result = new int[16];
pred.predictPlane(unpadded, x, y, 4, 4, 0, 0, result, 0, 32, 32, 0);
Assert.assertArrayEquals("@ " + x + "," + y, interp[(y << 3) + x], result);
int[] result32 = new int[32];
pred.predictPlane(topField(unpadded, 4, 4), x, y, 4, 8, 1, 0, result32, 0, 32, 32, 1);
Assert.assertArrayEquals("@ " + x + "," + y + ":tff", topFieldInt(interp[(y << 3) + x], 4, 4),
result32);
Arrays.fill(result32, 0);
pred.predictPlane(bottomField(unpadded, 4, 4), x, y, 4, 8, 1, 1, result32, 1, 32, 32, 1);
Assert.assertArrayEquals("@ " + x + "," + y + ":bff",
bottomFieldInt(interp[(y << 3) + x], 4, 4), result32);
}
}
}
} |
package org.mvel2.tests.core;
import org.mvel2.*;
import static org.mvel2.MVEL.*;
import org.mvel2.ast.ASTNode;
import org.mvel2.ast.Function;
import org.mvel2.ast.WithNode;
import org.mvel2.compiler.CompiledExpression;
import org.mvel2.compiler.ExpressionCompiler;
import org.mvel2.debug.DebugTools;
import org.mvel2.debug.Debugger;
import org.mvel2.debug.Frame;
import org.mvel2.integration.Interceptor;
import org.mvel2.integration.PropertyHandlerFactory;
import org.mvel2.integration.ResolverTools;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.ClassImportResolverFactory;
import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.integration.impl.StaticMethodImportResolverFactory;
import org.mvel2.optimizers.OptimizerFactory;
import org.mvel2.tests.core.res.*;
import org.mvel2.util.CompilerTools;
import org.mvel2.util.MethodStub;
import static org.mvel2.util.ParseTools.loadFromFile;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.util.Collections.unmodifiableCollection;
import java.util.List;
@SuppressWarnings({"ALL"})
public class CoreConfidenceTests extends AbstractTest {
public void testSingleProperty() {
assertEquals(false, test("fun"));
}
public void testMethodOnValue() {
assertEquals("DOG", test("foo.bar.name.toUpperCase()"));
}
public void testMethodOnValue2() {
assertEquals("DOG", test("foo. bar. name.toUpperCase()"));
}
public void testSimpleProperty() {
assertEquals("dog", test("foo.bar.name"));
}
public void testSimpleProperty2() {
assertEquals("cat", test("DATA"));
}
public void testPropertyViaDerivedClass() {
assertEquals("cat", test("derived.data"));
}
public void testDeepAssignment() {
Map map = createTestMap();
assertEquals("crap", testCompiledSimple("foo.bar.assignTest = 'crap'", map));
assertEquals("crap", testCompiledSimple("foo.bar.assignTest", map));
}
public void testDeepAssignment2() {
Map map = createTestMap();
ExpressionCompiler compiler = new ExpressionCompiler("foo.bar.age = 21");
ParserContext ctx = new ParserContext();
ctx.addInput("foo", Foo.class);
ctx.setStrongTyping(true);
CompiledExpression ce = compiler.compile(ctx);
executeExpression(ce, map);
assertEquals(((Foo) map.get("foo")).getBar().getAge(), 21);
}
public void testThroughInterface() {
assertEquals("FOOBAR!", test("testImpl.name"));
}
public void testThroughInterface2() {
assertEquals(true, test("testImpl.foo"));
}
public void testMapAccessWithMethodCall() {
assertEquals("happyBar", test("funMap['foo'].happy()"));
}
public void testSimpleIfStatement() {
test("if (true) { System.out.println(\"test!\") } \n");
}
public void testBooleanOperator() {
assertEquals(true, test("foo.bar.woof == true"));
}
public void testBooleanOperator2() {
assertEquals(false, test("foo.bar.woof == false"));
}
public void testBooleanOperator3() {
assertEquals(true, test("foo.bar.woof== true"));
}
public void testBooleanOperator4() {
assertEquals(false, test("foo.bar.woof ==false"));
}
public void testBooleanOperator5() {
assertEquals(true, test("foo.bar.woof == true"));
}
public void testBooleanOperator6() {
assertEquals(false, test("foo.bar.woof==false"));
}
public void testTextComparison() {
assertEquals(true, test("foo.bar.name == 'dog'"));
}
public void testNETextComparison() {
assertEquals(true, test("foo.bar.name != 'foo'"));
}
public void testChor() {
assertEquals("cat", test("a or b or c"));
}
public void testChorWithLiteral() {
assertEquals("fubar", test("a or 'fubar'"));
}
public void testNullCompare() {
assertEquals(true, test("c != null"));
}
public void testUninitializedInt() {
assertEquals(0, test("sarahl"));
}
public void testAnd() {
assertEquals(true, test("c != null && foo.bar.name == 'dog' && foo.bar.woof"));
}
public void testAnd2() {
assertEquals(true, test("c!=null&&foo.bar.name=='dog'&&foo.bar.woof"));
}
public void testMath() {
assertEquals(188.4d, test("pi * hour"));
}
public void testMath2() {
assertEquals(3, test("foo.number-1"));
}
public void testMath3() {
assertEquals((10d * 5d) * 2d / 3d, test("(10 * 5) * 2 / 3"));
}
public void testMath4() {
int val = (int) ((100d % 3d) * 2d - 1d / 1d + 8d + (5d * 2d));
assertEquals(val, test("(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"));
}
public void testMath4a() {
String expression = "(100 % 90) * 20 - 15 / 16 + 80 + (50 * 21)";
System.out.println("Expression: " + expression);
assertEquals(((100d % 90d) * 20d - 15d / 16d + 80d + (50d * 21d)), MVEL.eval(expression));
}
public void testMath5() {
assertEquals(300.5 / 5.3 / 2.1 / 1.5, test("300.5 / 5.3 / 2.1 / 1.5"));
}
public void testMath5a() {
String expression = "300.5 / 5.3 / 2.1 / 1.5";
System.out.println("Expression: " + expression);
assertEquals(300.5 / 5.3 / 2.1 / 1.5, MVEL.eval(expression));
}
public void testMath6() {
int val = (300 * 5 + 1) + 100 / 2 * 2;
assertEquals(val, test("(300 * five + 1) + (100 / 2 * 2)"));
}
public void testMath7() {
int val = (int) ((100d % 3d) * 2d - 1d / 1d + 8d + (5d * 2d));
assertEquals(val, test("(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"));
}
public void testMath8() {
double val = 5d * (100.56d * 30.1d);
assertEquals(val, test("5 * (100.56 * 30.1)"));
}
public void testPowerOf() {
assertEquals(25, test("5 ** 2"));
}
public void testWhileUsingImports() {
Map<String, Object> imports = new HashMap<String, Object>();
imports.put("ArrayList", java.util.ArrayList.class);
imports.put("List", java.util.List.class);
ParserContext context = new ParserContext(imports, null, "testfile");
ExpressionCompiler compiler = new ExpressionCompiler("List list = new ArrayList(); return (list == empty)");
assertTrue((Boolean) executeExpression(compiler.compile(context), new DefaultLocalVariableResolverFactory()));
}
public void testComplexExpression() {
assertEquals("bar", test("a = 'foo'; b = 'bar'; c = 'jim'; list = {a,b,c}; list[1]"));
}
public void testComplexAnd() {
assertEquals(true, test("(pi * hour) > 0 && foo.happy() == 'happyBar'"));
}
public void testOperatorPrecedence() {
String ex = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.1";
assertEquals(true, test(ex));
}
public void testOperatorPrecedence2() {
String ex = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2";
assertEquals(true, test(ex));
}
public void testOperatorPrecedence3() {
String ex = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2";
assertEquals(false, test(ex));
}
public void testOperatorPrecedence4() {
String ex = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.2";
assertEquals(true, test(ex));
}
public void testOperatorPrecedence5() {
String ex = "_x_001 == _x_001 / 2 - _x_001 + _x_001 + _x_001 / 2 && _x_002 / 2 == _x_002 / 2";
Map vars = new HashMap();
vars.put("_x_001", 500.2);
vars.put("_x_002", 200.9);
vars.put("_r_001", 701);
ExpressionCompiler compiler = new ExpressionCompiler(ex);
assertEquals(true, executeExpression(compiler.compile(), vars));
}
public void testShortPathExpression() {
assertEquals(null, MVEL.eval("3 > 4 && foo.toUC('test'); foo.register", new Base(), createTestMap()));
}
public void testShortPathExpression2() {
assertEquals(true, test("4 > 3 || foo.toUC('test')"));
}
public void testShortPathExpression4() {
assertEquals(true, test("4>3||foo.toUC('test')"));
}
public void testOrOperator() {
assertEquals(true, test("true||true"));
}
public void testOrOperator2() {
assertEquals(true, test("2 > 3 || 3 > 2"));
}
public void testOrOperator3() {
assertEquals(true, test("pi > 5 || pi > 6 || pi > 3"));
}
public void testShortPathExpression3() {
assertEquals(false, test("defnull != null && defnull.length() > 0"));
}
public void testModulus() {
assertEquals(38392 % 2,
test("38392 % 2"));
}
public void testLessThan() {
assertEquals(true, test("pi < 3.15"));
assertEquals(true, test("pi <= 3.14"));
assertEquals(false, test("pi > 3.14"));
assertEquals(true, test("pi >= 3.14"));
}
public void testMethodAccess() {
assertEquals("happyBar", test("foo.happy()"));
}
public void testMethodAccess2() {
assertEquals("FUBAR", test("foo.toUC( 'fubar' )"));
}
public void testMethodAccess3() {
assertEquals(true, test("equalityCheck(c, 'cat')"));
}
public void testMethodAccess4() {
assertEquals(null, test("readBack(null)"));
}
public void testMethodAccess5() {
assertEquals("nulltest", test("appendTwoStrings(null, 'test')"));
}
public void testMethodAccess6() {
assertEquals(true, test(" equalityCheck( c \n , \n 'cat' ) "));
}
public void testNegation() {
assertEquals(true, test("!fun && !fun"));
}
public void testNegation2() {
assertEquals(false, test("fun && !fun"));
}
public void testNegation3() {
assertEquals(true, test("!(fun && fun)"));
}
public void testNegation4() {
assertEquals(false, test("(fun && fun)"));
}
public void testNegation5() {
assertEquals(true, test("!false"));
}
public void testNegation6() {
assertEquals(false, test("!true"));
}
public void testNegation7() {
assertEquals(true, test("s = false; t = !s; t"));
}
public void testNegation8() {
assertEquals(true, test("s = false; t =! s; t"));
}
public void testMultiStatement() {
assertEquals(true, test("populate(); barfoo == 'sarah'"));
}
public void testAssignment() {
assertEquals(true, test("populate(); blahfoo = 'sarah'; blahfoo == 'sarah'"));
}
public void testAssignment2() {
assertEquals("sarah", test("populate(); blahfoo = barfoo"));
}
public void testAssignment3() {
assertEquals(java.lang.Integer.class, test("blah = 5").getClass());
}
public void testAssignment4() {
assertEquals(102, test("a = 100 + 1 + 1"));
}
public void testAssignment6() {
assertEquals("blip", test("array[zero] = array[zero+1]; array[zero]"));
}
public void testOr() {
assertEquals(true, test("fun || true"));
}
public void testLiteralPassThrough() {
assertEquals(true, test("true"));
}
public void testLiteralPassThrough2() {
assertEquals(false, test("false"));
}
public void testLiteralPassThrough3() {
assertEquals(null, test("null"));
}
public void testLiteralReduction1() {
assertEquals("foo", test("null or 'foo'"));
}
public void testRegEx() {
assertEquals(true, test("foo.bar.name ~= '[a-z].+'"));
}
public void testRegExNegate() {
assertEquals(false, test("!(foo.bar.name ~= '[a-z].+')"));
}
public void testRegEx2() {
assertEquals(true, test("foo.bar.name ~= '[a-z].+' && foo.bar.name != null"));
}
public void testRegEx3() {
assertEquals(true, test("foo.bar.name~='[a-z].+'&&foo.bar.name!=null"));
}
public void testBlank() {
assertEquals(true, test("'' == empty"));
}
public void testBlank2() {
assertEquals(true, test("BWAH == empty"));
}
public void testBooleanModeOnly2() {
assertEquals(false, (Object) DataConversion.convert(test("BWAH"), Boolean.class));
}
public void testBooleanModeOnly4() {
assertEquals(true, test("hour == (hour + 0)"));
}
public void testTernary() {
assertEquals("foobie", test("zero==0?'foobie':zero"));
}
public void testTernary2() {
assertEquals("blimpie", test("zero==1?'foobie':'blimpie'"));
}
public void testTernary3() {
assertEquals("foobiebarbie", test("zero==1?'foobie':'foobie'+'barbie'"));
}
public void testTernary5() {
assertEquals("skat!", test("isdef someWierdVar ? 'squid' : 'skat!';"));
}
public void testStrAppend() {
assertEquals("foobarcar", test("'foo' + 'bar' + 'car'"));
}
public void testStrAppend2() {
assertEquals("foobarcar1", test("'foobar' + 'car' + 1"));
}
public void testInstanceCheck1() {
assertEquals(true, test("c is java.lang.String"));
}
public void testInstanceCheck2() {
assertEquals(false, test("pi is java.lang.Integer"));
}
public void testInstanceCheck3() {
assertEquals(true, test("foo is org.mvel2.tests.core.res.Foo"));
}
public void testBitwiseOr1() {
assertEquals(6, test("2|4"));
}
public void testBitwiseOr2() {
assertEquals(true, test("(2 | 1) > 0"));
}
public void testBitwiseOr3() {
assertEquals(true, test("(2|1) == 3"));
}
public void testBitwiseOr4() {
assertEquals(2 | 5, test("2|five"));
}
public void testBitwiseAnd1() {
assertEquals(2, test("2 & 3"));
}
public void testBitwiseAnd2() {
assertEquals(5 & 3, test("five & 3"));
}
public void testShiftLeft() {
assertEquals(4, test("2 << 1"));
}
public void testShiftLeft2() {
assertEquals(5 << 1, test("five << 1"));
}
public void testUnsignedShiftLeft() {
assertEquals(2, test("-2 <<< 0"));
}
// public void testUnsignedShiftLeft2() {
// assertEquals(5, test("(five - 10) <<< 0"));
public void testShiftRight() {
assertEquals(128, test("256 >> 1"));
}
public void testShiftRight2() {
assertEquals(5 >> 1, test("five >> 1"));
}
public void testUnsignedShiftRight() {
assertEquals(-5 >>> 1, test("-5 >>> 1"));
}
public void testUnsignedShiftRight2() {
assertEquals(-5 >>> 1, test("(five - 10) >>> 1"));
}
public void testXOR() {
assertEquals(3, test("1 ^ 2"));
}
public void testXOR2() {
assertEquals(5 ^ 2, test("five ^ 2"));
}
public void testContains1() {
assertEquals(true, test("list contains 'Happy!'"));
}
public void testContains2() {
assertEquals(false, test("list contains 'Foobie'"));
}
public void testContains3() {
assertEquals(true, test("sentence contains 'fox'"));
}
public void testContains4() {
assertEquals(false, test("sentence contains 'mike'"));
}
public void testContains5() {
assertEquals(true, test("!(sentence contains 'mike')"));
}
public void testContains6() {
assertEquals(true, test("bwahbwah = 'mikebrock'; testVar10 = 'mike'; bwahbwah contains testVar10"));
}
public void testInvert() {
assertEquals(~10, test("~10"));
}
public void testInvert2() {
assertEquals(~(10 + 1), test("~(10 + 1)"));
}
public void testInvert3() {
assertEquals(~10 + (1 + ~50), test("~10 + (1 + ~50)"));
}
public void testListCreation2() {
assertTrue(test("[\"test\"]") instanceof List);
}
public void testListCreation3() {
assertTrue(test("[66]") instanceof List);
}
public void testListCreation4() {
List ar = (List) test("[ 66 , \"test\" ]");
assertEquals(2, ar.size());
assertEquals(66, ar.get(0));
assertEquals("test", ar.get(1));
}
public void testListCreationWithCall() {
assertEquals(1, test("[\"apple\"].size()"));
}
public void testArrayCreationWithLength() {
assertEquals(2, test("Array.getLength({'foo', 'bar'})"));
}
public void testEmptyList() {
assertTrue(test("[]") instanceof List);
}
public void testEmptyArray() {
assertTrue(((Object[]) test("{}")).length == 0);
}
public void testEmptyArray2() {
assertTrue(((Object[]) test("{ }")).length == 0);
}
public void testArrayCreation() {
assertEquals(0, test("arrayTest = {{1, 2, 3}, {2, 1, 0}}; arrayTest[1][2]"));
}
public void testMapCreation() {
assertEquals("sarah", test("map = ['mike':'sarah','tom':'jacquelin']; map['mike']"));
}
public void testMapCreation2() {
assertEquals("sarah", test("map = ['mike' :'sarah' ,'tom' :'jacquelin' ]; map['mike']"));
}
public void testMapCreation3() {
assertEquals("foo", test("map = [1 : 'foo']; map[1]"));
}
public void testProjectionSupport() {
assertEquals(true, test("(name in things)contains'Bob'"));
}
public void testProjectionSupport1() {
assertEquals(true, test("(name in things) contains 'Bob'"));
}
public void testProjectionSupport2() {
assertEquals(3, test("(name in things).size()"));
}
public void testProjectionSupport3() {
assertEquals("FOO", test("(toUpperCase() in ['bar', 'foo'])[1]"));
}
public void testProjectionSupport4() {
Collection col = (Collection) test("(toUpperCase() in ['zero', 'zen', 'bar', 'foo'] if ($ == 'bar'))");
assertEquals(1, col.size());
assertEquals("BAR", col.iterator().next());
}
public void testProjectionSupport5() {
Collection col = (Collection) test("(toUpperCase() in ['zero', 'zen', 'bar', 'foo'] if ($.startsWith('z')))");
assertEquals(2, col.size());
Iterator iter = col.iterator();
assertEquals("ZERO", iter.next());
assertEquals("ZEN", iter.next());
}
public void testSizeOnInlineArray() {
assertEquals(3, test("{1,2,3}.size()"));
}
public void testSimpleListCreation() {
test("['foo', 'bar', 'foobar', 'FOOBAR']");
}
public void testStaticMethodFromLiteral() {
assertEquals(String.class.getName(), test("String.valueOf(Class.forName('java.lang.String').getName())"));
}
public void testObjectInstantiation() {
test("new java.lang.String('foobie')");
}
public void testObjectInstantiationWithMethodCall() {
assertEquals("FOOBIE", test("new String('foobie') . toUpperCase()"));
}
public void testObjectInstantiation2() {
test("new String() is String");
}
public void testObjectInstantiation3() {
test("new java.text.SimpleDateFormat('yyyy').format(new java.util.Date(System.currentTimeMillis()))");
}
public void testArrayCoercion() {
assertEquals("gonk", test("funMethod( {'gonk', 'foo'} )"));
}
public void testArrayCoercion2() {
assertEquals(10, test("sum({2,2,2,2,2})"));
}
public void testMapAccess() {
assertEquals("dog", test("funMap['foo'].bar.name"));
}
public void testMapAccess2() {
assertEquals("dog", test("funMap.foo.bar.name"));
}
public void testSoundex() {
assertTrue((Boolean) test("'foobar' soundslike 'fubar'"));
}
public void testSoundex2() {
assertFalse((Boolean) test("'flexbar' soundslike 'fubar'"));
}
public void testSoundex3() {
assertEquals(true, test("(c soundslike 'kat')"));
}
public void testSoundex4() {
assertEquals(true, test("_xx1 = 'cat'; _xx2 = 'katt'; (_xx1 soundslike _xx2)"));
}
public void testSoundex5() {
assertEquals(true, test("_type = 'fubar';_type soundslike \"foobar\""));
}
public void testSimilarity1() {
assertEquals(0.6666667f, test("c strsim 'kat'"));
}
public void testThisReference() {
assertEquals(true, test("this") instanceof Base);
}
public void testThisReference2() {
assertEquals(true, test("this.funMap") instanceof Map);
}
public void testThisReference3() {
assertEquals(true, test("this is org.mvel2.tests.core.res.Base"));
}
public void testThisReference4() {
assertEquals(true, test("this.funMap instanceof java.util.Map"));
}
public void testThisReference5() {
assertEquals(true, test("this.data == 'cat'"));
}
public void testThisReferenceInMethodCall() {
assertEquals(101, test("Integer.parseInt(this.number)"));
}
public void testThisReferenceInConstructor() {
assertEquals("101", test("new String(this.number)"));
}
// interpreted
public void testThisReferenceMapVirtualObjects() {
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
assertEquals(true, eval("this.foo == 'bar'", map, factory));
}
// compiled - reflective
public void testThisReferenceMapVirtualObjects1() {
// Create our root Map object
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
OptimizerFactory.setDefaultOptimizer("reflective");
// Run test
assertEquals(true, executeExpression(compileExpression("this.foo == 'bar'"), map, factory));
}
// compiled - asm
public void testThisReferenceMapVirtualObjects2() {
// Create our root Map object
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
// I think we can all figure this one out.
if (!Boolean.getBoolean("mvel2.disable.jit")) OptimizerFactory.setDefaultOptimizer("ASM");
// Run test
assertEquals(true, executeExpression(compileExpression("this.foo == 'bar'"), map, factory));
}
public void testStringEscaping() {
assertEquals("\"Mike Brock\"", test("\"\\\"Mike Brock\\\"\""));
}
public void testStringEscaping2() {
assertEquals("MVEL's Parser is Fast", test("'MVEL\\'s Parser is Fast'"));
}
public void testEvalToBoolean() {
assertEquals(true, (boolean) evalToBoolean("true ", "true"));
assertEquals(true, (boolean) evalToBoolean("true ", "true"));
}
public void testCompiledMapStructures() {
executeExpression(compileExpression("['foo':'bar'] contains 'foo'"), null, null, Boolean.class);
}
public void testSubListInMap() {
assertEquals("pear", test("map = ['test' : 'poo', 'foo' : [c, 'pear']]; map['foo'][1]"));
}
public void testCompiledMethodCall() {
assertEquals(String.class, executeExpression(compileExpression("c.getClass()"), new Base(), createTestMap()));
}
public void testStaticNamespaceCall() {
assertEquals(java.util.ArrayList.class, test("java.util.ArrayList"));
}
public void testStaticNamespaceClassWithMethod() {
assertEquals("FooBar", test("java.lang.String.valueOf('FooBar')"));
}
public void testConstructor() {
assertEquals("foo", test("a = 'foobar'; new String(a.toCharArray(), 0, 3)"));
}
public void testStaticNamespaceClassWithField() {
assertEquals(Integer.MAX_VALUE, test("java.lang.Integer.MAX_VALUE"));
}
public void testStaticNamespaceClassWithField2() {
assertEquals(Integer.MAX_VALUE, test("Integer.MAX_VALUE"));
}
public void testStaticFieldAsMethodParm() {
assertEquals(String.valueOf(Integer.MAX_VALUE), test("String.valueOf(Integer.MAX_VALUE)"));
}
public void testEmptyIf() {
assertEquals(5, test("a = 5; if (a == 5) { }; return a;"));
}
public void testEmptyIf2() {
assertEquals(5, test("a=5;if(a==5){};return a;"));
}
public void testIf() {
assertEquals(10, test("if (5 > 4) { return 10; } else { return 5; }"));
}
public void testIf2() {
assertEquals(10, test("if (5 < 4) { return 5; } else { return 10; }"));
}
public void testIf3() {
assertEquals(10, test("if(5<4){return 5;}else{return 10;}"));
}
public void testIfAndElse() {
assertEquals(true, test("if (false) { return false; } else { return true; }"));
}
public void testIfAndElseif() {
assertEquals(true, test("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;"));
}
public void testIfAndElseIfCondensedGrammar() {
assertEquals("Foo", test("if (false) return 'Bar'; else return 'Foo';"));
}
public void testForEach2() {
assertEquals(6, test("total = 0; a = {1,2,3}; foreach(item : a) { total += item }; total"));
}
public void testForEach3() {
assertEquals(true, test("a = {1,2,3}; foreach (i : a) { if (i == 1) { return true; } }"));
}
public void testForEach4() {
assertEquals("OneTwoThreeFour", test("a = {1,2,3,4}; builder = ''; foreach (i : a) {" +
" if (i == 1) { builder += 'One' } else if (i == 2) { builder += 'Two' } " +
"else if (i == 3) { builder += 'Three' } else { builder += 'Four' }" +
"}; builder;"));
}
public void testWith() {
assertEquals("OneTwo", test("with (foo) {aValue = 'One',bValue='Two'}; foo.aValue + foo.bValue;"));
}
public void testWith2() {
assertEquals("OneTwo", test(
"with (foo) { \n" +
"aValue = 'One', // this is a comment \n" +
"bValue='Two' // this is also a comment \n" +
"}; \n" +
"foo.aValue + foo.bValue;"));
}
public void testMagicArraySize() {
assertEquals(5, test("stringArray.size()"));
}
public void testMagicArraySize2() {
assertEquals(5, test("intArray.size()"));
}
public void testStaticVarAssignment() {
assertEquals("1", test("String mikeBrock = 1; mikeBrock"));
}
public void testImport() {
assertEquals(HashMap.class, test("import java.util.HashMap; HashMap;"));
}
public void testStaticImport() {
assertEquals(2.0, test("import_static java.lang.Math.sqrt; sqrt(4)"));
}
public void testFunctionPointer() {
assertEquals(2.0, test("squareRoot = java.lang.Math.sqrt; squareRoot(4)"));
}
public void testFunctionPointerAsParam() {
assertEquals("2.0", test("squareRoot = Math.sqrt; new String(String.valueOf(squareRoot(4)));"));
}
public void testFunctionPointerInAssignment() {
assertEquals(5.0, test("squareRoot = Math.sqrt; i = squareRoot(25); return i;"));
}
public void testIncrementOperator() {
assertEquals(2, test("x = 1; x++; x"));
}
public void testPreIncrementOperator() {
assertEquals(2, test("x = 1; ++x"));
}
public void testDecrementOperator() {
assertEquals(1, test("x = 2; x
}
public void testPreDecrementOperator() {
assertEquals(1, test("x = 2; --x"));
}
public void testQualifiedStaticTyping() {
Object val = test("java.math.BigDecimal a = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal b = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal c = a + b; return c; ");
assertEquals(new BigDecimal(20), val);
}
public void testUnQualifiedStaticTyping() {
CompiledExpression ce = (CompiledExpression) compileExpression("import java.math.BigDecimal; BigDecimal a = new BigDecimal( 10.0 ); BigDecimal b = new BigDecimal( 10.0 ); BigDecimal c = a + b; return c; ");
System.out.println(DebugTools.decompile(ce));
assertEquals(new BigDecimal(20), testCompiledSimple("import java.math.BigDecimal; BigDecimal a = new BigDecimal( 10.0 ); BigDecimal b = new BigDecimal( 10.0 ); BigDecimal c = a + b; return c; ", new HashMap()));
}
public void testObjectCreation() {
assertEquals(6, test("new Integer( 6 )"));
}
public void testTernary4() {
assertEquals("<test>", test("true ? '<test>' : '<poo>'"));
}
public void testStringAsCollection() {
assertEquals('o', test("abc = 'foo'; abc[1]"));
}
public void testSubExpressionIndexer() {
assertEquals("bar", test("xx = new java.util.HashMap(); xx.put('foo', 'bar'); prop = 'foo'; xx[prop];"));
}
public void testCompileTimeLiteralReduction() {
assertEquals(1000, test("10 * 100"));
}
public void testInterfaceResolution() {
Serializable ex = compileExpression("foo.collectionTest.size()");
Map map = createTestMap();
Foo foo = (Foo) map.get("foo");
foo.setCollectionTest(new HashSet());
Object result1 = executeExpression(ex, foo, map);
foo.setCollectionTest(new ArrayList());
Object result2 = executeExpression(ex, foo, map);
assertEquals(result1, result2);
}
/**
* Start collections framework based compliance tests
*/
public void testCreationOfSet() {
assertEquals("foo bar foo bar",
test("set = new java.util.LinkedHashSet(); " +
"set.add('foo');" +
"set.add('bar');" +
"output = '';" +
"foreach (item : set) {" +
"output = output + item + ' ';" +
"} " +
"foreach (item : set) {" +
"output = output + item + ' ';" +
"} " +
"output = output.trim();" +
"if (set.size() == 2) { return output; }"));
}
public void testCreationOfList() {
assertEquals(5, test("l = new java.util.LinkedList();" +
"l.add('fun');" +
"l.add('happy');" +
"l.add('fun');" +
"l.add('slide');" +
"l.add('crap');" +
"poo = new java.util.ArrayList(l);" +
"poo.size();"));
}
public void testMapOperations() {
assertEquals("poo5", test(
"l = new java.util.ArrayList();" +
"l.add('plop');" +
"l.add('poo');" +
"m = new java.util.HashMap();" +
"m.put('foo', l);" +
"m.put('cah', 'mah');" +
"m.put('bar', 'foo');" +
"m.put('sarah', 'mike');" +
"m.put('edgar', 'poe');" +
"" +
"if (m.edgar == 'poe') {" +
"return m.foo[1] + m.size();" +
"}"));
}
public void testStackOperations() {
assertEquals(10, test(
"stk = new java.util.Stack();" +
"stk.push(5);" +
"stk.push(5);" +
"stk.pop() + stk.pop();"
));
}
public void testSystemOutPrint() {
test("a = 0;\r\nSystem.out.println('This is a test');");
}
public void testBreakpoints() {
ExpressionCompiler compiler = new ExpressionCompiler("a = 5;\nb = 5;\n\nif (a == b) {\n\nSystem.out.println('Good');\nreturn a + b;\n}\n");
System.out.println("
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
System.out.println(DebugTools.decompile(compiled));
MVELRuntime.registerBreakpoint("test.mv", 7);
Debugger testDebugger = new Debugger() {
public int onBreak(Frame frame) {
System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]");
return 0;
}
};
MVELRuntime.setThreadDebugger(testDebugger);
assertEquals(10, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap())));
}
public void testBreakpoints2() {
ExpressionCompiler compiler = new ExpressionCompiler("System.out.println('test the debugger');\n a = 0;");
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
System.out.println(DebugTools.decompile(compiled));
}
public void testBreakpoints3() {
String expr = "System.out.println( \"a1\" );\n" +
"System.out.println( \"a2\" );\n" +
"System.out.println( \"a3\" );\n" +
"System.out.println( \"a4\" );\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.addImport("System", System.class);
context.setStrictTypeEnforcement(true);
context.setDebugSymbols(true);
context.setSourceFile("mysource");
// Serializable compiledExpression = compiler.compile(context);
String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(context));
System.out.println("output: " + s);
int fromIndex = 0;
int count = 0;
while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
count++;
}
assertEquals(4, count);
}
public void testBreakpointsAcrossWith() {
String line1 = "System.out.println( \"a1\" );\n";
String line2 = "c = new Cheese();\n";
String line3 = "with ( c ) { type = 'cheddar',\n" +
" price = 10 };\n";
String line4 = "System.out.println( \"a1\" );\n";
String expr = line1 + line2 + line3 + line4;
System.out.println(expr);
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.addImport("System", System.class);
context.addImport("Cheese", Cheese.class);
context.setStrictTypeEnforcement(true);
context.setDebugSymbols(true);
context.setSourceFile("mysource");
// Serializable compiledExpression = compiler.compile(context);
String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(context));
System.out.println("output: " + s);
int fromIndex = 0;
int count = 0;
while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
count++;
}
assertEquals(5, count);
}
public void testBreakpointsAcrossComments() {
String expression = "/** This is a comment\n" + // 1
" * Second comment line\n" + // 2
" * Third Comment Line\n" + // 3
" */\n" + // 4
"System.out.println('4');\n" +
"System.out.println('5');\n" +
"a = 0;\n" +
"b = 1;\n" +
"a + b";
ExpressionCompiler compiler = new ExpressionCompiler(expression);
// compiler.setDebugSymbols(true);
System.out.println("Expression:\n
System.out.println(expression);
System.out.println("
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test2.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
System.out.println(DebugTools.decompile(compiled));
MVELRuntime.registerBreakpoint("test2.mv", 9);
Debugger testDebugger = new Debugger() {
public int onBreak(Frame frame) {
System.out.println("Breakpoint Encountered [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]");
System.out.println("vars:" + frame.getFactory().getKnownVariables());
System.out.println("Resume Execution");
return 0;
}
};
MVELRuntime.setThreadDebugger(testDebugger);
assertEquals(1, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap())));
}
public void testBreakpointsAcrossComments2() {
ExpressionCompiler compiler = new ExpressionCompiler(
"// This is a comment\n" + // 1
"//Second comment line\n" + // 2
"//Third Comment Line\n" + // 3
"\n" +
"//Test\n" + // 5
"System.out.println('4');\n" +
"//System.out.println('5'); \n" + // 7
"a = 0;\n" +
"b = 1;\n" +
" a + b");
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test2.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
System.out.println(DebugTools.decompile(compiled));
MVELRuntime.registerBreakpoint("test2.mv", 6);
MVELRuntime.registerBreakpoint("test2.mv", 8);
MVELRuntime.registerBreakpoint("test2.mv", 9);
MVELRuntime.registerBreakpoint("test2.mv", 10);
Debugger testDebugger = new Debugger() {
public int onBreak(Frame frame) {
System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]");
return 0;
}
};
MVELRuntime.setThreadDebugger(testDebugger);
assertEquals(1, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap())));
}
public void testBreakpoints4() {
String expression = "System.out.println('foo');\n" +
"a = new Foo();\n" +
"update (a) { name = 'bar' };\n" +
"System.out.println('name:' + a.name);\n" +
"return a.name;";
Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
Map<String, Macro> macros = new HashMap<String, Macro>();
interceptors.put("Update", new Interceptor() {
public int doBefore(ASTNode node, VariableResolverFactory factory) {
((WithNode) node).getNestedStatement().getValue(null,
factory);
System.out.println("fired update interceptor -- before");
return 0;
}
public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
System.out.println("fired update interceptor -- after");
return 0;
}
});
macros.put("update", new Macro() {
public String doMacro() {
return "@Update with";
}
});
expression = parseMacros(expression, macros);
ExpressionCompiler compiler = new ExpressionCompiler(expression);
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setDebugSymbols(true);
ctx.setSourceFile("test2.mv");
ctx.addImport("Foo", Foo.class);
ctx.setInterceptors(interceptors);
CompiledExpression compiled = compiler.compile(ctx);
System.out.println("\nExpression:
System.out.println(expression);
System.out.println("
System.out.println(DebugTools.decompile(compiled));
MVELRuntime.registerBreakpoint("test2.mv", 3);
MVELRuntime.registerBreakpoint("test2.mv", 4);
MVELRuntime.registerBreakpoint("test2.mv", 5);
Debugger testDebugger = new Debugger() {
public int onBreak(Frame frame) {
System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]");
return 0;
}
};
MVELRuntime.setThreadDebugger(testDebugger);
assertEquals("bar", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap())));
}
public void testBreakpoints5() {
OptimizerFactory.setDefaultOptimizer("ASM");
String expression = "System.out.println('foo');\r\n" +
"a = new Foo();\r\n" +
"a.name = 'bar';\r\n" +
"foo.happy();\r\n" +
"System.out.println( 'name:' + a.name ); \r\n" +
"System.out.println( 'name:' + a.name ); \r\n" +
"System.out.println( 'name:' + a.name ); \r\n" +
"return a.name;";
Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
Map<String, Macro> macros = new HashMap<String, Macro>();
interceptors.put("Update", new Interceptor() {
public int doBefore(ASTNode node, VariableResolverFactory factory) {
((WithNode) node).getNestedStatement().getValue(null,
factory);
System.out.println("fired update interceptor -- before");
return 0;
}
public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
System.out.println("fired update interceptor -- after");
return 0;
}
});
macros.put("update", new Macro() {
public String doMacro() {
return "@Update with";
}
});
expression = parseMacros(expression, macros);
ExpressionCompiler compiler = new ExpressionCompiler(expression);
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test2.mv");
ctx.setDebugSymbols(true);
ctx.addImport("Foo", Foo.class);
ctx.setInterceptors(interceptors);
CompiledExpression compiled = compiler.compile(ctx);
System.out.println("\nExpression:
System.out.println(expression);
System.out.println("
System.out.println(DebugTools.decompile(compiled));
MVELRuntime.registerBreakpoint("test2.mv", 1);
Debugger testDebugger = new Debugger() {
public int onBreak(Frame frame) {
System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]");
return Debugger.STEP_OVER;
}
};
MVELRuntime.setThreadDebugger(testDebugger);
System.out.println("\n==RUN==\n");
assertEquals("bar", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap())));
}
public void testDebugSymbolsWithWindowsLinedEndings() throws Exception {
String expr = " System.out.println( \"a1\" );\r\n" +
" System.out.println( \"a2\" );\r\n" +
" System.out.println( \"a3\" );\r\n" +
" System.out.println( \"a4\" );\r\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.setDebugSymbols(true);
ctx.setSourceFile("mysource");
// Serializable compiledExpression = compiler.compile(ctx);
String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(ctx));
System.out.println(s);
int fromIndex = 0;
int count = 0;
while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
count++;
}
assertEquals(4, count);
}
public void testDebugSymbolsWithUnixLinedEndings() throws Exception {
String expr = " System.out.println( \"a1\" );\n" +
" System.out.println( \"a2\" );\n" +
" System.out.println( \"a3\" );\n" +
" System.out.println( \"a4\" );\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.setDebugSymbols(true);
ctx.setSourceFile("mysource");
// Serializable compiledExpression = compiler.compile(ctx);
String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(ctx));
int fromIndex = 0;
int count = 0;
while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
count++;
}
assertEquals(4, count);
}
public void testDebugSymbolsWithMixedLinedEndings() throws Exception {
String expr = " System.out.println( \"a1\" );\n" +
" System.out.println( \"a2\" );\r\n" +
" System.out.println( \"a3\" );\n" +
" System.out.println( \"a4\" );\r\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.setDebugSymbols(true);
ctx.setSourceFile("mysource");
// Serializable compiledExpression = compiler.compile(ctx);
String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(ctx));
System.out.println(s);
int fromIndex = 0;
int count = 0;
while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
count++;
}
assertEquals(4, count);
}
public void testReflectionCache() {
assertEquals("happyBar", test("foo.happy(); foo.bar.happy()"));
}
public void testVarInputs() {
ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;");
compiler.compile();
ParserContext pCtx = compiler.getParserContextState();
assertEquals(4, pCtx.getInputs().size());
assertTrue(pCtx.getInputs().containsKey("test"));
assertTrue(pCtx.getInputs().containsKey("foo"));
assertTrue(pCtx.getInputs().containsKey("bo"));
assertTrue(pCtx.getInputs().containsKey("trouble"));
assertEquals(2, pCtx.getVariables().size());
assertTrue(pCtx.getVariables().containsKey("bleh"));
assertTrue(pCtx.getVariables().containsKey("twa"));
assertEquals(String.class, pCtx.getVarOrInputType("bleh"));
}
public void testVarInputs2() {
ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;");
ParserContext ctx = new ParserContext();
ctx.setRetainParserState(true);
compiler.compile(ctx);
System.out.println(ctx.getVarOrInputType("bleh"));
}
public void testVarInputs3() {
ExpressionCompiler compiler = new ExpressionCompiler("addresses['home'].street");
compiler.compile();
assertFalse(compiler.getParserContextState().getInputs().keySet().contains("home"));
}
public void testVarInputs4() {
ExpressionCompiler compiler = new ExpressionCompiler("System.out.println( message );");
compiler.compile();
assertTrue(compiler.getParserContextState().getInputs().keySet().contains("message"));
}
public void testAnalyzer() {
ExpressionCompiler compiler = new ExpressionCompiler("order.id == 10");
compiler.compile();
for (String input : compiler.getParserContextState().getInputs().keySet()) {
System.out.println("input>" + input);
}
assertEquals(1, compiler.getParserContextState().getInputs().size());
assertTrue(compiler.getParserContextState().getInputs().containsKey("order"));
}
public void testClassImportViaFactory() {
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(HashMap.class);
ResolverTools.appendFactory(mvf, classes);
// Serializable compiled = compileExpression("HashMap map = new HashMap()", classes.getImportedClasses());
assertTrue(executeExpression(
compileExpression("HashMap map = new HashMap()", classes.getImportedClasses()), mvf) instanceof HashMap);
}
public void testSataticClassImportViaFactory() {
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(Person.class);
ResolverTools.appendFactory(mvf, classes);
// Serializable compiled = compileExpression("p = new Person('tom'); return p.name;", classes.getImportedClasses());
assertEquals("tom",
executeExpression(compileExpression("p = new Person('tom'); return p.name;",
classes.getImportedClasses()), mvf));
}
public void testSataticClassImportViaFactoryAndWithModification() {
OptimizerFactory.setDefaultOptimizer("ASM");
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(Person.class);
ResolverTools.appendFactory(mvf, classes);
// Serializable compiled = compileExpression("p = new Person('tom'); p.age = 20; with( p ) { age = p.age + 1 }; return p.age;", classes.getImportedClasses());
assertEquals(21, executeExpression(compileExpression(
"p = new Person('tom'); p.age = 20; with( p ) { age = p.age + 1 }; return p.age;",
classes.getImportedClasses()), mvf));
}
public void testCheeseConstructor() {
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(Cheese.class);
ResolverTools.appendFactory(mvf, classes);
// Serializable compiled = compileExpression("cheese = new Cheese(\"cheddar\", 15);", classes.getImportedClasses());
assertTrue(executeExpression(
compileExpression("cheese = new Cheese(\"cheddar\", 15);", classes.getImportedClasses()), mvf) instanceof Cheese);
}
public void testInterceptors() {
Interceptor testInterceptor = new Interceptor() {
public int doBefore(ASTNode node, VariableResolverFactory factory) {
System.out.println("BEFORE Node: " + node.getName());
return 0;
}
public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
System.out.println("AFTER Node: " + node.getName());
return 0;
}
};
Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
interceptors.put("test", testInterceptor);
// Serializable compiled = compileExpression("@test System.out.println('MIDDLE');", null, interceptors);
executeExpression(compileExpression("@test System.out.println('MIDDLE');", null, interceptors));
}
public void testMacroSupport() {
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", new Foo());
Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
Map<String, Macro> macros = new HashMap<String, Macro>();
interceptors.put("Modify", new Interceptor() {
public int doBefore(ASTNode node, VariableResolverFactory factory) {
((WithNode) node).getNestedStatement().getValue(null,
factory);
factory.createVariable("mod", "FOOBAR!");
return 0;
}
public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
return 0;
}
});
macros.put("modify", new Macro() {
public String doMacro() {
return "@Modify with";
}
});
ExpressionCompiler compiler = new ExpressionCompiler(parseMacros("modify (foo) { aValue = 'poo' }; mod", macros));
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext(null, interceptors, null);
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
// CompiledExpression compiled = compiler.compile(ctx);
assertEquals("FOOBAR!", executeExpression(compiler.compile(ctx), null, vars));
}
public void testMacroSupportWithDebugging() {
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", new Foo());
Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
Map<String, Macro> macros = new HashMap<String, Macro>();
interceptors.put("Modify", new Interceptor() {
public int doBefore(ASTNode node, VariableResolverFactory factory) {
((WithNode) node).getNestedStatement().getValue(null,
factory);
factory.createVariable("mod", "FOOBAR!");
return 0;
}
public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
return 0;
}
});
macros.put("modify", new Macro() {
public String doMacro() {
return "@Modify with";
}
});
ExpressionCompiler compiler = new ExpressionCompiler(
parseMacros(
"System.out.println('hello');\n" +
"System.out.println('bye');\n" +
"modify (foo) { aValue = 'poo', \n" +
" aValue = 'poo' };\n mod", macros)
);
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext(null, interceptors, null);
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
MVELRuntime.setThreadDebugger(new Debugger() {
public int onBreak(Frame frame) {
System.out.println(frame.getSourceName() + ":" + frame.getLineNumber());
return Debugger.STEP;
}
});
MVELRuntime.registerBreakpoint("test.mv", 3);
System.out.println(DebugTools.decompile(compiled
));
assertEquals("FOOBAR!", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(vars)));
}
public void testExecuteCoercionTwice() {
OptimizerFactory.setDefaultOptimizer("reflective");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", new Foo());
vars.put("$value", new Long(5));
ExpressionCompiler compiler = new ExpressionCompiler("with (foo) { countTest = $value };");
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
executeExpression(compiled, null, vars);
executeExpression(compiled, null, vars);
}
public void testExecuteCoercionTwice2() {
OptimizerFactory.setDefaultOptimizer("ASM");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", new Foo());
vars.put("$value", new Long(5));
ExpressionCompiler compiler = new ExpressionCompiler("with (foo) { countTest = $value };");
// compiler.setDebugSymbols(true);
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
executeExpression(compiled, null, vars);
executeExpression(compiled, null, vars);
}
public void testComments() {
assertEquals(10, test("// This is a comment\n5 + 5"));
}
public void testComments2() {
assertEquals(20, test("10 + 10; // This is a comment"));
}
public void testComments3() {
assertEquals(30, test("/* This is a test of\r\n" +
"MVEL's support for\r\n" +
"multi-line comments\r\n" +
"*/\r\n 15 + 15"));
}
public void testComments4() {
assertEquals(((10 + 20) * 2) - 10, test("/** This is a fun test script **/\r\n" +
"a = 10;\r\n" +
"/**\r\n" +
"* Here is a useful variable\r\n" +
"*/\r\n" +
"b = 20; // set b to '20'\r\n" +
"return ((a + b) * 2) - 10;\r\n" +
"// last comment\n"));
}
public void testSubtractNoSpace1() {
assertEquals(59, test("hour-1"));
}
public void testStrictTypingCompilation() {
ExpressionCompiler compiler = new ExpressionCompiler("a.foo;\nb.foo;\n x = 5");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
try {
compiler.compile(ctx);
}
catch (CompileException e) {
e.printStackTrace();
assertEquals(2, e.getErrors().size());
return;
}
assertTrue(false);
}
public void testStrictStaticMethodCall() {
ExpressionCompiler compiler = new ExpressionCompiler("Bar.staticMethod()");
ParserContext ctx = new ParserContext();
ctx.addImport("Bar", Bar.class);
ctx.setStrictTypeEnforcement(true);
Serializable s = compiler.compile(ctx);
DebugTools.decompile(s);
assertEquals(1, executeExpression(s));
}
public void testStrictTypingCompilation2() throws Exception {
ParserContext ctx = new ParserContext();
//noinspection RedundantArrayCreation
ctx.addImport("getRuntime", new MethodStub(Runtime.class.getMethod("getRuntime", new Class[]{})));
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler = new ExpressionCompiler("getRuntime()");
StaticMethodImportResolverFactory si = new StaticMethodImportResolverFactory(ctx);
Serializable expression = compiler.compile(ctx);
serializationTest(expression);
assertTrue(executeExpression(expression, si) instanceof Runtime);
}
public void testStrictTypingCompilation3() throws NoSuchMethodException {
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler =
new ExpressionCompiler("message='Hello';b=7;\nSystem.out.println(message + ';' + b);\n" +
"System.out.println(message + ';' + b); b");
assertEquals(7, executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory()));
}
public void testStrictTypingCompilation4() throws NoSuchMethodException {
ParserContext ctx = new ParserContext();
ctx.addImport(Foo.class);
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler =
new ExpressionCompiler("x_a = new Foo()");
compiler.compile(ctx);
assertEquals(Foo.class, ctx.getVariables().get("x_a"));
}
public void testProvidedExternalTypes() {
ExpressionCompiler compiler = new ExpressionCompiler("foo.bar");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.addInput("foo", Foo.class);
compiler.compile(ctx);
}
public void testEqualityRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("price == (new Integer( 5 ) + 5 ) ");
compiler.compile();
}
public void testEvaluationRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("(p.age * 2)");
compiler.compile();
assertTrue(compiler.getParserContextState().getInputs().containsKey("p"));
}
public void testAssignmentRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("total = total + $cheese.price");
compiler.compile();
}
public void testTypeRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("total = 0");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
compiler.compile(ctx);
assertEquals(Integer.class,
compiler.getParserContextState().getVarOrInputType("total"));
}
public void testDateComparison() {
assertTrue((Boolean) test("dt1 < dt2"));
}
public void testDynamicDeop() {
Serializable s = compileExpression("name");
assertEquals("dog", executeExpression(s, new Foo()));
assertEquals("dog", executeExpression(s, new Foo().getBar()));
}
public void testVirtProperty() {
// OptimizerFactory.setDefaultOptimizer("ASM");
Map<String, Object> testMap = new HashMap<String, Object>();
testMap.put("test", "foo");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("mp", testMap);
assertEquals("bar", executeExpression(compileExpression("mp.test = 'bar'; mp.test"), vars));
}
public void testMapPropertyCreateCondensed() {
assertEquals("foo", test("map = new java.util.HashMap(); map['test'] = 'foo'; map['test'];"));
}
public void testClassLiteral() {
assertEquals(String.class, test("java.lang.String"));
}
public void testDeepMethod() {
assertEquals(false, test("foo.bar.testList.add(new String()); foo.bar.testList == empty"));
}
public void testArrayAccessorAssign() {
assertEquals("foo", test("a = {'f00', 'bar'}; a[0] = 'foo'; a[0]"));
}
public void testListAccessorAssign() {
assertEquals("bar", test("a = new java.util.ArrayList(); a.add('foo'); a.add('BAR'); a[1] = 'bar'; a[1]"));
}
public void testBracketInString() {
test("System.out.println('1)your guess was:');");
}
public void testNesting() {
assertEquals("foo", test("new String(new String(new String(\"foo\")));"));
}
public void testDeepPropertyAdd() {
assertEquals(10, test("foo.countTest+ 10"));
}
public void testDeepAssignmentIncrement() {
assertEquals(true, test("foo.countTest += 5; if (foo.countTest == 5) { foo.countTest = 0; return true; } else { foo.countTest = 0; return false; }"));
}
public void testDeepAssignmentWithBlock() {
assertEquals(true, test("with (foo) { countTest += 5 }; if (foo.countTest == 5) { foo.countTest = 0; return true; } else { foo.countTest = 0; return false; }"));
}
public void testOperativeAssignMod() {
int val = 5;
assertEquals(val %= 2, test("int val = 5; val %= 2; val"));
}
public void testOperativeAssignDiv() {
int val = 10;
assertEquals(val /= 2, test("int val = 10; val /= 2; val"));
}
public void testOperativeAssignShift1() {
int val = 5;
assertEquals(val <<= 2, test("int val = 5; val <<= 2; val"));
}
public void testOperativeAssignShift2() {
int val = 5;
assertEquals(val >>= 2, test("int val = 5; val >>= 2; val"));
}
public void testOperativeAssignShift3() {
int val = -5;
assertEquals(val >>>= 2, test("int val = -5; val >>>= 2; val"));
}
public void testTypeCast() {
assertEquals("10", test("(String) 10"));
}
public void testMapAccessSemantics() {
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test", "foo");
outermap.put("innermap", innermap);
assertEquals("foo", testCompiledSimple("innermap['test']", outermap, null));
}
public void testMapBindingSemantics() {
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test", "foo");
outermap.put("innermap", innermap);
setProperty(outermap, "innermap['test']", "bar");
assertEquals("bar", testCompiledSimple("innermap['test']", outermap, null));
}
public void testMapNestedInsideList() {
ParserContext ctx = new ParserContext();
ctx.addImport("User", User.class);
ExpressionCompiler compiler = new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar'),\n'bobba' : new User('Bobba', 'Feta') ]; [ users.get('darth'), users.get('bobba') ]");
// Serializable s = compiler.compile(ctx);
List list = (List) executeExpression(compiler.compile(ctx), new HashMap());
User user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
compiler = new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar'),\n'bobba' : new User('Bobba', 'Feta') ]; [ users['darth'], users['bobba'] ]");
list = (List) executeExpression(compiler.compile(ctx), new HashMap());
user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
}
public void testListNestedInsideList() {
ParserContext ctx = new ParserContext();
ctx.addImport("User", User.class);
ExpressionCompiler compiler = new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), new User('Bobba', 'Feta') ]; [ users.get( 0 ), users.get( 1 ) ]");
/// Serializable s = compiler.compile(ctx);
List list = (List) executeExpression(compiler.compile(ctx), new HashMap());
User user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
compiler = new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), new User('Bobba', 'Feta') ]; [ users[0], users[1] ]");
// s = compiler.compile(ctx);
list = (List) executeExpression(compiler.compile(ctx), new HashMap());
user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
}
public void testSetSemantics() {
Bar bar = new Bar();
Foo foo = new Foo();
assertEquals("dog", MVEL.getProperty("name", bar));
assertEquals("dog", MVEL.getProperty("name", foo));
}
public void testMapBindingSemantics2() {
OptimizerFactory.setDefaultOptimizer("ASM");
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test", "foo");
outermap.put("innermap", innermap);
executeSetExpression(compileSetExpression("innermap['test']"), outermap, "bar");
assertEquals("bar", testCompiledSimple("innermap['test']", outermap, null));
}
public void testDynamicImports() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util");
ExpressionCompiler compiler = new ExpressionCompiler("HashMap");
Serializable s = compiler.compile(ctx);
assertEquals(HashMap.class, executeExpression(s));
compiler = new ExpressionCompiler("map = new HashMap(); map.size()");
s = compiler.compile(ctx);
assertEquals(0, executeExpression(s, new DefaultLocalVariableResolverFactory()));
}
public void testDynamicImports3() {
String expression = "import java.util.*; HashMap map = new HashMap(); map.size()";
ExpressionCompiler compiler = new ExpressionCompiler(expression);
Serializable s = compiler.compile();
assertEquals(0, executeExpression(s, new DefaultLocalVariableResolverFactory()));
assertEquals(0, MVEL.eval(expression, new HashMap()));
}
public void testDynamicImportsInList() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("[ new User('Bobba', 'Feta') ]");
List list = (List) executeExpression(compiler.compile(ctx));
User user = (User) list.get(0);
assertEquals("Bobba", user.getFirstName());
}
public void testDynamicImportsInMap() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("[ 'bobba' : new User('Bobba', 'Feta') ]");
Map map = (Map) executeExpression(compiler.compile(ctx));
User user = (User) map.get("bobba");
assertEquals("Bobba", user.getFirstName());
}
public void testDynamicImportsOnNestedExpressions() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", new Cheese(\"cheddar\", 15))");
// Serializable s = compiler.compile(ctx);
Cheesery p1 = new Cheesery("bobbo", new Cheese("cheddar", 15));
Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory());
assertEquals(p1, p2);
}
public void testDynamicImportsWithNullConstructorParam() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", null)");
// Serializable s = compiler.compile(ctx);
Cheesery p1 = new Cheesery("bobbo", null);
Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory());
assertEquals(p1, p2);
}
public void testDynamicImportsWithIdentifierSameAsClassWithDiffCase() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ctx.setStrictTypeEnforcement(false);
ExpressionCompiler compiler = new ExpressionCompiler("bar.add(\"hello\")");
compiler.compile(ctx);
}
public void testTypedAssignment() {
assertEquals("foobar", test("java.util.Map map = new java.util.HashMap(); map.put('conan', 'foobar'); map['conan'];"));
}
public void testFQCNwithStaticInList() {
assertEquals(Integer.MIN_VALUE, test("list = [java.lang.Integer.MIN_VALUE]; list[0]"));
}
public void testPrecedenceOrder() {
assertTrue((Boolean) test("5 > 6 && 2 < 1 || 10 > 9"));
}
public void testPrecedenceOrder1() {
String ex = "50 > 60 && 20 < 10 || 100 > 90";
System.out.println("Expression: " + ex);
assertTrue((Boolean) MVEL.eval(ex));
}
@SuppressWarnings({"unchecked"})
public void testDifferentImplSameCompile() {
Serializable compiled = compileExpression("a.funMap.hello");
Map testMap = new HashMap();
for (int i = 0; i < 100; i++) {
Base b = new Base();
b.funMap.put("hello", "dog");
testMap.put("a", b);
assertEquals("dog", executeExpression(compiled, testMap));
b = new Base();
b.funMap.put("hello", "cat");
testMap.put("a", b);
assertEquals("cat", executeExpression(compiled, testMap));
}
}
@SuppressWarnings({"unchecked"})
public void testInterfaceMethodCallWithSpace() {
// Serializable compiled = compileExpression("drools.retract (cheese)");
Map map = new HashMap();
DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
map.put("drools", helper);
Cheese cheese = new Cheese("stilton", 15);
map.put("cheese", cheese);
executeExpression(compileExpression("drools.retract (cheese)"), map);
assertSame(cheese, helper.retracted.get(0));
}
@SuppressWarnings({"unchecked"})
public void testInterfaceMethodCallWithMacro() {
Map macros = new HashMap(1);
macros.put("retract",
new Macro() {
public String doMacro() {
return "drools.retract";
}
});
// Serializable compiled = compileExpression(parseMacros("retract(cheese)", macros));
Map map = new HashMap();
DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
map.put("drools", helper);
Cheese cheese = new Cheese("stilton", 15);
map.put("cheese", cheese);
executeExpression(compileExpression(parseMacros("retract(cheese)", macros)), map);
assertSame(cheese, helper.retracted.get(0));
}
@SuppressWarnings({"UnnecessaryBoxing"})
public void testToList() {
String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )";
List list = (List) test(text);
assertSame("dog", list.get(0));
assertEquals("hello", list.get(1));
assertEquals(new Integer(42), list.get(2));
Map map = (Map) list.get(3);
assertEquals("value1", map.get("key1"));
List nestedList = (List) map.get("cat");
assertEquals(14, nestedList.get(0));
assertEquals("car", nestedList.get(1));
assertEquals(42, nestedList.get(2));
nestedList = (List) list.get(4);
assertEquals(42, nestedList.get(0));
map = (Map) nestedList.get(1);
assertEquals("value1", map.get("cat"));
}
@SuppressWarnings({"UnnecessaryBoxing"})
public void testToListStrictMode() {
String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )";
ParserContext ctx = new ParserContext();
ctx.addInput("misc", MiscTestClass.class);
ctx.addInput("foo", Foo.class);
ctx.addInput("c", String.class);
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler = new ExpressionCompiler(text);
// Serializable expr = compiler.compile(ctx);
List list = (List) executeExpression(compiler.compile(ctx), createTestMap());
assertSame("dog", list.get(0));
assertEquals("hello", list.get(1));
assertEquals(new Integer(42), list.get(2));
Map map = (Map) list.get(3);
assertEquals("value1", map.get("key1"));
List nestedList = (List) map.get("cat");
assertEquals(14, nestedList.get(0));
assertEquals("car", nestedList.get(1));
assertEquals(42, nestedList.get(2));
nestedList = (List) list.get(4);
assertEquals(42, nestedList.get(0));
map = (Map) nestedList.get(1);
assertEquals("value1", map.get("cat"));
}
public void testParsingStability1() {
assertEquals(true, test("( order.number == 1 || order.number == ( 1+1) || order.number == $id )"));
}
public void testParsingStability2() {
ExpressionCompiler compiler = new ExpressionCompiler("( dim.height == 1 || dim.height == ( 1+1) || dim.height == x )");
Map<String, Object> imports = new HashMap<String, Object>();
imports.put("java.awt.Dimension", Dimension.class);
final ParserContext parserContext = new ParserContext(imports,
null,
"sourceFile");
parserContext.setStrictTypeEnforcement(false);
compiler.compile(parserContext);
}
public void testParsingStability3() {
assertEquals(false, test("!( [\"X\", \"Y\"] contains \"Y\" )"));
}
public void testParsingStability4() {
assertEquals(true, test("vv=\"Edson\"; !(vv ~= \"Mark\")"));
}
public void testConcatWithLineBreaks() {
ExpressionCompiler parser = new ExpressionCompiler("\"foo\"+\n\"bar\"");
ParserContext ctx = new ParserContext();
ctx.setDebugSymbols(true);
ctx.setSourceFile("source.mv");
// Serializable c = parser.compile(ctx);
assertEquals("foobar", executeExpression(parser.compile(ctx)));
}
/**
* Community provided test cases
*/
@SuppressWarnings({"unchecked"})
public void testCalculateAge() {
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0, 10); // 1999 jan 20
Map objectMap = new HashMap(1);
Map propertyMap = new HashMap(1);
propertyMap.put("GEBDAT", c1.getTime());
objectMap.put("EV_VI_ANT1", propertyMap);
assertEquals("N", testCompiledSimple("new org.mvel2.tests.core.res.PDFFieldUtil().calculateAge(EV_VI_ANT1.GEBDAT) >= 25 ? 'Y' : 'N'"
, null, objectMap));
}
/**
* Provided by: Alex Roytman
*/
public void testMethodResolutionWithNullParameter() {
Context ctx = new Context();
ctx.setBean(new Bean());
Map<String, Object> vars = new HashMap<String, Object>();
System.out.println("bean.today: " + eval("bean.today", ctx, vars));
System.out.println("formatDate(bean.today): " + eval("formatDate(bean.today)", ctx, vars));
//calling method with string param with null parameter works
System.out.println("formatString(bean.nullString): " + eval("formatString(bean.nullString)", ctx, vars));
System.out.println("bean.myDate = bean.nullDate: " + eval("bean.myDate = bean.nullDate; return bean.nullDate;", ctx, vars));
//calling method with Date param with null parameter fails
System.out.println("formatDate(bean.myDate): " + eval("formatDate(bean.myDate)", ctx, vars));
//same here
System.out.println(eval("formatDate(bean.nullDate)", ctx, vars));
}
/**
* Provided by: Phillipe Ombredanne
*/
public void testCompileParserContextShouldNotLoopIndefinitelyOnValidJavaExpression() {
String expr = " System.out.println( message );\n" +
"m.setMessage( \"Goodbye cruel world\" );\n" +
"System.out.println(m.getStatus());\n" +
"m.setStatus( Message.GOODBYE );\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message", Message.class);
context.addInput("System", void.class);
context.addInput("message", Object.class);
context.addInput("m", Object.class);
compiler.compile(context);
}
public void testStaticNested() {
assertEquals(1, eval("org.mvel2.tests.core.AbstractTest$Message.GOODBYE", new HashMap()));
}
public void testStaticNestedWithImport() {
String expr = "Message.GOODBYE;\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message", Message.class);
// Serializable compiledExpression = compiler.compile(context);
assertEquals(1, executeExpression(compiler.compile(context)));
}
public void testStaticNestedWithMethodCall() {
String expr = "item = new Item( \"Some Item\"); $msg.addItem( item ); return $msg";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message", Message.class);
context.addImport("Item", Item.class);
// Serializable compiledExpression = compiler.compile(context);
Map vars = new HashMap();
vars.put("$msg", new Message());
Message msg = (Message) executeExpression(compiler.compile(context), vars);
Item item = (Item) msg.getItems().get(0);
assertEquals("Some Item", item.getName());
}
public void testsequentialAccessorsThenMethodCall() {
String expr = "System.out.println(drools.workingMemory); drools.workingMemory.ruleBase.removeRule(\"org.drools.examples\", \"some rule\"); ";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(true);
context.addInput("drools", KnowledgeHelper.class);
RuleBase ruleBase = new RuleBaseImpl();
WorkingMemory wm = new WorkingMemoryImpl(ruleBase);
KnowledgeHelper drools = new DefaultKnowledgeHelper(wm);
// Serializable compiledExpression = compiler.compile(context);
Map vars = new HashMap();
vars.put("drools", drools);
executeExpression(compiler.compile(context), vars);
}
/**
* Provided by: Aadi Deshpande
*/
public void testPropertyVerfierShoudldNotLoopIndefinately() {
String expr = "\t\tmodel.latestHeadlines = $list;\n" +
"model.latestHeadlines.add( 0, (model.latestHeadlines[2]) );";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
compiler.setVerifying(true);
ParserContext pCtx = new ParserContext();
pCtx.addInput("$list", List.class);
pCtx.addInput("model", Model.class);
compiler.compile(pCtx);
}
public void testCompileWithNewInsideMethodCall() {
String expr = " p.name = \"goober\";\n" +
" System.out.println(p.name);\n" +
" drools.insert(new Address(\"Latona\"));\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Person", Person.class);
context.addImport("Address", Address.class);
context.addInput("p", Person.class);
context.addInput("drools", Drools.class);
compiler.compile(context);
}
/**
* Submitted by: cleverpig
*/
public void testBug4() {
ClassA A = new ClassA();
ClassB B = new ClassB();
System.out.println(MVEL.getProperty("date", A));
System.out.println(MVEL.getProperty("date", B));
}
/**
* Submitted by: Michael Neale
*/
public void testInlineCollectionParser1() {
assertEquals("q", ((Map) test("['Person.age' : [1, 2, 3, 4],'Person.rating' : 'q']")).get("Person.rating"));
assertEquals("q", ((Map) test("['Person.age' : [1, 2, 3, 4], 'Person.rating' : 'q']")).get("Person.rating"));
}
public void testIndexer() {
assertEquals("foobar", testCompiledSimple("import java.util.LinkedHashMap; LinkedHashMap map = new LinkedHashMap();" +
" map.put('a', 'foo'); map.put('b', 'bar'); s = ''; foreach (key : map.keySet()) { System.out.println(map[key]); s += map[key]; }; return s;", createTestMap()));
}
public void testLateResolveOfClass() {
ExpressionCompiler compiler = new ExpressionCompiler("System.out.println(new Foo());");
ParserContext ctx = new ParserContext();
ctx.addImport(Foo.class);
// CompiledExpression s = compiler.compile(ctx);
compiler.removeParserContext();
System.out.println(executeExpression(compiler.compile(ctx)));
}
public void testClassAliasing() {
assertEquals("foobar", test("Foo = String; new Foo('foobar')"));
}
public void testRandomExpression1() {
assertEquals("HelloWorld", test("if ((x15 = foo.bar) == foo.bar && x15 == foo.bar) { return 'HelloWorld'; } else { return 'GoodbyeWorld' } "));
}
public void testRandomExpression2() {
assertEquals(11, test("counterX = 0; foreach (item:{1,2,3,4,5,6,7,8,9,10}) { counterX++; }; return counterX + 1;"));
}
public void testRandomExpression3() {
assertEquals(0, test("counterX = 10; foreach (item:{1,1,1,1,1,1,1,1,1,1}) { counterX -= item; } return counterX;"));
}
public void testRandomExpression4() {
assertEquals(true, test("result = org.mvel2.MVEL.eval('10 * 3'); result == (10 * 3);"));
}
public void testRandomExpression5() {
assertEquals(true, test("FooClassRef = foo.getClass(); fooInst = new FooClassRef(); name = org.mvel2.MVEL.eval('name', fooInst); return name == 'dog'"));
}
public void testRandomExpression6() {
assertEquals(500, test("exprString = '250' + ' ' + '*' + ' ' + '2'; compiledExpr = org.mvel2.MVEL.compileExpression(exprString);" +
" return org.mvel2.MVEL.executeExpression(compiledExpr);"));
}
public void testRandomExpression7() {
assertEquals("FOOBAR", test("'foobar'.toUpperCase();"));
}
public void testRandomExpression8() {
assertEquals(true, test("'someString'.intern(); 'someString'.hashCode() == 'someString'.hashCode();"));
}
public void testRandomExpression9() {
assertEquals(false, test("_abc = 'someString'.hashCode(); _xyz = _abc + 1; _abc == _xyz"));
}
public void testRandomExpression10() {
assertEquals(false, test("(_abc = (_xyz = 'someString'.hashCode()) + 1); _abc == _xyz"));
}
/**
* Submitted by: Guerry Semones
*/
private Map<Object, Object> outerMap;
private Map<Object, Object> innerMap;
public void testAddIntToMapWithMapSyntax() throws Throwable {
outerMap = new HashMap<Object, Object>();
innerMap = new HashMap<Object, Object>();
outerMap.put("innerMap", innerMap);
// fails because mvel2 checks for 'tak' in the outerMap,
// rather than inside innerMap in outerMap
PropertyAccessor.set(outerMap, "innerMap['foo']", 42);
// mvel2 set it here
// assertEquals(42, outerMap.get("tak"));
// instead of here
assertEquals(42, innerMap.get("foo"));
}
public void testUpdateIntInMapWithMapSyntax() throws Throwable {
outerMap = new HashMap<Object, Object>();
innerMap = new HashMap<Object, Object>();
outerMap.put("innerMap", innerMap);
// fails because mvel2 checks for 'tak' in the outerMap,
// rather than inside innerMap in outerMap
innerMap.put("foo", 21);
PropertyAccessor.set(outerMap, "innerMap['foo']", 42);
// instead of updating it here
assertEquals(42, innerMap.get("foo"));
}
private HashMap<String, Object> context = new HashMap<String, Object>();
public void before() {
HashMap<String, Object> map = new HashMap<String, Object>();
MyBean bean = new MyBean();
bean.setVar(4);
map.put("bean", bean);
context.put("map", map);
}
public void testDeepProperty() {
before();
Object obj = executeExpression(compileExpression("map.bean.var"), context);
assertEquals(4, obj);
}
public void testDeepProperty2() {
before();
Object obj = executeExpression(compileExpression("map.bean.getVar()"), context);
assertEquals(4, obj);
}
public class MyBean {
int var;
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
}
public static class TargetClass {
private short _targetValue = 5;
public short getTargetValue() {
return _targetValue;
}
}
public void testNestedMethodCall() {
List elements = new ArrayList();
elements.add(new TargetClass());
Map variableMap = new HashMap();
variableMap.put("elements", elements);
eval(
"results = new java.util.ArrayList(); foreach (element : elements) { if( {5} contains element.targetValue.intValue()) { results.add(element); } }; results",
variableMap);
}
public void testBooleanEvaluation() {
assertEquals(true, test("true||false||false"));
}
public void testBooleanEvaluation2() {
assertEquals(true, test("equalityCheck(1,1)||fun||ackbar"));
}
/**
* Submitted by: Dimitar Dimitrov
*/
public void testFailing() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("os", "windows");
assertTrue((Boolean) eval("os ~= 'windows|unix'", map));
}
public void testSuccess() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("os", "windows");
assertTrue((Boolean) eval("'windows' ~= 'windows|unix'", map));
assertFalse((Boolean) eval("time ~= 'windows|unix'", new java.util.Date()));
}
public void testBooleanStrAppend() {
assertEquals("footrue", test("\"foo\" + true"));
}
public void testStringAppend() {
assertEquals("catbar", test("c + 'bar'"));
}
public void testConvertableTo() {
assertEquals(true, test("pi convertable_to Integer"));
}
public void testAssignPlus() {
assertEquals(10, test("xx0 = 5; xx0 += 4; xx0 + 1"));
}
public void testAssignPlus2() {
assertEquals(10, test("xx0 = 5; xx0 =+ 4; xx0 + 1"));
}
public void testAssignDiv() {
assertEquals(2, test("xx0 = 20; xx0 /= 10; xx0"));
}
public void testAssignMult() {
assertEquals(36, test("xx0 = 6; xx0 *= 6; xx0"));
}
public void testAssignSub() {
assertEquals(11, test("xx0 = 15; xx0 -= 4; xx0"));
}
public void testAssignSub2() {
assertEquals(-95, test("xx0 = 5; xx0 =- 100"));
}
public void testStaticWithExplicitParam() {
PojoStatic pojo = new PojoStatic("10");
eval("org.mvel2.tests.core.res.AStatic.Process('10')", pojo, new HashMap());
}
public void testSimpleExpression() {
PojoStatic pojo = new PojoStatic("10");
eval("value!= null", pojo, new HashMap());
}
public void testStaticWithExpressionParam() {
PojoStatic pojo = new PojoStatic("10");
assertEquals("java.lang.String", eval("org.mvel2.tests.core.res.AStatic.Process(value.getClass().getName().toString())", pojo));
}
public void testStringIndex() {
assertEquals(true, test("a = 'foobar'; a[4] == 'a'"));
}
public void testArrayConstructionSupport1() {
assertTrue(test("new String[5]") instanceof String[]);
}
public void testArrayConstructionSupport2() {
assertTrue((Boolean) test("xStr = new String[5]; xStr.size() == 5"));
}
public void testArrayConstructionSupport3() {
assertEquals("foo", test("xStr = new String[5][5]; xStr[4][0] = 'foo'; xStr[4][0]"));
}
public void testArrayConstructionSupport4() {
assertEquals(10, test("xStr = new String[5][10]; xStr[4][0] = 'foo'; xStr[4].length"));
}
public void testMath14() {
assertEquals(10 - 5 * 2 + 5 * 8 - 4, test("10-5*2 + 5*8-4"));
}
public void testMath15() {
String ex = "100-500*200 + 500*800-400";
// System.out.println("Expression: " + ex);
assertEquals(100 - 500 * 200 + 500 * 800 - 400, test(ex));
}
public void testMath16() {
String ex = "100-500*200*150 + 500*800-400";
assertEquals(100 - 500 * 200 * 150 + 500 * 800 - 400, test(ex));
}
public void testMath17() {
String ex = "(100d * 50d) * 20d / 30d * 2d";
// System.out.println("Expression: " + ex);
Object o = test(ex);
assertEquals((100d * 50d) * 20d / 30d * 2d, o);
}
public void testMath18() {
String ex = "a = 100d; b = 50d; c = 20d; d = 30d; e = 2d; (a * b) * c / d * e";
System.out.println("Expression: " + ex);
assertEquals((100d * 50d) * 20d / 30d * 2d, testCompiledSimple(ex, new HashMap()));
}
public void testMath19() {
String ex = "a = 100; b = 500; c = 200; d = 150; e = 500; f = 800; g = 400; a-b*c*d + e*f-g";
System.out.println("Expression: " + ex);
assertEquals(100 - 500 * 200 * 150 + 500 * 800 - 400, testCompiledSimple(ex, new HashMap()));
}
public void testMath32() {
String ex = "x = 20; y = 10; z = 5; x-y-z";
System.out.println("Expression: " + ex);
assertEquals(20 - 10 - 5, testCompiledSimple(ex, new HashMap()));
}
public void testMath33() {
String ex = "x = 20; y = 2; z = 2; x/y/z";
System.out.println("Expression: " + ex);
assertEquals(20 / 2 / 2, testCompiledSimple(ex, new HashMap()));
}
public void testMath20() {
String ex = "10-5*7-3*8-6";
System.out.println("Expression: " + ex);
assertEquals(10 - 5 * 7 - 3 * 8 - 6, test(ex));
}
public void testMath21() {
String expression = "100-50*70-30*80-60";
System.out.println("Expression: " + expression);
assertEquals(100 - 50 * 70 - 30 * 80 - 60, test(expression));
}
public void testMath22() {
String expression = "(100-50)*70-30*(20-9)**3";
System.out.println("Expression: " + expression);
assertEquals((int) ((100 - 50) * 70 - 30 * Math.pow(20 - 9, 3)), test(expression));
}
public void testMath22b() {
String expression = "a = 100; b = 50; c = 70; d = 30; e = 20; f = 9; g = 3; (a-b)*c-d*(e-f)**g";
System.out.println("Expression: " + expression);
assertEquals((int) ((100 - 50) * 70 - 30 * Math.pow(20 - 9, 3)), testCompiledSimple(expression, new HashMap()));
}
public void testMath23() {
String expression = "10 ** (3)*10**3";
System.out.println("Expression: " + expression);
assertEquals((int) (Math.pow(10, 3) * Math.pow(10, 3)), test(expression));
}
public void testMath24() {
String expression = "51 * 52 * 33 / 24 / 15 + 45 * 66 * 47 * 28 + 19";
double val = 51d * 52d * 33d / 24d / 15d + 45d * 66d * 47d * 28d + 19d;
System.out.println("Expression: " + expression);
System.out.println("Expected Result: " + val);
assertEquals(val, test(expression));
}
public void testMath25() {
String expression = "51 * (4 - 100 * 5) + 10 + 5 * 2 / 1 + 0 + 0 - 80";
int val = 51 * (4 - 100 * 5) + 10 + 5 * 2 / 1 + 0 + 0 - 80;
System.out.println("Expression: " + expression);
System.out.println("Expected Result: " + val);
assertEquals(val, test(expression));
}
public void testMath26() {
String expression = "5 + 3 * 8 * 2 ** 2";
int val = (int) (5d + 3d * 8d * Math.pow(2, 2));
System.out.println("Expression: " + expression);
System.out.println("Expected Result: " + val);
Object result = test(expression);
assertEquals(val, result);
}
public void testMath27() {
String expression = "50 + 30 * 80 * 20 ** 3 * 51";
double val = 50 + 30 * 80 * Math.pow(20, 3) * 51;
System.out.println("Expression: " + expression);
System.out.println("Expected Result: " + val);
Object result = test(expression);
assertEquals((int) val, result);
}
public void testMath28() {
String expression = "50 + 30 + 80 + 11 ** 2 ** 2 * 51";
double val = 50 + 30 + 80 + Math.pow(Math.pow(11, 2), 2) * 51;
Object result = test(expression);
assertEquals((int) val, result);
}
public void testMath29() {
String expression = "10 + 20 / 4 / 4";
System.out.println("Expression: " + expression);
double val = 10d + 20d / 4d / 4d;
assertEquals(val, MVEL.eval(expression));
}
public void testMath30() {
String expression = "40 / 20 + 10 + 6 / 2";
float val = 40f / 20f + 10f + 6f / 2f;
assertEquals((int) val, MVEL.eval(expression));
}
public void testMath31() {
String expression = "40 / 20 + 5 - 4 + 8 / 2 * 2 * 6 ** 2 + 6 - 8";
double val = 40f / 20f + 5f - 4f + 8f / 2f * 2f * Math.pow(6, 2) + 6f - 8f;
assertEquals((int) val, MVEL.eval(expression));
}
public void testMath34() {
String expression = "a+b-c*d*x/y-z+10";
Map map = new HashMap();
map.put("a", 200);
map.put("b", 100);
map.put("c", 150);
map.put("d", 2);
map.put("x", 400);
map.put("y", 300);
map.put("z", 75);
Serializable s = compileExpression(expression);
assertEquals(200 + 100 - 150 * 2 * 400 / 300 - 75 + 10, executeExpression(s, map));
}
public void testMath34_Interpreted() {
String expression = "a+b-c*x/y-z";
Map map = new HashMap();
map.put("a", 200);
map.put("b", 100);
map.put("c", 150);
map.put("x", 400);
map.put("y", 300);
map.put("z", 75);
assertEquals(200 + 100 - 150 * 400 / 300 - 75, MVEL.eval(expression, map));
}
public void testMath35() {
String expression = "b/x/b/b*y+a";
Map map = new HashMap();
map.put("a", 10);
map.put("b", 20);
map.put("c", 30);
map.put("x", 40);
map.put("y", 50);
map.put("z", 60);
assertNumEquals(20d / 40d / 20d / 20d * 50d + 10d, executeExpression(compileExpression(expression), map));
}
public void testMath35_Interpreted() {
String expression = "b/x/b/b*y+a";
Map map = new HashMap();
map.put("a", 10);
map.put("b", 20);
map.put("c", 30);
map.put("x", 40);
map.put("y", 50);
map.put("z", 60);
assertNumEquals(20d / 40d / 20d / 20d * 50d + 10d, MVEL.eval(expression, map));
}
public void testMath36() {
String expression = "b/x*z/a+x-b+x-b/z+y";
Map map = new HashMap();
map.put("a", 10);
map.put("b", 20);
map.put("c", 30);
map.put("x", 40);
map.put("y", 50);
map.put("z", 60);
Serializable s = compileExpression(expression);
assertNumEquals(20d / 40d * 60d / 10d + 40d - 20d + 40d - 20d / 60d + 50d, executeExpression(s, map));
}
public void testMath37() {
String expression = "x+a*a*c/x*b*z+x/y-b";
Map map = new HashMap();
map.put("a", 10);
map.put("b", 20);
map.put("c", 30);
map.put("x", 2);
map.put("y", 2);
map.put("z", 60);
Serializable s = compileExpression(expression);
assertNumEquals(2d + 10d * 10d * 30d / 2d * 20d * 60d + 2d / 2d - 20d, executeExpression(s, map));
}
public void testNullSafe() {
Foo foo = new Foo();
Map map = new HashMap();
map.put("foo", foo);
String expression = "foo.?bar.name == null";
Serializable compiled = compileExpression(expression);
OptimizerFactory.setDefaultOptimizer("reflective");
assertEquals(false, executeExpression(compiled, map));
foo.setBar(null);
assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems)
OptimizerFactory.setDefaultOptimizer("ASM");
foo.setBar(new Bar());
assertEquals(false, executeExpression(compiled, map));
foo.setBar(null);
assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems)
assertEquals(true, eval(expression, map));
}
public void testMethodInvocationWithCollectionElement() {
context = new HashMap();
context.put("pojo", new POJO());
context.put("number", "1192800637980");
Object result = MVEL.eval("pojo.function(pojo.dates[0].time)", context);
assertEquals(String.valueOf(((POJO) context.get("pojo")).getDates().iterator().next().getTime()), result);
}
public void testNestedWithInList() {
Recipient recipient1 = new Recipient();
recipient1.setName("userName1");
recipient1.setEmail("user1@domain.com");
Recipient recipient2 = new Recipient();
recipient2.setName("userName2");
recipient2.setEmail("user2@domain.com");
List list = new ArrayList();
list.add(recipient1);
list.add(recipient2);
String text =
"array = [" +
"(with ( new Recipient() ) {name = 'userName1', email = 'user1@domain.com' })," +
"(with ( new Recipient() ) {name = 'userName2', email = 'user2@domain.com' })];\n";
ParserContext context = new ParserContext();
context.addImport(Recipient.class);
ExpressionCompiler compiler = new ExpressionCompiler(text);
Serializable execution = compiler.compile(context);
List result = (List) executeExpression(execution, new HashMap());
assertEquals(list, result);
}
// public void testNestedWithInMethod() {
// Recipient recipient1 = new Recipient();
// recipient1.setName("userName1");
// recipient1.setEmail("user1@domain.com");
// Recipients recipients = new Recipients();
// recipients.addRecipient(recipient1);
// String text =
// "recipients = new Recipients();\n" +
// "recipients.addRecipient( (with ( new Recipient() ) {name = 'userName1', email = 'user1@domain.com' }) );\n" +
// "return recipients;\n";
// ParserContext context;
// context = new ParserContext();
// context.addImport(Recipient.class);
// context.addImport(Recipients.class);
// ExpressionCompiler compiler = new ExpressionCompiler(text);
// Serializable execution = compiler.compile(context);
// Recipients result = (Recipients) MVEL.executeExpression(execution);
// assertEquals(recipients, result);
// public void testNestedWithInComplexGraph() {
// Recipients recipients = new Recipients();
// Recipient recipient1 = new Recipient();
// recipient1.setName("user1");
// recipient1.setEmail("user1@domain.com");
// recipients.addRecipient(recipient1);
// Recipient recipient2 = new Recipient();
// recipient2.setName("user2");
// recipient2.setEmail("user2@domain.com");
// recipients.addRecipient(recipient2);
// EmailMessage msg = new EmailMessage();
// msg.setRecipients(recipients);
// msg.setFrom("from@domain.com");
// String text = "(with ( new EmailMessage() ) { recipients = (with (new Recipients()) { recipients = [(with ( new Recipient() ) {name = 'user1', email = 'user1@domain.com'}), (with ( new Recipient() ) {name = 'user2', email = 'user2@domain.com'}) ] }), " +
// " from = 'from@domain.com' } )";
// ParserContext context;
// context = new ParserContext();
// context.addImport(Recipient.class);
// context.addImport(Recipients.class);
// context.addImport(EmailMessage.class);
// ExpressionCompiler compiler = new ExpressionCompiler(text);
// Serializable execution = compiler.compile(context);
// EmailMessage result = (EmailMessage) MVEL.executeExpression(execution);
// assertEquals(msg, result);
// public void testNestedWithInComplexGraph2() {
// Recipients recipients = new Recipients();
// Recipient recipient1 = new Recipient();
// recipient1.setName("user1");
// recipient1.setEmail("user1@domain.com");
// recipients.addRecipient(recipient1);
// Recipient recipient2 = new Recipient();
// recipient2.setName("user2");
// recipient2.setEmail("user2@domain.com");
// recipients.addRecipient(recipient2);
// EmailMessage msg = new EmailMessage();
// msg.setRecipients(recipients);
// msg.setFrom("from@domain.com");
// String text = "";
// text += "with( new EmailMessage() ) { ";
// text += " recipients = with( new Recipients() ){ ";
// text += " recipients = [ with( new Recipient() ) { name = 'user1', email = 'user1@domain.com' }, ";
// text += " with( new Recipient() ) { name = 'user2', email = 'user2@domain.com' } ] ";
// text += " }, ";
// text += " from = 'from@domain.com' }";
// ParserContext context;
// context = new ParserContext();
// context.addImport(Recipient.class);
// context.addImport(Recipients.class);
// context.addImport(EmailMessage.class);
// ExpressionCompiler compiler = new ExpressionCompiler(text);
// Serializable execution = compiler.compile(context);
// EmailMessage result = (EmailMessage) MVEL.executeExpression(execution);
// assertEquals(msg, result);
public void testNestedWithInComplexGraph3() {
Recipients recipients = new Recipients();
Recipient recipient1 = new Recipient();
recipient1.setName("user1");
recipient1.setEmail("user1@domain.com");
recipients.addRecipient(recipient1);
Recipient recipient2 = new Recipient();
recipient2.setName("user2");
recipient2.setEmail("user2@domain.com");
recipients.addRecipient(recipient2);
EmailMessage msg = new EmailMessage();
msg.setRecipients(recipients);
msg.setFrom("from@domain.com");
String text = "";
text += "new EmailMessage().{ ";
text += " recipients = new Recipients().{ ";
text += " recipients = [ new Recipient().{ name = 'user1', email = 'user1@domain.com' }, ";
text += " new Recipient().{ name = 'user2', email = 'user2@domain.com' } ] ";
text += " }, ";
text += " from = 'from@domain.com' }";
ParserContext context;
context = new ParserContext();
context.addImport(Recipient.class);
context.addImport(Recipients.class);
context.addImport(EmailMessage.class);
OptimizerFactory.setDefaultOptimizer("ASM");
ExpressionCompiler compiler = new ExpressionCompiler(text);
Serializable execution = compiler.compile(context);
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
OptimizerFactory.setDefaultOptimizer("reflective");
context = new ParserContext(context.getParserConfiguration());
compiler = new ExpressionCompiler(text);
execution = compiler.compile(context);
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
}
public static class Recipient {
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Recipient other = (Recipient) obj;
if (email == null) {
if (other.email != null) return false;
}
else if (!email.equals(other.email)) return false;
if (name == null) {
if (other.name != null) return false;
}
else if (!name.equals(other.name)) return false;
return true;
}
}
public static class Recipients {
private List<Recipient> list = Collections.EMPTY_LIST;
public void setRecipients(List<Recipient> recipients) {
this.list = recipients;
}
public boolean addRecipient(Recipient recipient) {
if (list == Collections.EMPTY_LIST) {
this.list = new ArrayList<Recipient>();
}
if (!this.list.contains(recipient)) {
this.list.add(recipient);
return true;
}
return false;
}
public boolean removeRecipient(Recipient recipient) {
return this.list.remove(recipient);
}
public List<Recipient> getRecipients() {
return this.list;
}
public Recipient[] toArray() {
return list.toArray(new Recipient[list.size()]);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((list == null) ? 0 : list.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Recipients other = (Recipients) obj;
if (list == null) {
if (other.list != null) return false;
}
return list.equals(other.list);
}
}
public static class EmailMessage {
private Recipients recipients;
private String from;
public EmailMessage() {
}
public Recipients getRecipients() {
return recipients;
}
public void setRecipients(Recipients recipients) {
this.recipients = recipients;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((from == null) ? 0 : from.hashCode());
result = prime * result + ((recipients == null) ? 0 : recipients.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final EmailMessage other = (EmailMessage) obj;
if (from == null) {
if (other.from != null) return false;
}
else if (!from.equals(other.from)) return false;
if (recipients == null) {
if (other.recipients != null) return false;
}
else if (!recipients.equals(other.recipients)) return false;
return true;
}
}
public class POJO {
private Set<Date> dates = new HashSet<Date>();
public POJO() {
dates.add(new Date());
}
public Set<Date> getDates() {
return dates;
}
public void setDates(Set<Date> dates) {
this.dates = dates;
}
public String function(long num) {
return String.valueOf(num);
}
}
public void testSubEvaluation() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("EV_BER_BER_NR", "12345");
map.put("EV_BER_BER_PRIV", Boolean.FALSE);
assertEquals("12345", testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')", null, map));
map.put("EV_BER_BER_PRIV", Boolean.TRUE);
assertEquals("12345/PRIVAT", testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')", null, map));
}
public void testNestedMethod1() {
Vector vectorA = new Vector();
Vector vectorB = new Vector();
vectorA.add("Foo");
Map map = new HashMap();
map.put("vecA", vectorA);
map.put("vecB", vectorB);
testCompiledSimple("vecB.add(vecA.remove(0)); vecA.add('Foo');", null, map);
assertEquals("Foo", vectorB.get(0));
}
public void testNegativeArraySizeBug() throws Exception {
String expressionString1 = "results = new java.util.ArrayList(); foreach (element : elements) { if( ( {30, 214, 158, 31, 95, 223, 213, 86, 159, 34, 32, 96, 224, 160, 85, 201, 29, 157, 100, 146, 82, 203, 194, 145, 140, 81, 27, 166, 212, 38, 28, 94, 168, 23, 87, 150, 35, 149, 193, 33, 132, 206, 93, 196, 24, 88, 195, 36, 26, 154, 167, 108, 204, 74, 46, 25, 153, 202, 79, 207, 143, 43, 16, 80, 198, 208, 144, 41, 97, 142, 83, 18, 162, 103, 155, 98, 44, 17, 205, 77, 156, 141, 165, 102, 84, 37, 101, 222, 40, 104, 99, 177, 182, 22, 180, 21, 137, 221, 179, 78, 42, 178, 19, 183, 139, 218, 219, 39, 220, 20, 184, 217, 138, 62, 190, 171, 123, 113, 59, 118, 225, 124, 169, 60, 117, 1} contains element.attribute ) ) { results.add(element); } }; results";
String expressionString2 = "results = new java.util.ArrayList(); foreach (element : elements) { if( ( {30, 214, 158, 31, 95, 223, 213, 86, 159, 34, 32, 96, 224, 160, 85, 201, 29, 157, 100, 146, 82, 203, 194, 145, 140, 81, 27, 166, 212, 38, 28, 94, 168, 23, 87, 150, 35, 149, 193, 33, 132, 206, 93, 196, 24, 88, 195, 36, 26, 154, 167, 108, 204, 74, 46, 25, 153, 202, 79, 207, 143, 43, 16, 80, 198, 208, 144, 41, 97, 142, 83, 18, 162, 103, 155, 98, 44, 17, 205, 77, 156, 141, 165, 102, 84, 37, 101, 222, 40, 104, 99, 177, 182, 22, 180, 21, 137, 221, 179, 78, 42, 178, 19, 183, 139, 218, 219, 39, 220, 20, 184, 217, 138, 62, 190, 171, 123, 113, 59, 118, 225, 124, 169, 60, 117, 1, 61, 189, 122, 68, 58, 119, 63, 226, 3, 172} contains element.attribute ) ) { results.add(element); } }; results";
List<Target> targets = new ArrayList<Target>();
targets.add(new Target(1));
targets.add(new Target(999));
Map vars = new HashMap();
vars.put("elements", targets);
assertEquals(1, ((List) testCompiledSimple(expressionString1, null, vars)).size());
assertEquals(1, ((List) testCompiledSimple(expressionString2, null, vars)).size());
}
public static final class Target {
private int _attribute;
public Target(int attribute_) {
_attribute = attribute_;
}
public int getAttribute() {
return _attribute;
}
}
public void testFunctionDefAndCall() {
assertEquals("FoobarFoobar",
test("function heyFoo() { return 'Foobar'; };\n" +
"return heyFoo() + heyFoo();"));
}
public void testFunctionDefAndCall2() {
ExpressionCompiler compiler = new ExpressionCompiler("function heyFoo() { return 'Foobar'; };\n" +
"return heyFoo() + heyFoo();");
Serializable s = compiler.compile();
Map<String, Function> m = CompilerTools.extractAllDeclaredFunctions((CompiledExpression) s);
assertTrue(m.containsKey("heyFoo"));
OptimizerFactory.setDefaultOptimizer("reflective");
assertEquals("FoobarFoobar", executeExpression(s, new HashMap()));
assertEquals("FoobarFoobar", executeExpression(s, new HashMap()));
OptimizerFactory.setDefaultOptimizer("dynamic");
}
public void testFunctionDefAndCall3() {
assertEquals("FOOBAR", test("function testFunction() { a = 'foo'; b = 'bar'; a + b; }; testFunction().toUpperCase(); "));
}
public void testFunctionDefAndCall4() {
assertEquals("barfoo", test("function testFunction(input) { return input; }; testFunction('barfoo');"));
}
public void testFunctionDefAndCall5() {
assertEquals(10, test("function testFunction(x, y) { return x + y; }; testFunction(7, 3);"));
}
public void testFunctionDefAndCall6() {
assertEquals("foo", MVEL.eval("def fooFunction(x) x; fooFunction('foo')", new HashMap()));
}
public void testDynamicImports2() {
assertEquals(BufferedReader.class, test("import java.io.*; BufferedReader"));
}
public void testStringWithTernaryIf() {
test("System.out.print(\"Hello : \" + (foo != null ? \"FOO!\" : \"NO FOO\") + \". Bye.\");");
}
public void testFunctionsScript1() throws IOException {
MVEL.evalFile(new File("samples/scripts/functions1.mvel"));
}
public void testQuickSortScript1() throws IOException {
MVEL.evalFile(new File("samples/scripts/quicksort.mvel"));
}
public void testQuickSortScript2() throws IOException {
Object[] sorted = (Object[]) test(new String(loadFromFile(new File("samples/scripts/quicksort.mvel"))));
int last = -1;
for (Object o : sorted) {
if (last == -1) {
last = (Integer) o;
}
else {
assertTrue(((Integer) o) > last);
last = (Integer) o;
}
}
}
public void testQuickSortScript3() throws IOException {
Object[] sorted = (Object[]) test(new String(loadFromFile(new File("samples/scripts/quicksort2.mvel"))));
int last = -1;
for (Object o : sorted) {
if (last == -1) {
last = (Integer) o;
}
else {
assertTrue(((Integer) o) > last);
last = (Integer) o;
}
}
}
public void testMultiLineString() throws IOException {
MVEL.evalFile(new File("samples/scripts/multilinestring.mvel"));
}
public void testCompactIfElse() {
assertEquals("foo", test("if (false) 'bar'; else 'foo';"));
}
public void testAndOpLiteral() {
assertEquals(true, test("true && true"));
}
public void testAnonymousFunctionDecl() {
assertEquals(3, test("anonFunc = function (a,b) { return a + b; }; anonFunc(1,2)"));
}
public void testFunctionSemantics() {
assertEquals(true, test("function fooFunction(a) { return a; }; x__0 = ''; 'boob' == fooFunction(x__0 = 'boob') && x__0 == 'boob';"));
}
public void testUseOfVarKeyword() {
assertEquals("FOO_BAR", test("var barfoo = 'FOO_BAR'; return barfoo;"));
}
public void testAssignment5() {
assertEquals(15, test("x = (10) + (5); x"));
}
public void testSetExpressions1() {
Map<String, Object> myMap = new HashMap<String, Object>();
final Serializable fooExpr = compileSetExpression("foo");
executeSetExpression(fooExpr, myMap, "blah");
assertEquals("blah", myMap.get("foo"));
executeSetExpression(fooExpr, myMap, "baz");
assertEquals("baz", myMap.get("foo"));
}
public void testInlineCollectionNestedObjectCreation() {
Map m = (Map) test("['Person.age' : [1, 2, 3, 4], 'Person.rating' : ['High', 'Low']," +
" 'Person.something' : (new String('foo').toUpperCase())]");
assertEquals("FOO", m.get("Person.something"));
}
public void testInlineCollectionNestedObjectCreation1() {
Map m = (Map) test("[new String('foo') : new String('bar')]");
assertEquals("bar", m.get("foo"));
}
public void testEgressType() {
ExpressionCompiler compiler = new ExpressionCompiler("( $cheese )");
ParserContext context = new ParserContext();
context.addInput("$cheese", Cheese.class);
assertEquals(Cheese.class, compiler.compile(context).getKnownEgressType());
}
public void testDuplicateVariableDeclaration() {
ExpressionCompiler compiler = new ExpressionCompiler("String x = \"abc\"; Integer x = new Integer( 10 );");
ParserContext context = new ParserContext();
try {
compiler.compile(context);
fail("Compilation must fail with duplicate variable declaration exception.");
}
catch (CompileException ce) {
// success
}
}
public void testFullyQualifiedTypeAndCast() {
assertEquals(1, test("java.lang.Integer number = (java.lang.Integer) '1';"));
}
public void testAnonymousFunction() {
assertEquals("foobar", test("a = function { 'foobar' }; a();"));
}
public void testThreadSafetyInterpreter1() {
//First evaluation
System.out.println("First evaluation: " + MVEL.eval("true"));
new Thread(new Runnable() {
public void run() {
// Second evaluation - this succeeds only if the first evaluation is not commented out
System.out.println("Second evaluation: " + MVEL.eval("true"));
}
}).start();
}
public void testStringEquals() {
assertEquals(true, test("ipaddr == '10.1.1.2'"));
}
public void testArrayList() throws SecurityException, NoSuchMethodException {
Collection<String> collection = new ArrayList<String>();
collection.add("I CAN HAS CHEEZBURGER");
assertEquals(collection.size(), MVEL.eval("size()", collection));
}
public void testUnmodifiableCollection() throws SecurityException, NoSuchMethodException {
Collection<String> collection = new ArrayList<String>();
collection.add("I CAN HAS CHEEZBURGER");
collection = unmodifiableCollection(collection);
assertEquals(collection.size(), MVEL.eval("size()", collection));
}
public void testSingleton() throws SecurityException, NoSuchMethodException {
Collection<String> collection = Collections.singleton("I CAN HAS CHEEZBURGER");
assertEquals(collection.size(), MVEL.eval("size()", collection));
}
public void testCharComparison() {
assertEquals(true, test("'z' > 'a'"));
}
public void testCharComparison2() {
assertEquals(false, test("'z' < 'a'"));
}
public void testRegExMatch() {
assertEquals(true, MVEL.eval("$test = 'foo'; $ex = 'f.*'; $test ~= $ex", new HashMap()));
}
public static class TestClass2 {
public void addEqualAuthorizationConstraint(Foo leg, Bar ctrlClass, Integer authorization) {
}
}
public void testJIRA93() {
Map testMap = createTestMap();
testMap.put("testClass2", new TestClass2());
Serializable s = compileExpression("testClass2.addEqualAuthorizationConstraint(foo, foo.bar, 5)");
for (int i = 0; i < 5; i++) {
executeExpression(s, testMap);
}
}
public void testJIRA96() {
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.addInput("fooString", String[].class);
ExpressionCompiler compiler = new ExpressionCompiler("fooString[0].toUpperCase()");
compiler.compile(ctx);
}
public void testStrongTyping() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
try {
new ExpressionCompiler("blah").compile(ctx);
}
catch (Exception e) {
// should fail
return;
}
assertTrue(false);
}
public void testStrongTyping2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("blah", String.class);
try {
new ExpressionCompiler("1-blah").compile(ctx);
}
catch (Exception e) {
e.printStackTrace();
return;
}
assertTrue(false);
}
public void testStringToArrayCast() {
Object o = test("(char[]) 'abcd'");
assertTrue(o instanceof char[]);
}
public void testStringToArrayCast2() {
assertTrue((Boolean) test("_xyxy = (char[]) 'abcd'; _xyxy[0] == 'a'"));
}
public void testStaticallyTypedArrayVar() {
assertTrue((Boolean) test("char[] _c___ = new char[10]; _c___ instanceof char[]"));
}
public void testParserErrorHandling() {
final ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler("a[");
try {
compiler.compile(ctx);
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testJIRA99_Interpreted() {
Map map = new HashMap();
map.put("x", 20);
map.put("y", 10);
map.put("z", 5);
assertEquals(20 - 10 - 5, MVEL.eval("x - y - z", map));
}
public void testJIRA99_Compiled() {
Map map = new HashMap();
map.put("x", 20);
map.put("y", 10);
map.put("z", 5);
assertEquals(20 - 10 - 5, testCompiledSimple("x - y - z", map));
}
public void testJIRA100() {
assertEquals(new BigDecimal(20), test("java.math.BigDecimal axx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal bxx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal cxx = axx + bxx; return cxx; "));
}
// public void testJIRA100a() {
// assertEquals(new BigDecimal(233.23d), test("java.math.BigDecimal axx = new java.math.BigDecimal( 109.45 ); java.math.BigDecimal bxx = new java.math.BigDecimal( 123.78 ); java.math.BigDecimal cxx = axx + bxx; return cxx; "));
public void testJIRA100b() {
String expression = "(8 / 10) * 100 <= 80;";
assertEquals((8 / 10) * 100 <= 80, testCompiledSimple(expression, new HashMap()));
}
public void testJIRA92() {
assertEquals(false, test("'stringValue' > null"));
}
public void testAssignToBean() {
Person person = new Person();
MVEL.eval("this.name = 'foo'", person);
assertEquals("foo", person.getName());
executeExpression(compileExpression("this.name = 'bar'"), person);
assertEquals("bar", person.getName());
}
public void testParameterizedTypeInStrictMode() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", HashMap.class, new Class[]{String.class, String.class});
ExpressionCompiler compiler = new ExpressionCompiler("foo.get('bar').toUpperCase()");
compiler.compile(ctx);
}
public void testParameterizedTypeInStrictMode2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("ctx", Object.class);
ExpressionCompiler compiler = new ExpressionCompiler("org.mvel2.DataConversion.convert(ctx, String).toUpperCase()");
// CompiledExpression ce = compiler.compile(ctx);
assertEquals(String.class, compiler.compile(ctx).getKnownEgressType());
}
public void testParameterizedTypeInStrictMode3() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
ExpressionCompiler compiler = new ExpressionCompiler("base.list");
assertTrue(compiler.compile(ctx).getParserContext().getLastTypeParameters()[0].equals(String.class));
}
public void testParameterizedTypeInStrictMode4() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
ExpressionCompiler compiler = new ExpressionCompiler("base.list.get(1).toUpperCase()");
CompiledExpression ce = compiler.compile(ctx);
assertEquals(String.class, ce.getKnownEgressType());
}
public void testMapAssignmentNestedExpression() {
Map map = new HashMap();
map.put("map", new HashMap());
String ex = "map[java.lang.Integer.MAX_VALUE] = 'bar'; map[java.lang.Integer.MAX_VALUE];";
assertEquals("bar", executeExpression(compileExpression(ex), map));
assertEquals("bar", MVEL.eval(ex, map));
}
public void testMapAssignmentNestedExpression2() {
Map map = new HashMap();
map.put("x", "bar");
map.put("map", new HashMap());
String ex = "map[x] = 'foo'; map['bar'];";
assertEquals("foo", executeExpression(compileExpression(ex), map));
assertEquals("foo", MVEL.eval(ex, map));
}
/**
* MVEL-103
*/
public static class MvelContext {
public boolean singleCalled;
public boolean arrayCalled;
public String[] regkeys;
public void methodForTest(String string) {
System.out.println("sigle param method called!");
singleCalled = true;
}
public void methodForTest(String[] strings) {
System.out.println("array param method called!");
arrayCalled = true;
}
public void setRegkeys(String[] regkeys) {
this.regkeys = regkeys;
}
public void setRegkeys(String regkey) {
this.regkeys = regkey.split(",");
}
}
public void testMethodResolutionOrder() {
MvelContext mvelContext = new MvelContext();
MVEL.eval("methodForTest({'1','2'})", mvelContext);
MVEL.eval("methodForTest('1')", mvelContext);
assertTrue(mvelContext.arrayCalled && mvelContext.singleCalled);
}
public void testOKQuoteComment() throws Exception {
// ' in comments outside of blocks seem OK
compileExpression("// ' this is OK!");
compileExpression("// ' this is OK!\n");
compileExpression("// ' this is OK!\nif(1==1) {};");
}
public void testOKDblQuoteComment() throws Exception {
// " in comments outside of blocks seem OK
compileExpression("// \" this is OK!");
compileExpression("// \" this is OK!\n");
compileExpression("// \" this is OK!\nif(1==1) {};");
}
public void testIfComment() throws Exception {
// No quote? OK!
compileExpression("if(1 == 1) {\n" +
" // Quote & Double-quote seem to break this expression\n" +
"}");
}
public void testIfQuoteCommentBug() throws Exception {
// Comments in an if seem to fail if they contain a '
compileExpression("if(1 == 1) {\n" +
" // ' seems to break this expression\n" +
"}");
}
public void testIfDblQuoteCommentBug() throws Exception {
// Comments in a foreach seem to fail if they contain a '
compileExpression("if(1 == 1) {\n" +
" // ' seems to break this expression\n" +
"}");
}
public void testForEachQuoteCommentBug() throws Exception {
// Comments in a foreach seem to fail if they contain a '
compileExpression("foreach ( item : 10 ) {\n" +
" // The ' character causes issues\n" +
"}");
}
public void testForEachDblQuoteCommentBug() throws Exception {
// Comments in a foreach seem to fail if they contain a '
compileExpression("foreach ( item : 10 ) {\n" +
" // The \" character causes issues\n" +
"}");
}
public void testForEachCommentOK() throws Exception {
// No quote? OK!
compileExpression("foreach ( item : 10 ) {\n" +
" // The quote & double quote characters cause issues\n" +
"}");
}
public void testElseIfCommentBugPreCompiled() throws Exception {
// Comments can't appear before else if() - compilation works, but evaluation fails
executeExpression(compileExpression("// This is never true\n" +
"if (1==0) {\n" +
" // Never reached\n" +
"}\n" +
"// This is always true...\n" +
"else if (1==1) {" +
" System.out.println('Got here!');" +
"}\n"));
}
public void testElseIfCommentBugEvaluated() throws Exception {
// Comments can't appear before else if()
MVEL.eval("// This is never true\n" +
"if (1==0) {\n" +
" // Never reached\n" +
"}\n" +
"// This is always true...\n" +
"else if (1==1) {" +
" System.out.println('Got here!');" +
"}\n");
}
public void testRegExpOK() throws Exception {
// This works OK intepreted
assertEquals(Boolean.TRUE, MVEL.eval("'Hello'.toUpperCase() ~= '[A-Z]{0,5}'"));
assertEquals(Boolean.TRUE, MVEL.eval("1 == 0 || ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')"));
// This works OK if toUpperCase() is avoided in pre-compiled
assertEquals(Boolean.TRUE, executeExpression(compileExpression("'Hello' ~= '[a-zA-Z]{0,5}'")));
}
public void testRegExpPreCompiledBug() throws Exception {
// If toUpperCase() is used in the expression then this fails; returns null not
// a boolean.
Object ser = compileExpression("'Hello'.toUpperCase() ~= '[a-zA-Z]{0,5}'");
assertEquals(Boolean.TRUE, executeExpression(ser));
}
public void testRegExpOrBug() throws Exception {
// This fails during execution due to returning null, I think...
assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 0 || ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')")));
}
public void testRegExpAndBug() throws Exception {
// This also fails due to returning null, I think...
// Object ser = MVEL.compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')");
assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')")));
}
public void testLiteralUnionWithComparison() {
// Serializable ce = compileExpression("'Foo'.toUpperCase() == 'FOO'");
assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')")));
}
public static final List<String> STRINGS = Arrays.asList("hi", "there");
public static class A {
public List<String> getStrings() {
return STRINGS;
}
}
public final void testDetermineEgressParametricType() {
final ParserContext parserContext = new ParserContext();
parserContext.setStrongTyping(true);
parserContext.addInput("strings", List.class, new Class[]{String.class});
final CompiledExpression expr = new ExpressionCompiler("strings").compile(parserContext);
assertTrue(STRINGS.equals(executeExpression(expr, new A())));
final Type[] typeParameters = expr.getParserContext().getLastTypeParameters();
assertTrue(typeParameters != null);
assertTrue(String.class.equals(typeParameters[0]));
}
public final void testDetermineEgressParametricType2() {
final ParserContext parserContext = new ParserContext();
parserContext.setStrongTyping(true);
parserContext.addInput("strings", List.class, new Class[]{String.class});
final CompiledExpression expr = new ExpressionCompiler("strings", parserContext)
.compile();
assertTrue(STRINGS.equals(executeExpression(expr, new A())));
final Type[] typeParameters = expr.getParserContext().getLastTypeParameters();
assertTrue(null != typeParameters);
assertTrue(String.class.equals(typeParameters[0]));
}
public void testCustomPropertyHandler() {
PropertyHandlerFactory.registerPropertyHandler(SampleBean.class, new SampleBeanAccessor());
assertEquals("dog", test("foo.sampleBean.bar.name"));
PropertyHandlerFactory.unregisterPropertyHandler(SampleBean.class);
}
public void testSetAccessorOverloadedEqualsStrictMode() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", Foo.class);
try {
CompiledExpression expr = new ExpressionCompiler("foo.bar = 0").compile(ctx);
}
catch (CompileException e) {
// should fail.
e.printStackTrace();
return;
}
assertTrue(false);
}
public void testSetAccessorOverloadedEqualsStrictMode2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", Foo.class);
try {
CompiledExpression expr = new ExpressionCompiler("foo.aValue = 'bar'").compile(ctx);
}
catch (CompileException e) {
assertTrue(false);
}
}
public void testAnalysisCompile() {
CompiledExpression ce = new ExpressionCompiler("foo.aValue = 'bar'").compile();
assertTrue(ce.getParserContext().getInputs().keySet().contains("foo"));
}
public void testInlineWith() {
CompiledExpression expr = new ExpressionCompiler("foo.{name='poopy', aValue='bar'}").compile();
Foo f = (Foo) executeExpression(expr, createTestMap());
assertEquals("poopy", f.getName());
assertEquals("bar", f.aValue);
}
public void testInlineWith2() {
CompiledExpression expr = new ExpressionCompiler("foo.{name = 'poopy', aValue = 'bar', bar.{name = 'foobie'}}").compile();
Foo f = (Foo) executeExpression(expr, createTestMap());
assertEquals("poopy", f.getName());
assertEquals("bar", f.aValue);
assertEquals("foobie", f.getBar().getName());
}
public void testInlineWith3() {
CompiledExpression expr = new ExpressionCompiler("foo.{name = 'poopy', aValue = 'bar', bar.{name = 'foobie'}, toUC('doopy')}").compile();
Foo f = (Foo) executeExpression(expr, createTestMap());
assertEquals("poopy", f.getName());
assertEquals("bar", f.aValue);
assertEquals("foobie", f.getBar().getName());
assertEquals("doopy", f.register);
}
public void testInlineWith4() {
OptimizerFactory.setDefaultOptimizer("ASM");
ExpressionCompiler expr = new ExpressionCompiler("new Foo().{ name = 'bar' }");
ParserContext pCtx = new ParserContext();
pCtx.addImport(Foo.class);
CompiledExpression c = expr.compile(pCtx);
Foo f = (Foo) executeExpression(c);
assertEquals("bar", f.getName());
f = (Foo) executeExpression(c);
assertEquals("bar", f.getName());
}
public void testInlineWith5() {
OptimizerFactory.setDefaultOptimizer("ASM");
ParserContext pCtx = new ParserContext();
pCtx.setStrongTyping(true);
pCtx.addInput("foo", Foo.class);
CompiledExpression expr = new ExpressionCompiler("foo.{name='poopy', aValue='bar'}").compile(pCtx);
Foo f = (Foo) executeExpression(expr, createTestMap());
assertEquals("poopy", f.getName());
assertEquals("bar", f.aValue);
}
public void testInlineWithImpliedThis() {
Base b = new Base();
ExpressionCompiler expr = new ExpressionCompiler(".{ data = 'foo' }");
CompiledExpression compiled = expr.compile();
executeExpression(compiled, b);
assertEquals(b.data, "foo");
}
public void testDataConverterStrictMode() throws Exception {
OptimizerFactory.setDefaultOptimizer("ASM");
DataConversion.addConversionHandler(Date.class, new MVELDateCoercion());
ParserContext ctx = new ParserContext();
ctx.addImport("Cheese", Cheese.class);
ctx.setStrongTyping(true);
ctx.setStrictTypeEnforcement(true);
Locale.setDefault(Locale.US);
Cheese expectedCheese = new Cheese();
expectedCheese.setUseBy(new SimpleDateFormat("dd-MMM-yyyy").parse("10-Jul-1974"));
ExpressionCompiler compiler = new ExpressionCompiler("c = new Cheese(); c.useBy = '10-Jul-1974'; return c");
Cheese actualCheese = (Cheese) executeExpression(compiler.compile(ctx), createTestMap());
assertEquals(expectedCheese.getUseBy(), actualCheese.getUseBy());
}
public static class MVELDateCoercion implements ConversionHandler {
public boolean canConvertFrom(Class cls) {
if (cls == String.class || cls.isAssignableFrom(Date.class)) {
return true;
}
else {
return false;
}
}
public Object convertFrom(Object o) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
if (o instanceof String) {
return sdf.parse((String) o);
}
else {
return o;
}
}
catch (Exception e) {
throw new RuntimeException("Exception was thrown", e);
}
}
}
private static final KnowledgeHelperFixer fixer = new KnowledgeHelperFixer();
public void testSingleLineCommentSlash() {
String result = fixer.fix(" //System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );");
assertEquals(" //System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );",
result);
}
public void testSingleLineCommentHash() {
String result = fixer.fix(" #System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );");
assertEquals(" #System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );",
result);
}
public void testMultiLineComment() {
String result = fixer.fix(" /*System.out.println( \"help\" );\r\n*/ System.out.println( \"help\" ); \r\n list.add( $person );");
assertEquals(" /*System.out.println( \"help\" );\r\n*/ System.out.println( \"help\" ); \r\n list.add( $person );",
result);
}
public void testAdd__Handle__Simple() {
String result = fixer.fix("update(myObject );");
assertEqualsIgnoreWhitespace("drools.update(myObject );",
result);
result = fixer.fix("update ( myObject );");
assertEqualsIgnoreWhitespace("drools.update( myObject );",
result);
}
public void testAdd__Handle__withNewLines() {
final String result = fixer.fix("\n\t\n\tupdate( myObject );");
assertEqualsIgnoreWhitespace("\n\t\n\tdrools.update( myObject );",
result);
}
public void testAdd__Handle__rComplex() {
String result = fixer.fix("something update( myObject); other");
assertEqualsIgnoreWhitespace("something drools.update( myObject); other",
result);
result = fixer.fix("something update ( myObject );");
assertEqualsIgnoreWhitespace("something drools.update( myObject );",
result);
result = fixer.fix(" update( myObject ); x");
assertEqualsIgnoreWhitespace(" drools.update( myObject ); x",
result);
//should not touch, as it is not a stand alone word
result = fixer.fix("xxupdate(myObject ) x");
assertEqualsIgnoreWhitespace("xxupdate(myObject ) x",
result);
}
public void testMultipleMatches() {
String result = fixer.fix("update(myObject); update(myObject );");
assertEqualsIgnoreWhitespace("drools.update(myObject); drools.update(myObject );",
result);
result = fixer.fix("xxx update(myObject ); update( myObject ); update( yourObject ); yyy");
assertEqualsIgnoreWhitespace("xxx drools.update(myObject ); drools.update( myObject ); drools.update( yourObject ); yyy",
result);
}
public void testAssert1() {
final String raw = "insert( foo );";
final String result = "drools.insert( foo );";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAssert2() {
final String raw = "some code; insert( new String(\"foo\") );\n More();";
final String result = "some code; drools.insert( new String(\"foo\") );\n More();";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAssertLogical() {
final String raw = "some code; insertLogical(new String(\"foo\"));\n More();";
final String result = "some code; drools.insertLogical(new String(\"foo\"));\n More();";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testModifyRetractModifyInsert() {
final String raw = "some code; insert( bar ); modifyRetract( foo );\n More(); retract( bar ); modifyInsert( foo );";
final String result = "some code; drools.insert( bar ); drools.modifyRetract( foo );\n More(); drools.retract( bar ); drools.modifyInsert( foo );";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAllActionsMushedTogether() {
String result = fixer.fix("insert(myObject ); update(ourObject);\t retract(herObject);");
assertEqualsIgnoreWhitespace("drools.insert(myObject ); drools.update(ourObject);\t drools.retract(herObject);",
result);
result = fixer.fix("insert( myObject ); update(ourObject);\t retract(herObject );\ninsert( myObject ); update(ourObject);\t retract( herObject );");
assertEqualsIgnoreWhitespace("drools.insert( myObject ); drools.update(ourObject);\t drools.retract(herObject );\ndrools.insert( myObject ); drools.update(ourObject);\t drools.retract( herObject );",
result);
}
public void testLeaveLargeAlone() {
final String original = "yeah yeah yeah minsert( xxx ) this is a long() thing Person (name=='drools') modify a thing";
final String result = fixer.fix(original);
assertEqualsIgnoreWhitespace(original,
result);
}
public void testWithNull() {
final String original = null;
final String result = fixer.fix(original);
assertEqualsIgnoreWhitespace(original,
result);
}
public void testLeaveAssertAlone() {
final String original = "drools.insert(foo)";
assertEqualsIgnoreWhitespace(original,
fixer.fix(original));
}
public void testLeaveAssertLogicalAlone() {
final String original = "drools.insertLogical(foo)";
assertEqualsIgnoreWhitespace(original,
fixer.fix(original));
}
public void testWackyAssert() {
final String raw = "System.out.println($person1.getName() + \" and \" + $person2.getName() +\" are sisters\");\n" + "insert($person1.getName(\"foo\") + \" and \" + $person2.getName() +\" are sisters\"); yeah();";
final String expected = "System.out.println($person1.getName() + \" and \" + $person2.getName() +\" are sisters\");\n" + "drools.insert($person1.getName(\"foo\") + \" and \" + $person2.getName() +\" are sisters\"); yeah();";
assertEqualsIgnoreWhitespace(expected,
fixer.fix(raw));
}
public void testMoreAssertCraziness() {
final String raw = "foobar(); (insert(new String(\"blah\").get()); bangBangYudoHono();)";
assertEqualsIgnoreWhitespace("foobar(); (drools.insert(new String(\"blah\").get()); bangBangYudoHono();)",
fixer.fix(raw));
}
public void testRetract() {
final String raw = "System.out.println(\"some text\");retract(object);";
assertEqualsIgnoreWhitespace("System.out.println(\"some text\");drools.retract(object);",
fixer.fix(raw));
}
private void assertEqualsIgnoreWhitespace(final String expected,
final String actual) {
if (expected == null || actual == null) {
assertEquals(expected,
actual);
return;
}
final String cleanExpected = expected.replaceAll("\\s+",
"");
final String cleanActual = actual.replaceAll("\\s+",
"");
assertEquals(cleanExpected,
cleanActual);
}
public void testIsDefOperator() {
assertEquals(true, test("_v1 = 'bar'; isdef _v1"));
}
public void testIsDefOperator2() {
assertEquals(false, test("isdef _v1"));
}
public void testIsDefOperator3() {
assertEquals(true, test("!(isdef _v1)"));
}
public void testIsDefOperator4() {
assertEquals(true, test("! (isdef _v1)"));
}
public void testIsDefOperator5() {
assertEquals(true, test("!isdef _v1"));
}
public void testReturnType1() {
assertEquals(Double.class, new ExpressionCompiler("100.5").compile().getKnownEgressType());
}
public void testReturnType2() {
assertEquals(Integer.class, new ExpressionCompiler("1").compile().getKnownEgressType());
}
public void testStrongTyping3() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
try {
new ExpressionCompiler("foo.toUC(100.5").compile(ctx);
}
catch (Exception e) {
// should fail.
return;
}
assertTrue(false);
}
public void testDoLoop() {
assertEquals(10, test("i = 0; do { i++ } while (i != 10); i"));
}
public void testDoLoop2() {
assertEquals(50, test("i=100;do{i--}until(i==50); i"));
}
public void testForLoop() {
assertEquals("012345", test("String str = ''; for(i=0;i<6;i++) { str += i }; str"));
}
public void testForLoop2() {
assertEquals("012345", MVEL.eval("String str='';for(i=0;i<6;i++){str+=i};str", new HashMap()));
}
public void testUntilLoop() {
assertEquals("012345", test("String str = ''; int i = 0; until (i == 6) { str += i++; }; str"));
}
public void testEgressType1() {
assertEquals(Boolean.class, new ExpressionCompiler("foo != null").compile().getKnownEgressType());
}
public void testIncrementInBooleanStatement() {
assertEquals(true, test("hour++ < 61 && hour == 61"));
}
public void testIncrementInBooleanStatement2() {
assertEquals(true, test("++hour == 61"));
}
public void testDeepNestedLoopsInFunction() {
assertEquals(10, test("def increment(i) { i + 1 }; def ff(i) { x = 0; while (i < 1) { " +
"x++; while (i < 10) { i = increment(i); } }; if (x == 1) return i; else -1; }; i = 0; ff(i);"));
}
public void testArrayDefinitionWithInitializer() {
String[] compareTo = new String[]{"foo", "bar"};
String[] results = (String[]) test("new String[] { 'foo', 'bar' }");
for (int i = 0; i < compareTo.length; i++) {
if (!compareTo[i].equals(results[i])) throw new AssertionError("arrays do not match.");
}
}
public void testStaticallyTypedItemInForEach() {
assertEquals("1234", test("StringBuffer sbuf = new StringBuffer(); foreach (int i : new int[] { 1,2,3,4 }) { sbuf.append(i); }; sbuf.toString()"));
}
public void testArrayDefinitionWithCoercion() {
Double[] d = (Double[]) test("new double[] { 1,2,3,4 }");
assertEquals(2d, d[1]);
}
public void testArrayDefinitionWithCoercion2() {
Float[] d = (Float[]) test("new float[] { 1,2,3,4 }");
assertEquals(2f, d[1]);
}
public void testStaticallyTypedLong() {
assertEquals(10l, test("10l"));
}
public void testCompileTimeCoercion() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", Foo.class);
assertEquals(true, executeExpression(new ExpressionCompiler("foo.bar.woof == 'true'").compile(ctx), createTestMap()));
}
public void testHexCharacter() {
assertEquals(0x0A, MVEL.eval("0x0A"));
}
public void testOctalEscapes() {
assertEquals("\344", MVEL.eval("'\\344'"));
}
public void testOctalEscapes2() {
assertEquals("\7", MVEL.eval("'\\7'"));
}
public void testOctalEscapes3() {
assertEquals("\777", MVEL.eval("'\\777'"));
}
public void testUniHex1() {
assertEquals("\uFFFF::", MVEL.eval("'\\uFFFF::'"));
}
public void testNumLiterals() {
assertEquals(1e1f, MVEL.eval("1e1f"));
}
public void testNumLiterals2() {
assertEquals(2.f, MVEL.eval("2.f"));
}
public void testNumLiterals3() {
assertEquals(.3f, MVEL.eval(".3f"));
}
public void testNumLiterals4() {
assertEquals(3.14f, MVEL.eval("3.14f"));
}
public void testNumLiterals5() {
Object o = MVEL.eval("1e1");
assertEquals(1e1, MVEL.eval("1e1"));
}
public void testNumLiterals6() {
assertEquals(2., MVEL.eval("2."));
}
public void testNumLiterals7() {
assertEquals(.3, MVEL.eval(".3"));
}
public void testNumLiterals8() {
assertEquals(1e-9d, MVEL.eval("1e-9d"));
}
public void testNumLiterals9() {
assertEquals(0x400921FB54442D18L, MVEL.eval("0x400921FB54442D18L"));
}
public void testArrayCreation2() {
String[][] s = (String[][])
test("new String[][] {{\"2008-04-01\", \"2008-05-10\"}, {\"2007-03-01\", \"2007-02-12\"}}");
assertEquals("2007-03-01", s[1][0]);
}
public void testArrayCreation3() {
OptimizerFactory.setDefaultOptimizer("ASM");
Serializable ce =
MVEL.compileExpression("new String[][] {{\"2008-04-01\", \"2008-05-10\"}, {\"2007-03-01\", \"2007-02-12\"}}");
String[][] s = (String[][])
MVEL.executeExpression(ce);
assertEquals("2007-03-01", s[1][0]);
}
public void testArrayCreation4() {
String[][] s = (String[][])
test("new String[][]{{\"2008-04-01\", \"2008-05-10\"}, {\"2007-03-01\", \"2007-02-12\"}}");
assertEquals("2007-03-01", s[1][0]);
}
public void testNakedMethodCall() {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
OptimizerFactory.setDefaultOptimizer("ASM");
Serializable c = MVEL.compileExpression("tm = System.currentTimeMillis");
assertTrue(((Long) MVEL.executeExpression(c, new HashMap())) > 0);
OptimizerFactory.setDefaultOptimizer("reflective");
assertTrue(((Long) MVEL.executeExpression(c, new HashMap())) > 0);
Map map = new HashMap();
map.put("foo", new Foo());
c = MVEL.compileExpression("foo.happy");
assertEquals("happyBar", MVEL.executeExpression(c, map));
OptimizerFactory.setDefaultOptimizer("ASM");
c = MVEL.compileExpression("foo.happy");
assertEquals("happyBar", MVEL.executeExpression(c, map));
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
}
public void testDecl() {
assertEquals((char) 100, test("char chr; chr = 100; chr"));
}
public void testInlineUnion() {
assertEquals("test", test("{'foo', 'test'}[1]"));
}
public static double minim(double[] tab) {
double min = Float.MAX_VALUE;
for (int i = 0; i < tab.length; i++) {
if (min > tab[i]) {
min = tab[i];
}
}
return min;
}
public void testJIRA113() {
assertEquals(true, test("org.mvel2.tests.core.CoreConfidenceTests.minim( new double[] {456.2, 2.3} ) == 2.3"));
}
public void testSetCoercion() {
Serializable s = compileSetExpression("name");
Foo foo = new Foo();
executeSetExpression(s, foo, 12);
assertEquals("12", foo.getName());
foo = new Foo();
setProperty(foo, "name", 12);
assertEquals("12", foo.getName());
}
public void testSetCoercion2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("sampleBean", SampleBean.class);
Serializable s = compileSetExpression("sampleBean.map2['bleh']", ctx);
Foo foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());
foo = new Foo();
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getSampleBean().getMap2().get("bleh").intValue());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("sampleBean", SampleBean.class);
s = compileSetExpression("sampleBean.map2['bleh']", ctx);
foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());
executeSetExpression(s, foo, new Integer(12));
assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());
}
public void testListCoercion() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
Serializable s = compileSetExpression("bar.testList[0]", ctx);
Foo foo = new Foo();
foo.getBar().getTestList().add(new Integer(-1));
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getTestList().get(0).intValue());
foo = new Foo();
foo.getBar().getTestList().add(new Integer(-1));
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getTestList().get(0).intValue());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
s = compileSetExpression("bar.testList[0]", ctx);
foo = new Foo();
foo.getBar().getTestList().add(new Integer(-1));
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getTestList().get(0).intValue());
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getTestList().get(0).intValue());
}
public void testArrayCoercion1() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
Serializable s = compileSetExpression("bar.intarray[0]", ctx);
Foo foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getIntarray()[0].intValue());
foo = new Foo();
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getIntarray()[0].intValue());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
s = compileSetExpression("bar.intarray[0]", ctx);
foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getIntarray()[0].intValue());
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getIntarray()[0].intValue());
}
public void testFieldCoercion1() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
Serializable s = compileSetExpression("bar.assignTest", ctx);
Foo foo = new Foo();
executeSetExpression(s, foo, 12);
assertEquals("12", foo.getBar().getAssignTest());
foo = new Foo();
executeSetExpression(s, foo, 13);
assertEquals("13", foo.getBar().getAssignTest());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
s = compileSetExpression("bar.assignTest", ctx);
foo = new Foo();
executeSetExpression(s, foo, 12);
assertEquals("12", foo.getBar().getAssignTest());
executeSetExpression(s, foo, 13);
assertEquals("13", foo.getBar().getAssignTest());
}
public void testJIRA115() {
String exp = "results = new java.util.ArrayList(); foreach (element : elements) { if( {1,32769,32767} contains element ) { results.add(element); } }; results";
Map map = new HashMap();
map.put("elements", new int[]{1, 32769, 32767});
ArrayList result = (ArrayList) MVEL.eval(exp, map);
assertEquals(3, result.size());
}
public void testStaticTyping2() {
String exp = "int x = 5; int y = 2; new int[] { x, y }";
Integer[] res = (Integer[]) MVEL.eval(exp, new HashMap());
assertEquals(5, res[0].intValue());
assertEquals(2, res[1].intValue());
}
public void testFunctions5() {
String exp = "def foo(a,b) { a + b }; foo(1.5,5.25)";
System.out.println(MVEL.eval(exp, new HashMap()));
}
public void testChainedMethodCallsWithParams() {
assertEquals(true, test("foo.toUC(\"abcd\").equals(\"ABCD\")"));
}
public void testIsUsedInIf() {
assertEquals(true, test("c = 'str'; if (c is String) { true; } else { false; } "));
}
public void testJIRA122() {
Serializable s = MVEL.compileExpression("java.lang.Character.toLowerCase(name.charAt(0)) == 'a'");
OptimizerFactory.setDefaultOptimizer("ASM");
Map map = new HashMap();
map.put("name", "Adam");
assertEquals(true, MVEL.executeExpression(s, map));
assertEquals(true, MVEL.executeExpression(s, map));
}
public void testJIRA103() {
MvelContext mvelContext = new MvelContext();
MVEL.setProperty(mvelContext, "regkeys", "s");
}
public void testJIRA103b() {
MvelContext mvelContext = new MvelContext();
Map map = new HashMap();
map.put("ctx", mvelContext);
Serializable c = MVEL.compileExpression("ctx.regkeys = 'foo'");
MVEL.executeExpression(c, map);
MVEL.executeExpression(c, map);
}
public void testNewUsingWith() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(Foo.class);
ctx.addImport(Bar.class);
Serializable s = MVEL.compileExpression("[ 'foo' : (with ( new Foo() ) { bar = with ( new Bar() ) { name = 'ziggy' } }) ]", ctx);
OptimizerFactory.setDefaultOptimizer("reflective");
assertEquals("ziggy", (((Foo) ((Map) MVEL.executeExpression(s)).get("foo")).getBar().getName()));
}
private static Map<String, Boolean> JIRA124_CTX = Collections.singletonMap("testValue", true);
public void testJIRA124() throws Exception {
assertEquals("A", testTernary(1, "testValue == true ? 'A' : 'B' + 'C'"));
assertEquals("AB", testTernary(2, "testValue ? 'A' + 'B' : 'C'"));
assertEquals("A", testTernary(3, "(testValue ? 'A' : 'B' + 'C')"));
assertEquals("AB", testTernary(4, "(testValue ? 'A' + 'B' : 'C')"));
assertEquals("A", testTernary(5, "(testValue ? 'A' : ('B' + 'C'))"));
assertEquals("AB", testTernary(6, "(testValue ? ('A' + 'B') : 'C')"));
JIRA124_CTX = Collections.singletonMap("testValue", false);
assertEquals("BC", testTernary(1, "testValue ? 'A' : 'B' + 'C'"));
assertEquals("C", testTernary(2, "testValue ? 'A' + 'B' : 'C'"));
assertEquals("BC", testTernary(3, "(testValue ? 'A' : 'B' + 'C')"));
assertEquals("C", testTernary(4, "(testValue ? 'A' + 'B' : 'C')"));
assertEquals("BC", testTernary(5, "(testValue ? 'A' : ('B' + 'C'))"));
assertEquals("C", testTernary(6, "(testValue ? ('A' + 'B') : 'C')"));
}
private static Object testTernary(int i, String expression) throws Exception {
Object val;
Object val2;
try {
val = MVEL.executeExpression(MVEL.compileExpression(expression), JIRA124_CTX);
}
catch (Exception e) {
System.out.println("FailedCompiled[" + i + "]:" + expression);
throw e;
}
try {
val2 = MVEL.eval(expression, JIRA124_CTX);
}
catch (Exception e) {
System.out.println("FailedEval[" + i + "]:" + expression);
throw e;
}
if (((val == null || val2 == null) && val != val2) || (val != null && !val.equals(val2))) {
throw new AssertionError("results do not match (" + String.valueOf(val) + " != " + String.valueOf(val2) + ")");
}
return val;
}
public void testMethodCaching() {
MVEL.eval("for (pet: getPets()) pet.run();", new PetStore());
}
public static class PetStore {
public List getPets() {
List pets = new ArrayList();
pets.add(new Dog());
pets.add(new Cat());
return pets;
}
}
public static class Pet {
public void run() {
}
}
public static class Dog extends Pet {
@Override
public void run() {
System.out.println("dog is running");
}
}
public static class Cat extends Pet {
@Override
public void run() {
System.out.println("cat is running");
}
}
public void testSetExpressions2() {
Foo foo = new Foo();
Collection col = new ArrayList();
final Serializable fooExpr = compileSetExpression("collectionTest");
executeSetExpression(fooExpr, foo, col);
assertEquals(col, foo.getCollectionTest());
}
public void testRec1() {
tak(24, 16, 8);
}
public int tak(int x, int y, int z) {
System.out.println("x=" + x + "; y=" + y + "; z=" + z);
return y >= x ? z : tak(tak(x-1, y, z), tak(y-1, z, x), tak(z-1, x, y));
}
public void testDhanjiBreak() {
MVEL.eval(
" def tak(x, y, z) { " +
"y >= x ? z : tak(tak(x-1, y, z), tak(y-1, z, x), tak(z-1, x, y))\n " +
" }\n\n" +
"i = 1;\n" +
"while(i-- > 0) {\n" +
" tak(24, 16, 8);\n" +
"}", new HashMap());
}
} |
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.BillingController.IConfiguration;
import net.robotmedia.billing.helper.AbstractBillingObserver;
import net.robotmedia.billing.model.Transaction;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import net.robotmedia.billing.BillingRequest.ResponseCode;
class PaymentWrapper
{
private static final String KEY_TRANSACTIONS_RESTORED = "net.robotmedia.billing.transactionsRestored";
private static String publicKey = "";
private AbstractBillingObserver billingObserver;
private boolean billingSupported = false;
private Set<String> pendingItems = new HashSet<String>();
private Set<String> ownedItems = new HashSet<String>();
public boolean transactionsRestored = false;
public void Init(String publicKey)
{
BillingController.setConfiguration(getConfiguration(publicKey));
billingObserver = getBillingObserver();
BillingController.registerObserver(billingObserver);
BillingController.checkBillingSupported(MonkeyGame.activity);
BillingController.checkSubscriptionSupported(MonkeyGame.activity);
}
public boolean Purchase(String productId) {
pendingItems.add(productId);
BillingController.requestPurchase(MonkeyGame.activity, productId, true, null);
return false;
}
public boolean IsBought(String productId) {
return ownedItems.contains(productId);
}
public boolean IsPurchaseInProgress() {
if (billingSupported && !billingObserver.isTransactionsRestored()) {
return true;
} else {
return !pendingItems.isEmpty();
}
}
private AbstractBillingObserver getBillingObserver()
{
return new AbstractBillingObserver(MonkeyGame.activity) {
public void onBillingChecked(boolean supported) {
PaymentWrapper.this.onBillingChecked(supported);
}
public void onPurchaseStateChanged(String itemId, PurchaseState state) {
PaymentWrapper.this.onPurchaseStateChanged(itemId, state);
}
public void onRequestPurchaseResponse(String itemId, ResponseCode response) {
PaymentWrapper.this.onRequestPurchaseResponse(itemId, response);
}
public void onSubscriptionChecked(boolean supported) {
// Ignored
}
@Override
public boolean isTransactionsRestored() {
return PaymentWrapper.this.transactionsRestored;
}
@Override
public void onTransactionsRestored() {
PaymentWrapper.this.restoreFromLocalTransactions();
PaymentWrapper.this.transactionsRestored = true;
}
};
}
private IConfiguration getConfiguration(String publicKey)
{
PaymentWrapper.publicKey = publicKey;
return new IConfiguration() {
public byte[] getObfuscationSalt() {
return new byte[] {41, -90, -116, -41, 66, -53, 122, -110, -127, -96, -88, 77, 127, 115, 1, 73, 57, 110, 48, -116};
}
public String getPublicKey() {
return PaymentWrapper.publicKey;
}
};
}
public void restoreFromLocalTransactions() {
for (Transaction trans : BillingController.getTransactions(MonkeyGame.activity)) {
onPurchaseStateChanged(trans.productId, trans.purchaseState);
}
}
public void onBillingChecked(boolean supported) {
billingSupported = supported;
if (billingSupported && !billingObserver.isTransactionsRestored()) {
BillingController.restoreTransactions(MonkeyGame.activity);
}
}
public void onPurchaseStateChanged(String itemId, PurchaseState state) {
pendingItems.remove(itemId);
if (state == PurchaseState.PURCHASED) {
ownedItems.add(itemId);
}
if (state == PurchaseState.CANCELLED) {
ownedItems.remove(itemId);
}
}
public void onRequestPurchaseResponse(String itemId, ResponseCode response) {
pendingItems.remove(itemId);
}
protected void finalize() throws Throwable {
BillingController.unregisterObserver(billingObserver);
BillingController.setConfiguration(null);
}
} |
package org.neo4j.gis.spatial.pipes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.NoSuchElementException;
import org.geotools.data.neo4j.Neo4jFeatureBuilder;
import org.geotools.data.neo4j.StyledImageExporter;
import org.geotools.feature.FeatureCollection;
import org.geotools.filter.text.cql2.CQLException;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.crs.DefaultEngineeringCRS;
import org.geotools.styling.Style;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.neo4j.collections.rtree.filter.SearchAll;
import org.neo4j.collections.rtree.filter.SearchFilter;
import org.neo4j.cypher.javacompat.CypherParser;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.examples.AbstractJavaDocTestbase;
import org.neo4j.gis.spatial.Constants;
import org.neo4j.gis.spatial.EditableLayerImpl;
import org.neo4j.gis.spatial.Layer;
import org.neo4j.gis.spatial.SpatialDatabaseService;
import org.neo4j.gis.spatial.filter.SearchIntersectWindow;
import org.neo4j.gis.spatial.osm.OSMImporter;
import org.neo4j.gis.spatial.pipes.osm.OSMGeoPipeline;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.impl.annotations.Documented;
import org.neo4j.test.ImpermanentGraphDatabase;
import org.neo4j.test.TestData.Title;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.util.AffineTransformation;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
public class GeoPipesTest extends AbstractJavaDocTestbase
{
private static Layer osmLayer;
private static EditableLayerImpl boxesLayer;
private static EditableLayerImpl concaveLayer;
private static EditableLayerImpl intersectionLayer;
private static EditableLayerImpl equalLayer;
private static EditableLayerImpl linesLayer;
@Test
public void find_all()
{
int count = 0;
for ( GeoPipeFlow flow : GeoPipeline.start( osmLayer ).createWellKnownText() )
{
count++;
assertEquals( 1, flow.getProperties().size() );
String wkt = (String) flow.getProperties().get( "WellKnownText" );
assertTrue( wkt.indexOf( "LINESTRING" ) == 0 );
}
assertEquals( 2, count );
}
@Test
public void filter_by_osm_attribute()
{
GeoPipeline pipeline = OSMGeoPipeline.startOsm( osmLayer ).osmAttributeFilter(
"name", "Storgatan" ).copyDatabaseRecordProperties();
GeoPipeFlow flow = pipeline.next();
assertFalse( pipeline.hasNext() );
assertEquals( "Storgatan", flow.getProperties().get( "name" ) );
}
@Test
public void filter_by_property()
{
GeoPipeline pipeline = GeoPipeline.start( osmLayer ).copyDatabaseRecordProperties().propertyFilter(
"name", "Storgatan" );
GeoPipeFlow flow = pipeline.next();
assertFalse( pipeline.hasNext() );
assertEquals( "Storgatan", flow.getProperties().get( "name" ) );
}
@Test
public void filter_by_window_intersection()
{
assertEquals(
1,
GeoPipeline.start( osmLayer ).windowIntersectionFilter( 10, 40, 20,
56.0583531 ).count() );
}
@Test
public void filter_by_cql_using_bbox() throws CQLException
{
assertEquals(
1,
GeoPipeline.start( osmLayer ).cqlFilter(
"BBOX(the_geom, 10, 40, 20, 56.0583531)" ).count() );
}
@Test
public void filter_by_cql_using_property() throws CQLException
{
GeoPipeline pipeline = GeoPipeline.start( osmLayer ).cqlFilter(
"name = 'Storgatan'" ).copyDatabaseRecordProperties();
GeoPipeFlow flow = pipeline.next();
assertFalse( pipeline.hasNext() );
assertEquals( "Storgatan", flow.getProperties().get( "name" ) );
}
/**
* Affine Transformation
*
* The ApplyAffineTransformation pipe applies an affine transformation to every geometry.
*
* Example:
*
* @@s_affine_transformation
*
* Output:
*
* @@affine_transformation
*/
@Documented
@Test
public void traslate_geometries()
{
// START SNIPPET: s_affine_transformation
GeoPipeline pipeline = GeoPipeline.start( boxesLayer )
.applyAffineTransform(AffineTransformation.translationInstance( 2, 3 ));
// END SNIPPET: s_affine_transformation
addImageSnippet(boxesLayer, pipeline, getTitle());
GeoPipeline original = GeoPipeline.start( osmLayer ).copyDatabaseRecordProperties().sort(
"name" );
GeoPipeline translated = GeoPipeline.start( osmLayer ).applyAffineTransform(
AffineTransformation.translationInstance( 10, 25 ) ).copyDatabaseRecordProperties().sort(
"name" );
for ( int k = 0; k < 2; k++ )
{
Coordinate[] coords = original.next().getGeometry().getCoordinates();
Coordinate[] newCoords = translated.next().getGeometry().getCoordinates();
assertEquals( coords.length, newCoords.length );
for ( int i = 0; i < coords.length; i++ )
{
assertEquals( coords[i].x + 10, newCoords[i].x, 0 );
assertEquals( coords[i].y + 25, newCoords[i].y, 0 );
}
}
}
@Test
public void calculate_area()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).calculateArea().sort(
"Area" );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
1.0, 0 );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
8.0, 0 );
}
@Test
public void calculate_length()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).calculateLength().sort(
"Length" );
assertEquals( (Double) pipeline.next().getProperties().get( "Length" ),
4.0, 0 );
assertEquals( (Double) pipeline.next().getProperties().get( "Length" ),
12.0, 0 );
}
@Test
public void get_boundary_length()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toBoundary().createWellKnownText().calculateLength().sort(
"Length" );
GeoPipeFlow first = pipeline.next();
GeoPipeFlow second = pipeline.next();
assertEquals( "LINEARRING (12 26, 12 27, 13 27, 13 26, 12 26)",
first.getProperties().get( "WellKnownText" ) );
assertEquals( "LINEARRING (2 3, 2 5, 6 5, 6 3, 2 3)",
second.getProperties().get( "WellKnownText" ) );
assertEquals( (Double) first.getProperties().get( "Length" ), 4.0, 0 );
assertEquals( (Double) second.getProperties().get( "Length" ), 12.0, 0 );
}
/**
* Buffer
*
* The Buffer pipe applies a buffer to geometries.
*
* Example:
*
* @@s_buffer
*
* Output:
*
* @@buffer
*/
@Documented
@Test
public void get_buffer()
{
// START SNIPPET: s_buffer
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toBuffer( 0.5 );
// END SNIPPET: s_buffer
addImageSnippet(boxesLayer, pipeline, getTitle());
pipeline = GeoPipeline.start( boxesLayer ).toBuffer( 0.1 ).createWellKnownText().calculateArea().sort(
"Area" );
assertTrue( ( (Double) pipeline.next().getProperties().get( "Area" ) ) > 1 );
assertTrue( ( (Double) pipeline.next().getProperties().get( "Area" ) ) > 8 );
}
/**
* Centroid
*
* The Centroid pipe calculates geometry centroid.
*
* Example:
*
* @@s_centroid
*
* Output:
*
* @@centroid
*/
@Documented
@Test
public void get_centroid()
{
// START SNIPPET: s_centroid
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toCentroid();
// END SNIPPET: s_centroid
addImageSnippet(boxesLayer, pipeline, getTitle(), Constants.GTYPE_POINT);
pipeline = GeoPipeline.start( boxesLayer ).toCentroid().createWellKnownText().copyDatabaseRecordProperties().sort(
"name" );
assertEquals( "POINT (12.5 26.5)",
pipeline.next().getProperties().get( "WellKnownText" ) );
assertEquals( "POINT (4 4)",
pipeline.next().getProperties().get( "WellKnownText" ) );
}
/**
* Convex Hull
*
* The ConvexHull pipe calculates geometry convex hull.
*
* Example:
*
* @@s_convex_hull
*
* Output:
*
* @@convex_hull
*/
@Documented
@Test
public void get_convex_hull()
{
// START SNIPPET: s_convex_hull
GeoPipeline pipeline = GeoPipeline.start( concaveLayer ).toConvexHull();
// END SNIPPET: s_convex_hull
addImageSnippet(concaveLayer, pipeline, getTitle());
pipeline = GeoPipeline.start( concaveLayer ).toConvexHull().createWellKnownText();
assertEquals( "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))",
pipeline.next().getProperties().get( "WellKnownText" ) );
}
/**
* Densify
*
* The Densify pipe inserts extra vertices along the line segments in the geometry.
* The densified geometry contains no line segment which is longer than the given distance tolerance.
*
* Example:
*
* @@s_densify
*
* Output:
*
* @@densify
*/
@Documented
@Test
public void densify()
{
// START SNIPPET: s_densify
GeoPipeline pipeline = GeoPipeline.start( concaveLayer ).densify( 5 ).extractPoints();
// END SNIPPET: s_densify
addImageSnippet(concaveLayer, pipeline, getTitle(), Constants.GTYPE_POINT);
pipeline = GeoPipeline.start( concaveLayer ).toConvexHull().densify( 10 ).createWellKnownText();
assertEquals(
"POLYGON ((0 0, 0 5, 0 10, 5 10, 10 10, 10 5, 10 0, 5 0, 0 0))",
pipeline.next().getProperties().get( "WellKnownText" ) );
}
@Test
public void json()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).createJson().copyDatabaseRecordProperties().sort(
"name" );
assertEquals(
"{\"type\":\"Polygon\",\"coordinates\":[[[12,26],[12,27],[13,27],[13,26],[12,26]]]}",
pipeline.next().getProperties().get( "GeoJSON" ) );
assertEquals(
"{\"type\":\"Polygon\",\"coordinates\":[[[2,3],[2,5],[6,5],[6,3],[2,3]]]}",
pipeline.next().getProperties().get( "GeoJSON" ) );
}
/**
* Max
*
* The Max pipe computes the maximum value of the specified property and
* discard items with a value less than the maximum.
*
* Example:
*
* @@s_max
*
* Output:
*
* @@max
*/
@Documented
@Test
public void get_max_area()
{
// START SNIPPET: s_max
GeoPipeline pipeline = GeoPipeline.start( boxesLayer )
.calculateArea()
.getMax( "Area" );
// END SNIPPET: s_max
addImageSnippet( boxesLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( boxesLayer ).calculateArea().getMax(
"Area" );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
8.0, 0 );
}
/**
* Boundary
*
* The Boundary pipe calculates boundary of every geometry in the pipeline.
*
* Example:
*
* @@s_boundary
*
* Output:
*
* @@boundary
*/
@Documented
@Test
public void get_boundary()
{
// START SNIPPET: s_boundary
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toBoundary();
// END SNIPPET: s_boundary
addImageSnippet( boxesLayer, pipeline, getTitle(), Constants.GTYPE_LINESTRING );
// TODO test?
}
/**
* Difference
*
* The Difference pipe computes a geometry representing
* the points making up item geometry that do not make up the given geometry.
*
* Example:
*
* @@s_difference
*
* Output:
*
* @@difference
*/
@Documented
@Test
public void difference() throws Exception
{
// START SNIPPET: s_difference
WKTReader reader = new WKTReader( intersectionLayer.getGeometryFactory() );
Geometry geometry = reader.read( "POLYGON ((3 3, 3 5, 7 7, 7 3, 3 3))" );
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).difference( geometry );
// END SNIPPET: s_difference
addImageSnippet( intersectionLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Intersection
*
* The Intersection pipe computes a geometry representing the intersection between item geometry and the given geometry.
*
* Example:
*
* @@s_intersection
*
* Output:
*
* @@intersection
*/
@Documented
@Test
public void intersection() throws Exception
{
// START SNIPPET: s_intersection
WKTReader reader = new WKTReader( intersectionLayer.getGeometryFactory() );
Geometry geometry = reader.read( "POLYGON ((3 3, 3 5, 7 7, 7 3, 3 3))" );
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).intersect( geometry );
// END SNIPPET: s_intersection
addImageSnippet( intersectionLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Union
*
* The Union pipe unites item geometry with a given geometry.
*
* Example:
*
* @@s_union
*
* Output:
*
* @@union
*/
@Documented
@Test
public void union() throws Exception
{
// START SNIPPET: s_union
WKTReader reader = new WKTReader( intersectionLayer.getGeometryFactory() );
Geometry geometry = reader.read( "POLYGON ((3 3, 3 5, 7 7, 7 3, 3 3))" );
SearchFilter filter = new SearchIntersectWindow( intersectionLayer, new Envelope( 7, 10, 7, 10 ) );
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer, filter ).union( geometry );
// END SNIPPET: s_union
addImageSnippet( intersectionLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Min
*
* The Min pipe computes the minimum value of the specified property and
* discard items with a value greater than the minimum.
*
* Example:
*
* @@s_min
*
* Output:
*
* @@min
*/
@Documented
@Test
public void get_min_area()
{
// START SNIPPET: s_min
GeoPipeline pipeline = GeoPipeline.start( boxesLayer )
.calculateArea()
.getMin( "Area" );
// END SNIPPET: s_min
addImageSnippet( boxesLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( boxesLayer ).calculateArea().getMin(
"Area" );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
1.0, 0 );
}
@Test
public void extract_osm_points()
{
int count = 0;
GeoPipeline pipeline = OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().createWellKnownText();
for ( GeoPipeFlow flow : pipeline )
{
count++;
assertEquals( 1, flow.getProperties().size() );
String wkt = (String) flow.getProperties().get( "WellKnownText" );
assertTrue( wkt.indexOf( "POINT" ) == 0 );
}
assertEquals( 24, count );
}
/**
* A more complex Open Street Map example.
*
* This example demostrates the some pipes chained together to make a full
* geoprocessing pipeline.
*
* Example:
*
* @@s_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step1_
*
* @@step1_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step2_
*
* @@step2_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step3_
*
* @@step3_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step4_
*
* @@step4_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step5_
*
* @@step5_break_up_all_geometries_into_points_and_make_density_islands
*/
@Documented
@Title("break_up_all_geometries_into_points_and_make_density_islands")
@Test
public void break_up_all_geometries_into_points_and_make_density_islands_and_get_the_outer_linear_ring_of_the_density_islands_and_buffer_the_geometry_and_count_them()
{
// START SNIPPET: s_break_up_all_geometries_into_points_and_make_density_islands
//step1
GeoPipeline pipeline = OSMGeoPipeline.startOsm( osmLayer )
//step2
.extractOsmPoints()
//step3
.groupByDensityIslands( 0.0005 )
//step4
.toConvexHull()
//step5
.toBuffer( 0.0004 );
// END SNIPPET: s_break_up_all_geometries_into_points_and_make_density_islands
assertEquals( 9, pipeline.count() );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ), "step1_"+getTitle(), Constants.GTYPE_LINESTRING );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints(), "step2_"+getTitle(), Constants.GTYPE_POINT );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().groupByDensityIslands( 0.0005 ), "step3_"+getTitle(), Constants.GTYPE_POLYGON );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().groupByDensityIslands( 0.0005 ).toConvexHull(), "step4_"+getTitle(), Constants.GTYPE_POLYGON );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().groupByDensityIslands( 0.0005 ).toConvexHull().toBuffer( 0.0004 ), "step5_"+getTitle(), Constants.GTYPE_POLYGON );
}
/**
* Extract Points
*
* The Extract Points pipe extracts every point from a geometry.
*
* Example:
*
* @@s_extract_points
*
* Output:
*
* @@extract_points
*/
@Documented
@Test
public void extract_points()
{
// START SNIPPET: s_extract_points
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).extractPoints();
// END SNIPPET: s_extract_points
addImageSnippet(boxesLayer, pipeline, getTitle(), Constants.GTYPE_POINT);
int count = 0;
for ( GeoPipeFlow flow : GeoPipeline.start( boxesLayer ).extractPoints().createWellKnownText() )
{
count++;
assertEquals( 1, flow.getProperties().size() );
String wkt = (String) flow.getProperties().get( "WellKnownText" );
assertTrue( wkt.indexOf( "POINT" ) == 0 );
}
// every rectangle has 5 points, the last point is in the same position of the first
assertEquals( 10, count );
}
@Test
public void filter_by_null_property()
{
assertEquals(
2,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNullFilter(
"address" ).count() );
assertEquals(
0,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNullFilter(
"name" ).count() );
}
@Test
public void filter_by_not_null_property()
{
assertEquals(
0,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNotNullFilter(
"address" ).count() );
assertEquals(
2,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNotNullFilter(
"name" ).count() );
}
@Test
public void compute_distance() throws ParseException
{
WKTReader reader = new WKTReader( boxesLayer.getGeometryFactory() );
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).calculateDistance(
reader.read( "POINT (0 0)" ) ).sort( "Distance" );
assertEquals(
4, Math.round( (Double) pipeline.next().getProperty( "Distance" ) ) );
assertEquals(
29, Math.round( (Double) pipeline.next().getProperty( "Distance" ) ) );
}
/**
* Unite All
*
* The Union All pipe unites geometries of every item contained in the pipeline.
* This pipe groups every item in the pipeline in a single item containing the geometry output
* of the union.
*
* Example:
*
* @@s_unite_all
*
* Output:
*
* @@unite_all
*/
@Documented
@Test
public void unite_all()
{
// START SNIPPET: s_unite_all
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).unionAll();
// END SNIPPET: s_unite_all
addImageSnippet( intersectionLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( intersectionLayer )
.unionAll()
.createWellKnownText();
assertEquals(
"POLYGON ((0 0, 0 5, 2 5, 2 6, 4 6, 4 10, 10 10, 10 4, 6 4, 6 2, 5 2, 5 0, 0 0))",
pipeline.next().getProperty( "WellKnownText" ) );
try
{
pipeline.next();
fail();
}
catch ( NoSuchElementException e )
{
}
}
/**
* Intersect All
*
* The IntersectAll pipe intersects geometries of every item contained in the pipeline.
* It groups every item in the pipeline in a single item containing the geometry output
* of the intersection.
*
* Example:
*
* @@s_intersect_all
*
* Output:
*
* @@intersect_all
*/
@Documented
@Test
public void intersect_all()
{
// START SNIPPET: s_intersect_all
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).intersectAll();
// END SNIPPET: s_intersect_all
addImageSnippet( intersectionLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( intersectionLayer )
.intersectAll()
.createWellKnownText();
assertEquals( "POLYGON ((4 5, 5 5, 5 4, 4 4, 4 5))",
pipeline.next().getProperty( "WellKnownText" ) );
try
{
pipeline.next();
fail();
}
catch ( NoSuchElementException e )
{
}
}
/**
* Intersecting windows
*
* The FilterIntersectWindow pipe finds geometries that intersects a given rectangle.
* This pipeline:
*
* @@s_intersecting_windows
*
* will output:
*
* @@intersecting_windows
*/
@Documented
@Test
public void intersecting_windows()
{
// START SNIPPET: s_intersecting_windows
GeoPipeline pipeline = GeoPipeline
.start( boxesLayer )
.windowIntersectionFilter(new Envelope( 0, 10, 0, 10 ) );
// END SNIPPET: s_intersecting_windows
addImageSnippet( boxesLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Start Point
*
* The StartPoint pipe finds the starting point of item geometry.
* Example:
*
* @@s_start_point
*
* Output:
*
* @@start_point
*/
@Documented
@Test
public void start_point()
{
// START SNIPPET: s_start_point
GeoPipeline pipeline = GeoPipeline
.start( linesLayer )
.toStartPoint();
// END SNIPPET: s_start_point
addImageSnippet( linesLayer, pipeline, getTitle(), Constants.GTYPE_POINT );
pipeline = GeoPipeline
.start( linesLayer )
.toStartPoint()
.createWellKnownText();
assertEquals("POINT (12 26)", pipeline.next().getProperty("WellKnownText"));
}
/**
* End Point
*
* The EndPoint pipe finds the ending point of item geometry.
* Example:
*
* @@s_end_point
*
* Output:
*
* @@end_point
*/
@Documented
@Test
public void end_point()
{
// START SNIPPET: s_end_point
GeoPipeline pipeline = GeoPipeline
.start( linesLayer )
.toEndPoint();
// END SNIPPET: s_end_point
addImageSnippet( linesLayer, pipeline, getTitle(), Constants.GTYPE_POINT );
pipeline = GeoPipeline
.start( linesLayer )
.toEndPoint()
.createWellKnownText();
assertEquals("POINT (23 34)", pipeline.next().getProperty("WellKnownText"));
}
/**
* Envelope
*
* The Envelope pipe computes the minimum bounding box of item geometry.
* Example:
*
* @@s_envelope
*
* Output:
*
* @@envelope
*/
@Documented
@Test
public void envelope()
{
// START SNIPPET: s_envelope
GeoPipeline pipeline = GeoPipeline
.start( linesLayer )
.toEnvelope();
// END SNIPPET: s_envelope
addImageSnippet( linesLayer, pipeline, getTitle(), Constants.GTYPE_POLYGON );
// TODO test
}
@Test
public void test_equality() throws Exception
{
WKTReader reader = new WKTReader( equalLayer.getGeometryFactory() );
Geometry geom = reader.read( "POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))" );
GeoPipeline pipeline = GeoPipeline.startEqualExactSearch( equalLayer,
geom, 0 ).copyDatabaseRecordProperties();
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
pipeline = GeoPipeline.startEqualExactSearch( equalLayer, geom, 0.1 ).copyDatabaseRecordProperties().sort(
"id" );
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertEquals( "tolerance", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
pipeline = GeoPipeline.startIntersectWindowSearch( equalLayer,
geom.getEnvelopeInternal() ).equalNormFilter( geom, 0.1 ).copyDatabaseRecordProperties().sort(
"id" );
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertEquals( "tolerance", pipeline.next().getProperty( "name" ) );
assertEquals( "different order", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
pipeline = GeoPipeline.startIntersectWindowSearch( equalLayer,
geom.getEnvelopeInternal() ).equalTopoFilter( geom ).copyDatabaseRecordProperties().sort(
"id" );
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertEquals( "different order", pipeline.next().getProperty( "name" ) );
assertEquals( "topo equal", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
}
private String getTitle()
{
return gen.get().getTitle().replace( " ", "_" ).toLowerCase();
}
private void addImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName )
{
addImageSnippet( layer, pipeline, imgName, null );
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addOsmImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName,
Integer geomType )
{
addImageSnippet( layer, pipeline, imgName, geomType, 0.002 );
}
private void addImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName,
Integer geomType )
{
addImageSnippet( layer, pipeline, imgName, geomType, 1 );
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName,
Integer geomType,
double boundsDelta )
{
gen.get().addSnippet( imgName, "\nimage::" + imgName + ".png[scaledwidth=\"75%\"]\n" );
try
{
FeatureCollection layerCollection = GeoPipeline.start(layer, new SearchAll()).toFeatureCollection();
FeatureCollection pipelineCollection;
if (geomType == null) {
pipelineCollection = pipeline.toFeatureCollection();
} else {
pipelineCollection = pipeline.toFeatureCollection(
Neo4jFeatureBuilder.getType(layer.getName(), geomType, layer.getCoordinateReferenceSystem(), layer.getExtraPropertyNames()));
}
ReferencedEnvelope bounds = layerCollection.getBounds();
bounds.expandToInclude(pipelineCollection.getBounds());
bounds.expandBy(boundsDelta, boundsDelta);
StyledImageExporter exporter = new StyledImageExporter( db );
exporter.setExportDir( "target/docs/images/" );
exporter.saveImage(
new FeatureCollection[] {
layerCollection,
pipelineCollection,
},
new Style[] {
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN),
StyledImageExporter.createDefaultStyle(Color.RED, Color.ORANGE)
},
new File( imgName + ".png" ),
bounds);
}
catch ( IOException e )
{
e.printStackTrace();
}
}
private static void load() throws Exception
{
SpatialDatabaseService spatialService = new SpatialDatabaseService( db );
loadTestOsmData( "two-street.osm", 100 );
osmLayer = spatialService.getLayer( "two-street.osm" );
Transaction tx = db.beginTx();
try {
boxesLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "boxes" );
boxesLayer.setExtraPropertyNames( new String[] { "name" } );
boxesLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
WKTReader reader = new WKTReader( boxesLayer.getGeometryFactory() );
boxesLayer.add(
reader.read( "POLYGON ((12 26, 12 27, 13 27, 13 26, 12 26))" ),
new String[] { "name" }, new Object[] { "A" } );
boxesLayer.add( reader.read( "POLYGON ((2 3, 2 5, 6 5, 6 3, 2 3))" ),
new String[] { "name" }, new Object[] { "B" } );
concaveLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "concave" );
concaveLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( concaveLayer.getGeometryFactory() );
concaveLayer.add( reader.read( "POLYGON ((0 0, 2 5, 0 10, 10 10, 10 0, 0 0))" ) );
intersectionLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "intersection" );
intersectionLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( intersectionLayer.getGeometryFactory() );
intersectionLayer.add( reader.read( "POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))" ) );
intersectionLayer.add( reader.read( "POLYGON ((4 4, 4 10, 10 10, 10 4, 4 4))" ) );
intersectionLayer.add( reader.read( "POLYGON ((2 2, 2 6, 6 6, 6 2, 2 2))" ) );
equalLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "equal" );
equalLayer.setExtraPropertyNames( new String[] { "id", "name" } );
equalLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( intersectionLayer.getGeometryFactory() );
equalLayer.add( reader.read( "POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))" ),
new String[] { "id", "name" }, new Object[] { 1, "equal" } );
equalLayer.add( reader.read( "POLYGON ((0 0, 0.1 5, 5 5, 5 0, 0 0))" ),
new String[] { "id", "name" }, new Object[] { 2, "tolerance" } );
equalLayer.add( reader.read( "POLYGON ((0 5, 5 5, 5 0, 0 0, 0 5))" ),
new String[] { "id", "name" }, new Object[] { 3,
"different order" } );
equalLayer.add(
reader.read( "POLYGON ((0 0, 0 2, 0 4, 0 5, 5 5, 5 3, 5 2, 5 0, 0 0))" ),
new String[] { "id", "name" }, new Object[] { 4, "topo equal" } );
linesLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "lines" );
linesLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( intersectionLayer.getGeometryFactory() );
linesLayer.add( reader.read( "LINESTRING (12 26, 15 27, 18 32, 20 38, 23 34)" ) );
tx.success();
} finally {
tx.finish();
}
}
private static void loadTestOsmData( String layerName, int commitInterval )
throws Exception
{
String osmPath = "./" + layerName;
System.out.println( "\n=== Loading layer " + layerName + " from "
+ osmPath + " ===" );
OSMImporter importer = new OSMImporter( layerName );
importer.setCharset( Charset.forName( "UTF-8" ) );
importer.importFile( db, osmPath );
importer.reIndex( db, commitInterval );
}
@Before
public void setUp()
{
gen.get().setGraph( db );
parser = new CypherParser();
engine = new ExecutionEngine( db );
try
{
StyledImageExporter exporter = new StyledImageExporter( db );
exporter.setExportDir( "target/docs/images/" );
exporter.saveImage( GeoPipeline.start( intersectionLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"intersectionLayer.png" ) );
exporter.saveImage( GeoPipeline.start( boxesLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"boxesLayer.png" ) );
exporter.saveImage( GeoPipeline.start( concaveLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"concaveLayer.png" ) );
exporter.saveImage( GeoPipeline.start( equalLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"equalLayer.png" ) );
exporter.saveImage( GeoPipeline.start( linesLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"linesLayer.png" ) );
exporter.saveImage( GeoPipeline.start( osmLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"osmLayer.png" ) );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
@After
public void doc()
{
// gen.get().addSnippet( "graph", AsciidocHelper.createGraphViz( imgName , graphdb(), "graph"+getTitle() ) );
gen.get().addSourceSnippets( GeoPipesTest.class, "s_"+getTitle().toLowerCase() );
gen.get().document( "target/docs", "examples" );
}
@BeforeClass
public static void init()
{
db = new ImpermanentGraphDatabase( "target/" + System.currentTimeMillis() );
db.cleanContent( true );
try
{
load();
}
catch ( Exception e )
{
e.printStackTrace();
}
StyledImageExporter exporter = new StyledImageExporter( db );
exporter.setExportDir( "target/docs/images/" );
}
private void print( GeoPipeline pipeline )
{
while ( pipeline.hasNext() )
{
print( pipeline.next() );
}
}
private GeoPipeFlow print( GeoPipeFlow pipeFlow )
{
System.out.println( "GeoPipeFlow:" );
for ( String key : pipeFlow.getProperties().keySet() )
{
System.out.println( key + "=" + pipeFlow.getProperties().get( key ) );
}
System.out.println( "-" );
return pipeFlow;
}
} |
package org.spka.cursus.test;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import eu.lp0.cursus.db.DatabaseSession;
import eu.lp0.cursus.db.data.Event;
import eu.lp0.cursus.db.data.Pilot;
import eu.lp0.cursus.db.data.Race;
import eu.lp0.cursus.db.data.RaceAttendee;
import eu.lp0.cursus.db.data.Series;
public class Series2011DataTests extends AbstractSeries2011 {
@Test
public void checkPilots() throws Exception {
createSeriesData();
db.startSession();
try {
DatabaseSession.begin();
Series series = seriesDAO.find(SERIES_NAME);
Assert.assertEquals(22, series.getPilots().size());
DatabaseSession.commit();
} finally {
db.endSession();
}
}
@Test
public void checkEvent1() throws Exception {
createEvent1Data();
db.startSession();
try {
DatabaseSession.begin();
Series series = seriesDAO.find(SERIES_NAME);
Event event1 = eventDAO.find(series, EVENT1_NAME);
Assert.assertEquals(1, event1.getRaces().size());
DatabaseSession.commit();
} finally {
db.endSession();
}
}
@Test
public void checkRace1() throws Exception {
createRace1Data();
db.startSession();
try {
DatabaseSession.begin();
Series series = seriesDAO.find(SERIES_NAME);
Event event1 = eventDAO.find(series, EVENT1_NAME);
Race race1 = raceDAO.find(event1, RACE1_NAME);
Assert.assertEquals(22, race1.getAttendees().size());
for (Map.Entry<?, ?> entry : race1.getAttendees().entrySet()) {
Assert.assertEquals(Pilot.class, entry.getKey().getClass());
Assert.assertEquals(RaceAttendee.class, entry.getValue().getClass());
}
Assert.assertEquals(RaceAttendee.Type.V_SCORER, race1.getAttendees().get(sco060).getType());
Assert.assertEquals(RaceAttendee.Type.PILOT, race1.getAttendees().get(sco197).getType());
DatabaseSession.commit();
} finally {
db.endSession();
}
}
} |
//@@author A0093896H
package seedu.todo.commons.util;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.todo.commons.exceptions.IllegalValueException;
import seedu.todo.model.task.TaskDate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class DateTimeUtilTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void isValidDateString_test() {
String[] validFormats = {
"8 Oct 2015", "8/12/2014", "8-12-2000",
"2/October/2103", "13 March 2013", "4 May 2013"};
String[] invalidFormats = {"abcd", "adsa"};
for (String validFormat : validFormats) {
assertNotNull(DateTimeUtil.parseDateTimeString(validFormat, TaskDate.TASK_DATE_ON));
}
for (String invalidFormat : invalidFormats) {
assertNull(DateTimeUtil.parseDateTimeString(invalidFormat, TaskDate.TASK_DATE_ON));
}
}
@Test
public void containsDateField_test() {
assertTrue(DateTimeUtil.containsDateField("12/12/1234"));
assertFalse(DateTimeUtil.containsDateField("12"));
assertTrue(DateTimeUtil.containsDateField("12/12/1234 12:30"));
}
@Test
public void containsTimeField_test() {
assertFalse(DateTimeUtil.containsTimeField("12/12/1234"));
assertTrue(DateTimeUtil.containsTimeField("12:30"));
assertTrue(DateTimeUtil.containsTimeField("12"));
assertTrue(DateTimeUtil.containsTimeField("12/12/1234 12:30"));
}
@Test
public void beforeOther_test() throws IllegalValueException {
TaskDate onDate = new TaskDate("today", TaskDate.TASK_DATE_ON);
TaskDate byDate = new TaskDate("six days later", TaskDate.TASK_DATE_BY);
TaskDate onSameDate = new TaskDate("today 0900", TaskDate.TASK_DATE_ON);
TaskDate bySameDate = new TaskDate("today 1900", TaskDate.TASK_DATE_ON);
assertTrue(DateTimeUtil.beforeOther(onDate, byDate));
assertFalse(DateTimeUtil.beforeOther(byDate, onDate));
assertFalse(DateTimeUtil.beforeOther(onDate, onDate));
assertTrue(DateTimeUtil.beforeOther(onSameDate, bySameDate));
assertFalse(DateTimeUtil.beforeOther(bySameDate, onSameDate));
assertFalse(DateTimeUtil.beforeOther(onSameDate, onSameDate));
}
@Test
public void parseDateTimeString_test() {
LocalDateTime ldt = LocalDateTime.of(1996, 1, 1, 20, 34);
LocalDateTime ldtNoTime = LocalDateTime.of(1996, 1, 1, 0, 0);
LocalDateTime ldtNoDate = LocalDateTime.now();
ldtNoDate = ldtNoDate.of(ldtNoDate.getYear(), ldtNoDate.getMonth(), ldtNoDate.getDayOfMonth(), 20, 34);
assertEquals(ldt, DateTimeUtil.parseDateTimeString("1/1/1996 20:34", TaskDate.TASK_DATE_ON));
assertEquals(ldtNoTime, DateTimeUtil.parseDateTimeString("1/1/1996", TaskDate.TASK_DATE_ON));
assertEquals(ldtNoDate, DateTimeUtil.parseDateTimeString("20:34", TaskDate.TASK_DATE_ON));
}
//@@author A0142421X
@Test
public void testPrettyPrintDate_equals() {
LocalDateTime ldt = LocalDateTime.now();
LocalDate date = ldt.toLocalDate();
String expectedPrettyDate = date.format(DateTimeFormatter.ofPattern("dd MMM yyyy"));
assertEquals(DateTimeUtil.prettyPrintDate(date), expectedPrettyDate);
}
@Test
public void testPrettyPrintTime_equals() {
LocalDateTime ldt = LocalDateTime.now();
LocalTime time = ldt.toLocalTime();
String expectedPrettyPrintTime = time.format(DateTimeFormatter.ofPattern("hh:mm a"));
assertEquals(DateTimeUtil.prettyPrintTime(time), expectedPrettyPrintTime);
}
@Test
public void testCombineLocalDateAndTime_time_not_null_equals() {
LocalDateTime ldt = LocalDateTime.now();
LocalDate date = ldt.toLocalDate();
LocalTime time = ldt.toLocalTime();
LocalDateTime expectedCombineLocalDateAndTime = LocalDateTime.of(date, time);
assertEquals(DateTimeUtil.combineLocalDateAndTime(date, time), expectedCombineLocalDateAndTime);
}
@Test
public void testCombineLocalDateAndTime_time_null_equals() {
LocalDateTime ldt = LocalDateTime.now();
LocalDate date = ldt.toLocalDate();
LocalDateTime expectedCombineLocalDateAndTime = LocalDateTime.of(date.getYear(), date.getMonth(), date.getDayOfMonth(), 23, 59);
assertEquals(DateTimeUtil.combineLocalDateAndTime(date, null), expectedCombineLocalDateAndTime);
}
@Test
public void testBeforeOther_onDate_null_true() throws IllegalValueException {
TaskDate byDate = new TaskDate("8-12-2000", "by");
assertTrue(DateTimeUtil.beforeOther(null, byDate));
}
@Test
public void testBeforeOther_byDate_null_true() throws IllegalValueException {
TaskDate onDate = new TaskDate("8-12-2000", "on");
assertTrue(DateTimeUtil.beforeOther(onDate, null));
}
//@@author A0142421X-unused
//@@author
} |
package us.jubat.regression;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import us.jubat.testutil.JubaServer;
import us.jubat.testutil.JubatusClientTest;
public class RegressionClientTest extends JubatusClientTest {
private RegressionClient client;
public RegressionClientTest() {
super(JubaServer.regression);
}
@Before
public void setUp() throws Exception {
server.start(server.getConfigPath());
client = new RegressionClient(server.getHost(), server.getPort(),
TIMEOUT_SEC);
}
@After
public void tearDown() throws Exception {
server.stop();
}
@Test
public void testGet_config() throws IOException {
String config = client.get_config(NAME);
assertThat(formatAsJson(config),
is(formatAsJson(server.getConfigData())));
}
@Test
public void testTrain_and_Estimate() {
Datum datum = new Datum();
List<TupleStringString> string_values = new ArrayList<TupleStringString>();
for (int i = 1; i <= 10; i++) {
TupleStringString string_value = new TupleStringString();
string_value.first = "key/str" + Integer.toString(i);
string_value.second = "val/str" + Integer.toString(i);
string_values.add(string_value);
}
datum.string_values = string_values;
List<TupleStringDouble> num_values = new ArrayList<TupleStringDouble>();
for (int i = 1; i <= 10; i++) {
TupleStringDouble num_value = new TupleStringDouble();
num_value.first = "key/num" + Integer.toString(i);
num_value.second = i;
num_values.add(num_value);
}
datum.num_values = num_values;
TupleFloatDatum train_datum = new TupleFloatDatum();
train_datum.first = 1f;
train_datum.second = datum;
List<TupleFloatDatum> train_data = new ArrayList<TupleFloatDatum>();
train_data.add(train_datum);
for (int i = 1; i <= 100; i++) {
assertThat(client.train(NAME, train_data), is(1));
}
List<Datum> estimate_data = new ArrayList<Datum>();
estimate_data.add(datum);
List<Float> result = client.estimate(NAME, estimate_data);
assertThat(result, is(notNullValue()));
assertThat(result.size(), is(1));
assertThat(result.get(0).doubleValue(), is(closeTo(1.0, 0.00001)));
}
@Test
public void testSave_and_Load() {
String id = "regression.test_java-client.model";
assertThat(client.save(NAME, id), is(true));
assertThat(client.load(NAME, id), is(true));
}
@Test
public void testGet_status() {
Map<String, Map<String, String>> status = client.get_status(NAME);
assertThat(status, is(notNullValue()));
assertThat(status.size(), is(1));
}
@Test
public void testClear() {
Datum datum = new Datum();
List<TupleStringString> string_values = new ArrayList<TupleStringString>();
TupleStringString string_value = new TupleStringString();
string_value.first = "key/str";
string_value.second = "val/str";
string_values.add(string_value);
datum.string_values = string_values;
List<TupleStringDouble> num_values = new ArrayList<TupleStringDouble>();
TupleStringDouble num_value = new TupleStringDouble();
num_value.first = "key/str";
num_value.second = 1;
num_values.add(num_value);
datum.num_values = num_values;
TupleFloatDatum train_datum = new TupleFloatDatum();
train_datum.first = 1f;
train_datum.second = datum;
List<TupleFloatDatum> train_data = new ArrayList<TupleFloatDatum>();
train_data.add(train_datum);
client.train(NAME, train_data);
Map<String, Map<String, String>> before = client.get_status(NAME);
String node_name = (String) before.keySet().iterator().next();
assertThat(before.get(node_name).get("num_classes"), is(not("0")));
assertThat(before.get(node_name).get("num_features"), is(not("0")));
client.clear(NAME);
Map<String, Map<String, String>> after = client.get_status(NAME);
assertThat(after.get(node_name).get("num_classes"), is("0"));
assertThat(after.get(node_name).get("num_features"), is("0"));
}
} |
package projectguru.controllers;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.Duration;
import projectguru.controllers.util.SerbianLocalDateStringConverter;
import projectguru.entities.Document;
import projectguru.entities.DocumentRevision;
import projectguru.entities.Privileges;
import projectguru.entities.Project;
import projectguru.entities.Task;
import projectguru.entities.User;
import projectguru.handlers.LoggedUser;
import projectguru.handlers.ProjectHandler;
import projectguru.handlers.exceptions.EntityDoesNotExistException;
import projectguru.handlers.exceptions.InsuficientPrivilegesException;
import projectguru.handlers.exceptions.StoringException;
import projectguru.tasktree.TaskNode;
import projectguru.tasktree.TaskTree;
import projectguru.utils.FormLoader;
/**
*
* @author ZM
*/
public class TeamOfficeController {
@FXML
private ResourceBundle resources;
@FXML
private Label lblStatusLabel;
@FXML
private URL location;
@FXML
private Label label;
@FXML
private ListView<UserWrapper> listMembers;
@FXML
private ListView<ProjectWrapper> listProjects;
@FXML
private Accordion accProjects;
@FXML
private Accordion accMembers;
@FXML
private AnchorPane rightPane;
@FXML
private AnchorPane leftPane;
@FXML
private TreeTableView<TaskNode> treeTasks;
@FXML
private TreeTableColumn<TaskNode, String> treeColumnTasks;
@FXML
private TreeTableColumn<TaskNode, String> treeColumnDescription;
@FXML
private TreeTableColumn<TaskNode, Double> treeColumnCompleted;
@FXML
private Label lblTime;
@FXML
private AnchorPane anchorHeader;
@FXML
private Button btnAddSubtask;
@FXML
private Button btnAddActivity;
@FXML
private Button btnNewProject;
@FXML
private Button btnAddMember;
@FXML
private Button btnEditProject;
@FXML
private TextField tfSearchProjects;
@FXML
private TextField tfSearchMembers;
@FXML
private Label lblProjectName;
@FXML
private Label lblProjectCompleted;
@FXML
private Label lblStartDate;
@FXML
private TextArea tAreaDescription;
@FXML
private Label lblNumMembers;
@FXML
private Label lblEndDate;
@FXML
private Label lblBudget;
@FXML
private Label lblNumActivities;
@FXML
private Label lblNumTasks;
@FXML
private PieChart chartPie;
@FXML
private ListView<UserWrapper> listChefs;
@FXML
private MenuItem mItemKorisnickiNalozi;
@FXML
private Button btnGetReport;
@FXML
private Button btnDocuments;
@FXML
private Button btnFinances;
@FXML
private Button btnCurrentTask;
@FXML
void btnAddSubtaskPressed(ActionEvent event) {
ProjectWrapper projectItem = listProjects.getSelectionModel().getSelectedItem();
if (projectItem != null) {
TreeItem<TaskNode> taskNode = null;
if (treeTasks.getRoot() == null) {
if (user.getProjectHandler().checkProjectChefPrivileges(projectItem.getProject())) {
try {
FormLoader.loadFormAddTask(projectItem.getProject(), null, user, this, false);
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
FormLoader.showInformationDialog("Обавјештење", "Немате довољно привилегија");
}
} else if ((taskNode = treeTasks.getSelectionModel().getSelectedItem()) != null) {
if (user.getTaskHandler().checkTaskChefPrivileges(taskNode.getValue().getTask())) {
try {
FormLoader.loadFormAddTask(projectItem.getProject(), taskNode.getValue().getTask(), user, this, false);
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
FormLoader.showInformationDialog("Обавјештење", "Немате довољно привилегија");
}
} else {
FormLoader.showInformationDialog("Напомена", "Изаберите задатак за који желите додати подзадатак !");
}
} else {
FormLoader.showInformationDialog("Напомена", "Изаберите пројекат за који желите додати подзадатак !");
}
}
private void actionOnEditTask() {
ProjectWrapper projectItem = listProjects.getSelectionModel().getSelectedItem();
if (projectItem != null) {
TreeItem<TaskNode> taskNode = null;
if (treeTasks.getRoot() == null) {
try {
FormLoader.loadFormAddTask(projectItem.getProject(), null, user, this, true);
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
}
} else if ((taskNode = treeTasks.getSelectionModel().getSelectedItem()) != null) {
try {
FormLoader.loadFormAddTask(projectItem.getProject(), taskNode.getValue().getTask(), user, this, true);
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
FormLoader.showInformationDialog("Напомена", "Изаберите задатак за који желите додати подзадатак !");
}
} else {
FormLoader.showInformationDialog("Напомена", "Изаберите пројекат за који желите додати подзадатак !");
}
}
@FXML
void btnAddMemberPressed(ActionEvent event) {
try {
FormLoader.loadFormAddMembersOnProjects(user,
listProjects.getSelectionModel().getSelectedItem().getProject(),
this
);
} catch (IOException ex) {
ex.printStackTrace();
}
}
@FXML
void btnNewProjectPressed(ActionEvent event) {
try {
FormLoader.loadFormAddProject(user, null);
loadProjects();
} catch (IOException ex) {
ex.printStackTrace();
}
}
@FXML
void btnEditProjectPressed(ActionEvent event) {
ProjectWrapper projectWrapper = listProjects.getSelectionModel().getSelectedItem();
if (projectWrapper != null) {
Project project = projectWrapper.getProject();
try {
FormLoader.loadFormAddProject(user, project);
loadProjects();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
@FXML
void btnAddActivityPressed(ActionEvent event) {
if (treeTasks.getSelectionModel().getSelectedItem() != null) {
TaskNode taskNode = treeTasks.getSelectionModel().getSelectedItem().getValue();
try {
FormLoader.loadFormActivities(user, taskNode.getTask());
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
FormLoader.showInformationDialog("Напомена", "Изаберите задатак не који желите додати активност !");
}
}
@FXML
void btnDocumentsPressed(ActionEvent event) {
ProjectWrapper projectWrapper = listProjects.getSelectionModel().getSelectedItem();
try {
if (projectWrapper != null) {
FormLoader.loadFormDocumentation(projectWrapper.getProject(), user);
}
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
}
}
@FXML
void mItemKorisnickNaloziPressed(ActionEvent event) {
try {
FormLoader.loadFormUserAccounts(user);
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
void mItemClosePressed(ActionEvent event){
((Stage)btnAddActivity.getScene().getWindow()).close();
}
@FXML
void btnGetReportPressed(ActionEvent event) {
try {
ProjectWrapper item = listProjects.getSelectionModel().getSelectedItem();
if (item != null) {
FormLoader.loadFormReport(item.getProject(), user);
} else {
FormLoader.showInformationDialog("Обавјештење", "Изаберите пројекат за који желите генерисати извјештај");
}
} catch (Exception ex) {
FormLoader.showErrorDialog("Грешка у апликацији", "Не може да отвори форму за извјештај");
}
}
@FXML
void btnFinancesPressed(ActionEvent event) {
try {
ProjectWrapper item = listProjects.getSelectionModel().getSelectedItem();
if (item != null) {
FormLoader.loadFormFinancesOverview(item.getProject(), user);
} else {
FormLoader.showInformationDialog("Обавјештење", "Изаберите пројекат за који желите погледати финансије");
}
} catch (Exception ex) {
FormLoader.showErrorDialog("Грешка у апликацији", "Не може да отвори форму за преглед финансија");
}
}
@FXML
void btnCurrentTaskPressed(ActionEvent event) {
if (activeTask == null) {
FormLoader.showInformationDialog("Активни задатак", "Тренутно немате активног задатка !");
} else {
activeTask = user.getTaskHandler().getUpdatedTask(activeTask);
FormLoader.showExtendedInformationDialog("Активни задатак", "Задатак: " + activeTask.getName(), activeTask.getDescription());
}
}
/**
* Moje varijable
*/
private static LoggedUser user;
private ObservableList<ProjectWrapper> projects;
private ObservableList<UserWrapper> members;
private ContextMenu rootContextMenu;
private ContextMenu projectListMenu;
private long time = System.currentTimeMillis();
private Timeline clockTimeline;
private Timeline activeTaskTimeline;
private Task activeTask = null;
//sekunde nakon kojih tajmer vrsi provjeru pozadiniskog zadatka
private long seconds = 60;
private static final ImageView rootImage = new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/root.png")));
public void updateLoggedUser() throws EntityDoesNotExistException {
user.setUser(user.getProjectHandler().getUpdatedUser(user.getUser()));
if (user.getUser().getActivated() == false) {
FormLoader.showExtendedInformationDialog("Обавјештење", null, "Ваш налог је деактивиран.\nКонтактирајте администратора за више информација.");
System.exit(0);
}
setGUIForUser();
}
@FXML
void initialize() {
assert label != null : "fx:id=\"label\" was not injected: check your FXML file 'TeamOffice.fxml'.";
btnAddActivity.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/add_activity.png"))));
btnAddSubtask.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/add_task.png"))));
btnAddMember.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/add_member.png"))));
btnNewProject.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/add_project.png"))));
btnEditProject.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/edit.png"))));
btnDocuments.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/documents.png"))));
btnGetReport.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/report.png"))));
btnFinances.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/finances.png"))));
btnCurrentTask.setGraphic(new ImageView(new Image(TeamOfficeController.class
.getResourceAsStream("/projectguru/images/active_task.png"))));
projectListMenu = new ContextMenu();
final MenuItem refreshProjectList = new MenuItem("Учитај све пројекте");
refreshProjectList.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
loadProjects();
}
});
projectListMenu.getItems().add(refreshProjectList);
listProjects.setContextMenu(projectListMenu);
listProjects.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ProjectWrapper>() {
@Override
public void changed(ObservableValue<? extends ProjectWrapper> observable, ProjectWrapper oldValue, ProjectWrapper newValue) {
if (newValue != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
loadMembers(newValue.getProject());
loadTaskTree(newValue.getProject());
setOverviewTab();
}
});
}
}
});
rootContextMenu = new ContextMenu();
final MenuItem addSubtask = new MenuItem("Додај подзадатак");
final MenuItem addActivity = new MenuItem("Додај активност");
final MenuItem editSubtask = new MenuItem("Прикажи задатак");
final MenuItem activateTask = new MenuItem("Aктивирај задатак");
addSubtask.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
btnAddSubtaskPressed(event);
}
});
editSubtask.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// btnAddSubtaskPressed(event);
actionOnEditTask();
}
});
addActivity.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
btnAddActivityPressed(event);
}
});
activateTask.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
TreeItem<TaskNode> taskNode = treeTasks.getSelectionModel().getSelectedItem();
if (taskNode != null) {
try {
FormLoader.loadFormSetActiveTask(taskNode.getValue().getTask(), user);
} catch (IOException ex) {
Logger.getLogger(TeamOfficeController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
rootContextMenu.getItems().addAll(addSubtask, addActivity, editSubtask, activateTask);
treeColumnTasks.setCellFactory(new Callback<TreeTableColumn<TaskNode, String>, TreeTableCell<TaskNode, String>>() {
@Override
public TreeTableCell<TaskNode, String> call(TreeTableColumn<TaskNode, String> param) {
TreeTableCell<TaskNode, String> cell = new TreeTableCell<TaskNode, String>() {
@Override
protected void updateItem(String t, boolean bln) {
super.updateItem(t, bln);
if (bln) {
setText(null);
setContextMenu(null);
} else if (t != null) {
setText(t);
TaskNode node = this.getTreeTableRow().getItem();
if (node != null && user.getTaskHandler().checkTaskChefPrivileges(node.getTask())) {
setContextMenu(rootContextMenu);
}
}
}
};
return cell;
}
});
treeColumnCompleted.setCellFactory(new Callback<TreeTableColumn<TaskNode, Double>, TreeTableCell<TaskNode, Double>>() {
@Override
public TreeTableCell<TaskNode, Double> call(TreeTableColumn<TaskNode, Double> param) {
TreeTableCell<TaskNode, Double> cell = new TreeTableCell<TaskNode, Double>() {
@Override
protected void updateItem(Double t, boolean bln) {
super.updateItem(t, bln);
if (bln) {
setText(null);
setGraphic(null);
} else if (t != null) {
setAlignment(Pos.CENTER);
setText(String.format("%5.2f", t * 100) + "%");
setGraphic(new ColoredProgressBar(t));
}
}
};
return cell;
}
});
treeColumnTasks.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<TaskNode, String> param)
-> new ReadOnlyStringWrapper(param.getValue().getValue().getTask().getName())
);
treeColumnDescription.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<TaskNode, String> param)
-> new ReadOnlyStringWrapper(param.getValue().getValue().getTask().getDescription().replaceAll("\n", " "))
);
treeColumnCompleted.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<TaskNode, Double> param)
-> new ReadOnlyObjectWrapper<Double>(param.getValue().getValue().getPartDone()));
accProjects.setExpandedPane(accProjects.getPanes().get(0));
accMembers.setExpandedPane(accMembers.getPanes().get(0));
tfSearchProjects.textProperty().addListener(new ChangeListener() {
public void changed(ObservableValue observable, Object oldVal,
Object newVal) {
Platform.runLater(new Runnable() {
@Override
public void run() {
searchProjects((String) oldVal, (String) newVal);
}
});
}
});
tfSearchMembers.textProperty().addListener(new ChangeListener() {
public void changed(ObservableValue observable, Object oldVal,
Object newVal) {
if (listProjects.getSelectionModel().getSelectedItem() != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
searchMembers((String) oldVal, (String) newVal);
}
});
}
}
});
/**
* Dio zaduzen za satnicu
*/
clockTimeline = new Timeline();
clockTimeline.setCycleCount(Timeline.INDEFINITE);
clockTimeline.getKeyFrames().add(
new KeyFrame(Duration.seconds(1),
new EventHandler() {
@Override
public void handle(Event event) {
setTime();
}
}));
activeTaskTimeline = new Timeline();
activeTaskTimeline.setCycleCount(Timeline.INDEFINITE);
activeTaskTimeline.getKeyFrames().add(
new KeyFrame(Duration.seconds(60),
new EventHandler() {
@Override
public void handle(Event event) {
checkActiveTask();
}
}));
}
public void setGUIForUser() {
int privileges = user.getUser().getAppPrivileges();
if(privileges == Privileges.NO_PRIVILEGES.ordinal()){
btnNewProject.setDisable(true);
mItemKorisnickiNalozi.setVisible(false);
}else if(privileges == Privileges.CHEF.ordinal()){
btnNewProject.setDisable(false);
mItemKorisnickiNalozi.setVisible(false);
}else if(privileges == Privileges.ADMIN.ordinal()){
btnNewProject.setDisable(false);
mItemKorisnickiNalozi.setVisible(true);
}
}
public void setUser(LoggedUser user) {
this.user = user;
}
public void load() {
setGUIForUser();
loadProjects();
listProjects.getSelectionModel().select(0);
}
public void loadProjects() {
projects = FXCollections.observableArrayList(
user.getProjectHandler().getAllProjects()
.stream()
.map((pr) -> new ProjectWrapper(pr))
.collect(Collectors.toList())
);
listProjects.setItems(projects);
if(projects.size() > 0){
listProjects.getSelectionModel().select(null);
}
}
public void loadMembers(Project project) {
members = FXCollections.observableArrayList(
user.getProjectHandler().getAllMembers(project)
.stream()
.map((member) -> new UserWrapper(member))
.collect(Collectors.toList()));
listMembers.setItems(members);
}
public void loadTaskTree(Project project) {
Platform.runLater(new Runnable() {
@Override
public void run() {
treeTasks.setRoot(null);
Task rootTask = project.getIDRootTask();
if (rootTask != null) {
TaskTree tree = user.getTaskHandler().getTaskTree(rootTask);
TreeItem<TaskNode> root = new TreeItem<>(tree.getRoot());
root.setExpanded(true);
recursiveTaskTreeLoad(root, tree.getRoot());
treeTasks.setRoot(root);
}
}
});
}
private void recursiveTaskTreeLoad(TreeItem<TaskNode> root, TaskNode task) {
List<TaskNode> children = task.getChildren();
children.stream().forEach((child) -> {
TreeItem<TaskNode> newRoot = new TreeItem<>(child);
root.getChildren().add(newRoot);
recursiveTaskTreeLoad(newRoot, child);
});
}
public void addNodeToTree(Task subtask) {
TreeItem<TaskNode> task = treeTasks.getSelectionModel().getSelectedItem();
TreeItem<TaskNode> node = new TreeItem<>(user.getTaskHandler().getTaskTree(subtask).getRoot());
if (task == null || treeTasks.getRoot() == null) {
treeTasks.setRoot(node);
} else {
task.getChildren().add(node);
}
ProjectWrapper project = listProjects.getSelectionModel().getSelectedItem();
loadProjects();
if (project != null && projects.contains(project)) {
listProjects.getSelectionModel().select(project);
}
}
private void restartClock() {
time = System.currentTimeMillis();
}
private void setTime() {
long ellapsed = System.currentTimeMillis();
ellapsed -= time;
ellapsed /= 1000;
long s = ellapsed % 60;
long m = (ellapsed / 60) % 60;
long h = (ellapsed / (60 * 60)) % 24;
lblTime.setText(String.format("%02d:%02d:%02d", h, m, s));
}
private void setOverviewTab() {
Platform.runLater(new Runnable() {
@Override
public void run() {
ProjectWrapper projectWrapper = listProjects.getSelectionModel().getSelectedItem();
TreeItem<TaskNode> root = treeTasks.getRoot();
if (projectWrapper != null) {
ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
PieChart.Data worked;
PieChart.Data left;
if (root != null) {
chartPie.setTitle(String.format("Укупно одрађено: %5.2f ", (root.getValue().getPartDone() * 100)) + "%");
worked = new PieChart.Data("Одрађено", root.getValue().getPartDone() * 100);
left = new PieChart.Data("Преостало", 100 - (root.getValue().getPartDone() * 100));
} else {
chartPie.setTitle("Укупно одрађено: 0%");
worked = new PieChart.Data("Одрађено", 0);
left = new PieChart.Data("Преостало", 100);
}
pieChartData.add(worked);
pieChartData.add(left);
chartPie.setData(pieChartData);
Project project = projectWrapper.getProject();
lblStatusLabel.setText("Тренутно изабрани пројекат: " + project.getName());
lblProjectName.setText(project.getName());
tAreaDescription.setText(project.getDescription());
LocalDate start = project.getStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
SerbianLocalDateStringConverter cnv = new SerbianLocalDateStringConverter();
lblStartDate.setText(cnv.toString(start));
LocalDate end = project.getEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
lblEndDate.setText(cnv.toString(end));
lblBudget.setText(String.format("%02d", project.getBudget().intValue()));
lblNumTasks.setText((root != null) ? (root.getValue().getTask().getClosureTasksChildren().size() + 1) + "" : "0");
lblNumMembers.setText(project.getWorksOnProjectList().size() + "");
try {
lblNumActivities.setText((root != null) ? (user.getActivityHandler().findActivitiesForTask(root.getValue().getTask(), true, false)).size() + "" : "0");
} catch (InsuficientPrivilegesException ex) {
lblNumActivities.setText("- ");
} catch (StoringException ex) {
lblNumActivities.setText("- ");
}
ObservableList<UserWrapper> userList = FXCollections.observableArrayList(
user.getProjectHandler().getAllChefs(project)
.stream()
.map((member) -> new UserWrapper(member))
.collect(Collectors.toList()));
listChefs.setItems(userList);
ProjectHandler ph = user.getProjectHandler();
if(ph.checkProjectChefPrivileges(project)){
btnAddMember.setDisable(false);
btnAddSubtask.setVisible(true);
btnAddActivity.setVisible(true);
btnEditProject.setVisible(true);
btnFinances.setVisible(true);
btnDocuments.setVisible(true);
btnGetReport.setVisible(true);
lblProjectCompleted.setText("Шеф пројекта");
}else if(ph.checkMemberPrivileges(project)){
btnAddMember.setDisable(true);
btnAddSubtask.setVisible(true);
btnAddActivity.setVisible(true);
btnEditProject.setVisible(false);
btnFinances.setVisible(true);
btnDocuments.setVisible(true);
btnGetReport.setVisible(true);
lblProjectCompleted.setText("Члан пројекта");
}else if(ph.checkInsightPrivileges(project)){
btnAddMember.setDisable(true);
btnAddSubtask.setVisible(false);
btnAddActivity.setVisible(false);
btnEditProject.setVisible(false);
btnFinances.setVisible(true);
btnDocuments.setVisible(true);
btnGetReport.setVisible(true);
lblProjectCompleted.setText("Надзор");
}else if(ph.checkExternPrivileges(project)){
btnAddMember.setDisable(true);
btnAddSubtask.setVisible(false);
btnAddActivity.setVisible(false);
btnEditProject.setVisible(false);
btnFinances.setVisible(false);
btnDocuments.setVisible(true);
btnGetReport.setVisible(true);
lblProjectCompleted.setText("Екстерни члан");
}else {
btnAddMember.setDisable(true);
btnAddSubtask.setVisible(false);
btnAddActivity.setVisible(false);
btnEditProject.setVisible(false);
btnFinances.setVisible(false);
btnGetReport.setVisible(false);
btnDocuments.setVisible(false);
lblProjectCompleted.setText("Немате привилегија");
}
}
}
});
}
private void searchProjects(String oldValue, String newValue) {
if (oldValue != null && (newValue.length() < oldValue.length())) {
listProjects.setItems(projects);
}
if (newValue.length() == 0) {
loadProjects();
return;
}
String value = newValue.toUpperCase();
ObservableList<ProjectWrapper> subentries = FXCollections.observableArrayList();
for (Object entry : listProjects.getItems()) {
ProjectWrapper entryProject = (ProjectWrapper) entry;
if (entryProject.getProject().getName().toUpperCase().startsWith(value)) {
subentries.add(entryProject);
}
}
listProjects.setItems(subentries);
}
private void searchMembers(String oldValue, String newValue) {
if (oldValue != null && (newValue.length() < oldValue.length())) {
listMembers.setItems(members);
}
if (newValue.length() == 0 && listProjects.getSelectionModel().getSelectedItem() != null) {
loadMembers(listProjects.getSelectionModel().getSelectedItem().getProject());
return;
}
String value = newValue.toUpperCase();
ObservableList<UserWrapper> subentries = FXCollections.observableArrayList();
for (Object entry : listMembers.getItems()) {
UserWrapper entryUser = (UserWrapper) entry;
if (entryUser.getUser().getUsername().toUpperCase().startsWith(value)) {
subentries.add(entryUser);
}
}
listMembers.setItems(subentries);
}
/**
* Active task stuff
*/
public void startActiveTask() {
activeTask = user.getTaskHandler().getActiveTask();
if (activeTask == null) {
FormLoader.showExtendedInformationDialog("Обавјештење", " ", "Тренутно немате активни задатак.\n"
+ "Поновна провјера се врши за " + seconds / 60 + " мин.\n"
+ "Уколико добијете задатак почеће вам се рачунати вријеме.\n"
+ "За више информација кликните на дугме за активни задатак.\n");
} else {
clockTimeline.playFromStart();
FormLoader.showExtendedInformationDialog("Обавјештење", " ", "Почео је ваш рад на активном задатку.\n"
+ "За више информација кликните на дугме за активни задатак.\n");
try {
user.getTaskHandler().createNewTimetableEntry(new Date(), new Date());
} catch (StoringException ex) {
FormLoader.showErrorDialog("Грешка", "Грешка приликом уписа нове сатнице у базу.");
}
}
activeTaskTimeline.playFromStart();
}
private void checkActiveTask() {
try {
updateLoggedUser();
} catch (EntityDoesNotExistException ex) {
}
Task check = user.getTaskHandler().getActiveTask();
if (check == null) {
if (activeTask != null) {
activeTask = check;
clockTimeline.stop();
FormLoader.showExtendedInformationDialog("Обавјештење", " ", "Тренутно немате активни задатак.\n"
+ "Поновна провјера се врши за " + seconds / 60 + " мин.\n"
+ "За више информација кликните на дугме за активни задатак.\n");
}
} else {
if (activeTask == null) {
restartClock();
clockTimeline.playFromStart();
FormLoader.showExtendedInformationDialog("Обавјештење", " ", "Почео је ваш рад на активном задатку.\n"
+ "За више информација кликните на дугме за активни задатак.\n");
try {
user.getTaskHandler().createNewTimetableEntry(new Date(), new Date());
} catch (StoringException ex) {
FormLoader.showErrorDialog("Грешка", "Грешка приликом уписа нове сатнице у базу.");
}
} else if (!check.getId().equals(activeTask.getId())) {
restartClock();
clockTimeline.playFromStart();
FormLoader.showExtendedInformationDialog("Обавјештење", " ", "Дошло је до промјене вашег активног задатка.\n"
+ "За више информација кликните на дугме за активни задатак.");
try {
user.getTaskHandler().createNewTimetableEntry(new Date(), new Date());
} catch (StoringException ex) {
FormLoader.showErrorDialog("Грешка", "Грешка приликом уписа нове сатнице у базу.");
}
} else {
try {
user.getTaskHandler().updateActiveTime(new Date());
} catch (StoringException ex) {
FormLoader.showErrorDialog("Грешка", "Грешка приликом продужења сатнице у бази.");
}
}
}
activeTask = check;
}
/**
* Moje private Wrapper klase
*/
private static class ProjectWrapper {
private Project project;
public ProjectWrapper(Project project) {
this.project = project;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
@Override
public String toString() {
return project.getName();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ProjectWrapper other = (ProjectWrapper) obj;
if (!project.getId().equals(other.getProject().getId())) {
return false;
}
return true;
}
}
public static class UserWrapper {
private User user;
public UserWrapper(User user) {
this.user = user;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return user.getUsername();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof UserWrapper)) {
return false;
}
UserWrapper other = (UserWrapper) object;
return user.equals(other.getUser());
}
}
public static class DocumentWrapper {
private Document document;
public DocumentWrapper(Document document) {
this.document = document;
}
public Document getDocument() {
return document;
}
public void setDocument(Document document) {
this.document = document;
}
@Override
public String toString() {
return document.getName();
}
}
public static class DocumentRevisionWrapper {
private DocumentRevision document;
public DocumentRevisionWrapper(DocumentRevision document) {
this.document = document;
}
public DocumentRevision getDocument() {
return document;
}
public void setDocument(DocumentRevision document) {
this.document = document;
}
@Override
public String toString() {
return document.getDatePosted().toString();
}
}
private static class ColoredProgressBar extends ProgressBar {
public ColoredProgressBar(double initValue) {
super(initValue);
String cssClass = "green-bar";
if (initValue < 0.33) {
cssClass = "red-bar";
} else if (initValue >= 0.33 && initValue < 0.66) {
cssClass = "blue-bar";
} else if (initValue >= 0.66 && initValue < 1) {
cssClass = "green-bar";
}
getStyleClass().add(cssClass);
}
}
} |
package uk.ac.ed.inf.Metabolic.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.pathwayeditor.businessobjectsAPI.ILink;
import org.pathwayeditor.businessobjectsAPI.IMapObject;
import org.pathwayeditor.businessobjectsAPI.IRootMapObject;
import org.pathwayeditor.businessobjectsAPI.IShape;
import org.pathwayeditor.businessobjectsAPI.Location;
import org.pathwayeditor.contextadapter.publicapi.IValidationRuleDefinition;
import org.pathwayeditor.contextadapter.toolkit.ndom.GeometryUtils;
import org.pathwayeditor.contextadapter.toolkit.ndom.ModelObject;
import org.pathwayeditor.contextadapter.toolkit.ndom.NdomException;
import uk.ac.ed.inf.Metabolic.ndomAPI.ERelType;
import uk.ac.ed.inf.Metabolic.ndomAPI.IReaction;
public class MetabolicNDOMFactory extends NDOMFactory {
private Map<IShape, MetabolicMolecule> shape2Molecule = new HashMap<IShape, MetabolicMolecule>();
Map<MetabolicReaction, IShape> reaction2Shape = new HashMap<MetabolicReaction, IShape>();
LinkedList<Map<String, MetabolicCompound>> name2Compound = new LinkedList<Map<String, MetabolicCompound>>();
List<ILink> prodLinks;
public MetabolicNDOMFactory(IRootMapObject rmo) {
super(rmo);
}
public MetabolicNDOMFactory() {
super();
}
@Override
protected void semanticValidation() {
checkOrphanCompounds();
checkOrphanReactions();
}
void checkOrphanReactions() {
for (IReaction r : ndom.getReactionList()) {
if ((r.getSubstrateList().size() == 0)) {
IValidationRuleDefinition rd = getReportBuilder()
.getRuleStore().getRuleById(
MetabolicRuleLoader.ORPHAN_PROCESS_ERROR_ID);
IShape el = reaction2Shape.get(r);
getReportBuilder().setRuleFailed(el, rd, "Reaction has no substrates");
}
if ((r.getProductList().size() == 0)) {
IValidationRuleDefinition rd = getReportBuilder()
.getRuleStore().getRuleById(
MetabolicRuleLoader.ORPHAN_PROCESS_ERROR_ID);
IShape el = reaction2Shape.get(r);
getReportBuilder().setRuleFailed(el, rd, "Reaction has no products");
}
}
}
void checkOrphanCompounds() {
// ModelProcessor proc=new ModelProcessor(ndom);
for(Entry<IShape,MetabolicMolecule> e:shape2Molecule.entrySet()){
IShape el=e.getKey();
MetabolicMolecule c=e.getValue();
if((c.getInhibitoryRelationList().size()+c.getActivatoryRelationList().size()+c.getCatalyticRelationList().size()+c.getSinkList().size()+c.getSourceList().size())==0){
IValidationRuleDefinition rd = getReportBuilder()
.getRuleStore().getRuleById(
MetabolicRuleLoader.ORPHAN_COMPOUND_ERROR_ID);
getReportBuilder().setRuleFailed(el, rd, "Reaction has no products");
}
}
}
protected void rmo() {
name2Compound.addFirst(new HashMap<String, MetabolicCompound>());
super.rmo();
name2Compound.removeFirst();
}
void processProdLinks(MetabolicReaction r) {
if (r.isReversible()) {
IShape s = reaction2Shape.get(r);
// Set<ILink> substr = new HashSet<ILink>();
// Set<ILink> prod = new HashSet<ILink>();
Location srcLoc = null;
// double srcAngle;
for (ILink l : prodLinks) {
if (srcLoc == null) {
// first link
srcLoc = GeometryUtils.getSrcLocation(l, s);
substrate(l, r);
} else {
// all consequitive links
Location newLoc = GeometryUtils.getSrcLocation(l, s);
if (GeometryUtils.getAngle(srcLoc, newLoc) > 0) {
substrate(l, r);
} else {
productsIrr(l, r);
}
}
}
}
prodLinks = null;
}
@Override
protected void products(ILink el, MetabolicReaction r) {
if (r.isReversible()) {
prodLinks.add(el);
} else {
productsIrr(el, r);
}
}
private void productsIrr(ILink el, MetabolicReaction r) {
// TODO separate substrates from products
MetabolicRelation rel = production(el);
r.addProduct(rel);
IShape targ = el.getTarget();
MetabolicMolecule mol = shape2Molecule.get(targ);
if (mol == null) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID);
getReportBuilder()
.setRuleFailed(el, rd,
"Molecule in Production relation is not registered in the model");
// error("Molecule in Production relation is not registered in the
// model");
}
try {
mol.addSource(rel);
String vn = rel.getVarName();
String id = mol.getId();
updateKL(r, vn, id);
} catch (NdomException e) {
report(e);
e.printStackTrace();
}
}
void updateKL(MetabolicReaction r, String vn, String id) {
String kineticLaw = r.getKineticLaw();
if (kineticLaw != null) {
kineticLaw = kineticLaw.replaceAll(vn, id);
r.setKineticLaw(kineticLaw);
}
}
@Override
protected void substrate(ILink el, MetabolicReaction r) {
IShape targ =null;
MetabolicRelation rel = null;
if (r.isReversible()){
if( "Consume".equals(el.getObjectType().getTypeName())) {
// error("Consumption link to reversible reaction");
IValidationRuleDefinition rd = getReportBuilder()
.getRuleStore()
.getRuleById(
MetabolicRuleLoader.CONSUMPTION_TO_REVERSIBLE_ERROR_ID);
getReportBuilder().setRuleFailed(el, rd,
"Consumption link to reversible reaction");
return;
}else{
rel = consumptionRev(el);
targ = el.getTarget();
}
}else{
rel = consumption(el);
targ = el.getSource();
}
r.addSubstrate(rel);
MetabolicMolecule mol = shape2Molecule.get(targ);
if (mol == null) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID);
getReportBuilder()
.setRuleFailed(el, rd,
"Molecule in Consumption relation is not registered in the model");
// error("Molecule in Consumption relation is not registered in the
// model");
}
try {
mol.addSink(rel);
String vn = rel.getVarName();
String id = mol.getId();
updateKL(r, vn, id);
} catch (NdomException e) {
report(e);
e.printStackTrace();
}
}
private MetabolicRelation consumptionRev(ILink el) {
MetabolicRelation rel = relation(el, ERelType.Consumption);
rel.setRole(el.getSrcPort().getPropertyByName("ROLE").getValue());
// rel.setStoichiometry(getInt(el.getTargetPort().getPropertyByName(
// "STOICH").getValue(), "Wrong stoichiometry\t"));
setStoichiometry(el, el.getSrcPort(),rel);
return rel;
}
@Override
protected void activate(ILink el, MetabolicReaction r) {
MetabolicRelation rel = activation(el);
if (r == null) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID);
getReportBuilder()
.setRuleFailed(el, rd,
"Reaction for Activation relation is not registered in the model");
// error("Reaction for Activation relation is not registered in the
// model");
}
r.addActivator(rel);
IShape src = el.getSource();
MetabolicMolecule mol = shape2Molecule.get(src);
if (mol == null) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID);
getReportBuilder()
.setRuleFailed(el, rd,
"Molecule for Activation relation is not registered in the model");
}
try {
mol.addActivatoryRelation(rel);
} catch (NdomException e) {
report(e);
e.printStackTrace();
}
}
@Override
protected void inhibit(ILink el, MetabolicReaction r) {
MetabolicRelation rel = inhibition(el);
if (r == null) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID);
getReportBuilder()
.setRuleFailed(el, rd,
"Reaction for Inhibiton relation is not registered in the model");
}
r.addInhibitor(rel);
IShape src = el.getSource();
MetabolicMolecule mol = shape2Molecule.get(src);
if (mol == null) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID);
getReportBuilder()
.setRuleFailed(el, rd,
"Molecule for Inhibiton relation is not registered in the model");
}
try {
mol.addInhibitoryRelation(rel);
} catch (NdomException e) {
report(e);
e.printStackTrace();
}
}
@Override
protected void catalysis(ILink el, MetabolicReaction r) {
MetabolicRelation rel = catalysis(el);
r.addCatalyst(rel);
IShape src = el.getSource();
MetabolicMolecule mol = shape2Molecule.get(src);
if (mol == null) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.NOT_REGISTERED_ERROR_ID);
getReportBuilder()
.setRuleFailed(el, rd,
"Molecule for Catalysis relation is not registered in the model");
}
try {
mol.addCatalyticRelation(rel);
} catch (NdomException e) {
report(e);
e.printStackTrace();
}
}
@Override
protected void macromolecule(MetabolicCompartment comaprtment,
IMapObject mapObject) {
MetabolicMacromolecule m = macromolecule(mapObject);
shape2Molecule.put((IShape) mapObject, m);
comaprtment.addMacromolecule(m);
}
@Override
protected void macromolecule(MetabolicMacromolecule parent,
IMapObject mapObject) {
MetabolicMacromolecule m = macromolecule(mapObject);
shape2Molecule.put((IShape) mapObject, m);
parent.addSubunit(m);
}
@Override
protected void compound(MetabolicMacromolecule m, IMapObject mapObject) {
MetabolicCompound comp = compound(mapObject);
m.addCompound(comp);
shape2Molecule.put((IShape) mapObject, comp);
}
@Override
protected void compound(MetabolicCompartment compartment,
IMapObject mapObject) {
MetabolicCompound comp = compound(mapObject);
if (name2Compound.getFirst().containsKey(comp.getName())) {
MetabolicCompound comp1 = name2Compound.getFirst().get(
comp.getName());
compareCompounds(comp1, comp, compartment, mapObject);
comp = comp1;
} else {
name2Compound.getFirst().put(comp.getName(), comp);
compartment.addCompound(comp);
}
comp.setCloneNumber(comp.getCloneNumber() + 1);
shape2Molecule.put((IShape) mapObject, comp);
}
/**
* Check external references for two compound definitions. Validate that two
* compounds, having the same name have the same set of references to
* external databases.
*
* @param comp1
* reference compound
* @param comp
* compound under creation
*/
private void compareCompounds(MetabolicCompound comp1,
MetabolicCompound comp, ModelObject parent, IMapObject mapObject) {
String name = comp1.getASCIIName();
// TODO replace with rules
if (!comp1.getDescription().equals(comp.getDescription())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name + "has two sets of Descriptions: '"
+ comp1.getDescription() + "' and '"
+ comp.getDescription() + "'");
}
if (!comp1.getDetailedDescription().equals(
comp.getDetailedDescription())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name
+ "has two sets of DetailedDescription: '"
+ comp1.getDetailedDescription() + "' and '"
+ comp.getDetailedDescription() + "'");
}
if (!comp1.getCID().equals(comp.getCID())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name + "has two sets of CID: '"
+ comp1.getCID() + "' and '" + comp.getCID() + "'");
}
if (!comp1.getChEBIId().equals(comp.getChEBIId())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name + "has two sets of ChEBIId: '"
+ comp1.getChEBIId() + "' and '"
+ comp.getChEBIId() + "'");
}
if (!comp1.getInChI().equals(comp.getInChI())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name + "has two sets of InChI: '"
+ comp1.getInChI() + "' and '" + comp.getInChI()
+ "'");
}
if (comp1.getIC() != (comp.getIC())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name + "has two sets of getIC: '"
+ comp1.getIC() + "' and '" + comp.getIC() + "'");
}
if (!comp1.getPubChemId().equals(comp.getPubChemId())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name + "has two sets of PubChemId: '"
+ comp1.getPubChemId() + "' and '"
+ comp.getPubChemId() + "'");
}
if (!comp1.getSmiles().equals(comp.getSmiles())) {
IValidationRuleDefinition rd = getReportBuilder().getRuleStore()
.getRuleById(MetabolicRuleLoader.COMP_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
mapObject,
rd,
"Compound " + name + "has two sets of Smiles: '"
+ comp1.getSmiles() + "' and '" + comp.getSmiles()
+ "'");
}
}
@Override
protected void compartment(MetabolicCompartment parent, IMapObject mapObject) {
MetabolicCompartment compartment = compartment(mapObject);
try {
name2Compound.addFirst(new HashMap<String, MetabolicCompound>());
parent.addChildCompartment(compartment);
List<IMapObject> ch = mapObject.getChildren();
for (IMapObject el : ch) {
String ot = el.getObjectType().getTypeName();
if ("Compartment".equals(ot)) {
compartment(compartment, el);
} else if ("Process".equals(ot)) {
process(compartment, el);
} else if ("Compound".equals(ot)) {
compound(compartment, el);
} else if ("Macromolecule".equals(ot)) {
macromolecule(compartment, el);
}
}
name2Compound.removeFirst();
} catch (NdomException e) {
report(e);
e.printStackTrace();
}
}
@Override
protected void connectivity() {
for (MetabolicReaction r : reaction2Shape.keySet()) {
IShape s = reaction2Shape.get(r);
prodLinks = new ArrayList<ILink>();
Set<ILink> lset = s.getSourceLinks();
if (lset.size() == 0) {
}
for (ILink el : lset) {
String ot = el.getObjectType().getTypeName();
if ("Produce".equals(ot)) {
products(el, r);
}
}
lset = s.getTargetLinks();
int nsubstr = 0;
for (ILink el : lset) {
String ot = el.getObjectType().getTypeName();
if ("Consume".equals(ot)) {
substrate(el, r);
nsubstr++;
} else if ("Activation".equals(ot)) {
activate(el, r);
} else if ("Catalysis".equals(ot)) {
catalysis(el, r);
} else if ("Inhibition".equals(ot)) {
inhibit(el, r);
}
}
if (nsubstr == 0 && !r.isReversible()) {
// TODO replace with rules
IValidationRuleDefinition rd = getReportBuilder()
.getRuleStore().getRuleById(
MetabolicRuleLoader.RE_DEF_ERROR_ID);
getReportBuilder().setRuleFailed(
s,
rd,
"Reaction is not reversible and do not have substrates \t"
+ s.getId());
}
processProdLinks(r);
}
}
@Override
protected void process(ModelObject parent, IMapObject mapObject) {
MetabolicReaction re = process(mapObject);
// checkParameters(re);
ndom.addReaction(re);
reaction2Shape.put(re, (IShape) mapObject);
}
/**
* @deprecated replaced by
* {@link NDOMFactory#setReParam(IMapObject, MetabolicReaction)}
* @param re
* process node;
*/
void checkParameters(MetabolicReaction re) {
// String parameters = re.getParameters();
// //TODO replace with rules
// if(parameters.trim().length()>0 &&
// !parameters.matches("^(\\s*\\w+\\s*=\\s*[0-9eE\\-+.]+\\s*;)+$")){
// // !parameters.matches("^(\\s*\\w+\\s*=\\s*[0-9eE-+.]+\\s*;)+$")){
// error("Invalid parameter definition"+parameters);
}
}
/*
* $Log: MetabolicNDOMFactory.java,v $ Revision 1.8 2008/07/15 11:14:32 smoodie
* Refactored so code compiles with new Toolkit framework.
*
* Revision 1.7 2008/06/24 10:07:40 radams moved rule builder upt oAbstractNDOM
* parsers
*
* Revision 1.6 2008/06/23 14:42:35 radams added report builder to parser
*
* Revision 1.5 2008/06/23 14:22:34 radams added report builder to parser
*
* Revision 1.4 2008/06/20 22:48:19 radams imports
*
* Revision 1.3 2008/06/09 13:26:29 asorokin Bug fixes for SBML export
*
* Revision 1.2 2008/06/02 15:14:31 asorokin KineticLaw parameters parsing and
* validation
*
* Revision 1.1 2008/06/02 10:31:42 asorokin Reference to Service provider from
* all Service interfaces
*
*/ |
package se.chalmers.watchme.database;
import java.util.Calendar;
import java.util.List;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import se.chalmers.watchme.model.Movie;
import se.chalmers.watchme.model.Tag;
public class DatabaseAdapter {
private Uri uri_movies = WatchMeContentProvider.CONTENT_URI_MOVIES;
private Uri uri_tags = WatchMeContentProvider.CONTENT_URI_TAGS;
private Uri uri_has_tags = WatchMeContentProvider.CONTENT_URI_HAS_TAG;
private ContentResolver contentResolver;
public DatabaseAdapter(ContentResolver contentResolver) {
this.contentResolver = contentResolver;
}
/**
* Returns the specified Movie.
*
* @param id The id of the Movie.
* @return null if there is no Movie with the specified id..
*/
public Movie getMovie(long id) {
String selection = MoviesTable.COLUMN_MOVIE_ID + " = " + id;
Cursor cursor = contentResolver.query(uri_movies, null, selection, null, null);
if(cursor.moveToFirst()) {
String title = cursor.getString(1);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(cursor.getString(4)));
int rating = Integer.parseInt(cursor.getString(2));
String note = cursor.getString(3);
Movie movie = new Movie(title, calendar, rating, note);
movie.setId(id);
movie.setApiID(Integer.parseInt(cursor.getString(5)));
return movie;
}
return null;
}
/**
* Inserts a Movie to the database.
*
* @param movie Movie to be inserted.
* @return the id of the added Movie.
*/
public int addMovie(Movie movie) {
ContentValues values = new ContentValues();
values.put(MoviesTable.COLUMN_TITLE, movie.getTitle());
values.put(MoviesTable.COLUMN_RATING, movie.getRating());
values.put(MoviesTable.COLUMN_NOTE, movie.getNote());
values.put(MoviesTable.COLUMN_DATE, movie.getDate().getTimeInMillis());
values.put(MoviesTable.COLUMN_IMDB_ID, movie.getApiID());
Uri uri_movie_id = contentResolver.insert(uri_movies, values);
return Integer.parseInt(uri_movie_id.getLastPathSegment());
}
/**
* Delete a Movie from the database.
*
* @param movie The movie to be removed.
*/
public void removeMovie(Movie movie) {
String where = MoviesTable.COLUMN_MOVIE_ID + " = " + movie.getId();
contentResolver.delete(uri_movies, where, null);
}
/**
* Return all Movies from the database.
* @return all Movies from the database.
*/
public List<Movie> getAllMovies() {
return null;
}
/**
* Returns the specified Tag.
*
* @param id The id of the Tag.
* @return null if there is no Tag with the specified id.
*/
public Tag getTag(long id) {
String selection = TagsTable.COLUMN_TAG_ID + " = " + id;
Cursor cursor = contentResolver.query(uri_tags, null, selection, null, null);
if(cursor.moveToFirst()) {
String name = cursor.getString(1);
Tag tag = new Tag(name);
tag.setId(id);
return tag;
}
return null;
}
/**
* Inserts a Tag to the database.
*
* @param tag The Tag to be inserted.
* @return the id of the added Tag.
*/
private int addTag(Tag tag) {
ContentValues values = new ContentValues();
values.put(TagsTable.COLUMN_NAME, tag.getName());
Uri uri_tag_id = contentResolver.insert(uri_tags, values);
return Integer.parseInt(uri_tag_id.getLastPathSegment());
}
/**
* Deletes a Tag from the database.
* @param tag The Tag to be removed.
*/
public void removeTag(Tag tag) {
String where = TagsTable.COLUMN_TAG_ID + " = " + tag.getId();
contentResolver.delete(uri_tags, where, null);
}
/**
* Return all Tags in the database.
* @return all Tags in the database.
*/
public List<Tag> getAllTags() {
return null;
}
/**
* Return all Tags attached to a Movie.
*
* @param movie The Movie.
* @return all Tags attached to the Movie.
*/
public List<Tag> getAttachedTags(Movie movie) {
return null;
}
/**
* Return all Movies attached to a Tag.
* @param tag The tag.
* @return all Movies attached to the Tag.
*/
public List<Movie> getAttachedMovies(Tag tag) {
return null;
}
} |
//Contributor: HC,JZ
package team.sprocket.commands.shooter;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class ShootSequence extends CommandGroup {
public ShootSequence() {
addSequential(new Shoot());
addSequential(new Cock());
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
}
} |
package de.gmcs.builder;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import de.gmcs.builder.model.DomainObject;
import de.gmcs.builder.model.PrivateObject;
public class GenericBuilderTest {
@Test
public void testAll() throws Exception {
DomainObject result = GenericBuilder.getInstance(DomainObject.class)
.set("attribute", "attributeValue")
.set("unsettableAttribute", "unsettableAttributeValue")
.invoke("setProperty", "property", Integer.valueOf(3))
.invoke("perform")
.build();
assertThat(result.getAttribute(), is("attributeValue"));
assertThat(result.getUnsettableAttribute(), is("unsettableAttributeValue"));
assertThat(result.getProperty("property"), is(3));
assertThat(result.getPerformCounter(), is(1));
}
@Test
public void testParametrizedConstructor() throws Exception {
DomainObject result = GenericBuilder.getInstance(DomainObject.class, "attributeValue")
.invoke("setProperty", "property", Integer.valueOf(3))
.build();
assertThat(result.getAttribute(), is("attributeValue"));
assertThat(result.getProperty("property"), is(3));
}
@Test
public void testFactoryMethod() throws Exception {
PrivateObject result = GenericBuilder.getInstanceFromFactoryMethod(PrivateObject.class, "getInstance")
.invoke("setAttribute", "attribute")
.build();
assertThat(result.getAttribute(), is("attribute"));
}
@Test
public void testFactoryMethodWithArgs() throws Exception {
PrivateObject result = GenericBuilder.getInstanceFromFactoryMethod(PrivateObject.class, "getInstance", "attribute")
.build();
assertThat(result.getAttribute(), is("attribute"));
}
@Test(expected = GenericBuilderException.class)
public void testMissingSetterMethod() throws Exception {
GenericBuilder.getInstance(DomainObject.class)
.set("missing", "attributeValue");
}
@Test(expected = GenericBuilderException.class)
public void testMissingFactoryMethod() throws Exception {
GenericBuilder.getInstanceFromFactoryMethod(PrivateObject.class, "getInstanceMissing");
}
@Test(expected = GenericBuilderException.class)
public void testMissingMethod() throws Exception {
GenericBuilder.getInstance(DomainObject.class)
.invoke("setMissing", "attributeValue")
.build();
}
@Test(expected = GenericBuilderException.class)
public void testPrivateConstructor() throws Exception {
GenericBuilder.getInstance(PrivateObject.class);
}
} |
package io.scif.services;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import io.scif.FormatException;
import java.math.BigInteger;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.thread.ThreadService;
/**
* Tests {@link FormatService}.
*
* @author Curtis Rueden
*/
public class FormatServiceTest {
private FormatService formatService;
@Before
public void setUp() {
final Context context = new Context(FormatService.class);
formatService = context.getService(FormatService.class);
}
@After
public void tearDown() {
formatService.getContext().dispose();
}
/** Tests {@link FormatService#getSuffixes()}. */
@Test
public void testGetSuffixes() {
final String[] suffixes = formatService.getSuffixes();
final String[] expectedSuffixes = { "avi", "bmp", "btf", "csv", "dcm",
"dic", "dicom", "eps", "epsi", "fake", "fits", "fts", "gif", "ics", "ids",
"ima", "img", "isq", "j2k", "j2ki", "j2kr", "java", "jp2", "jpe", "jpeg",
"jpf", "jpg", "mng", "mov", "msr", "nhdr", "nrrd", "obf", "pct", "pcx",
"pgm", "pict", "png", "ps", "raw", "tf2", "tf8", "tif", "tiff", "txt",
"xml", "zip" };
assertArrayEquals(expectedSuffixes, suffixes);
}
/**
* Test simultaneous format caching on multiple threads.
* <p>
* NB: not annotated as a unit test due to length of execution.
* </p>
*/
// @Test
public void testMultiThreaded() throws InterruptedException {
final ThreadService ts = formatService.getContext().service(
ThreadService.class);
final Random random = new Random();
final long baseTime = System.currentTimeMillis();
final int threads = 500;
final int[] count = new int[1];
final Runnable runnable = () -> {
final long time = System.currentTimeMillis();
while (System.currentTimeMillis() - time < 10000) {
final String s = new BigInteger(64, random).toString() + ".tif";
try {
formatService.getFormat(s);
}
catch (FormatException exc) {
return;
}
}
synchronized (count) {
count[0]++;
}
};
for (int i = 0; i < threads; i++) {
ts.run(runnable);
}
while (System.currentTimeMillis() - baseTime < 30000) {
Thread.sleep(100);
}
assertEquals(threads, count[0]);
}
} |
package me.moodcat.eemcsdata;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import me.moodcat.database.embeddables.AcousticBrainzData;
import me.moodcat.eemcsdata.parser.ParseData;
import org.junit.Before;
import org.junit.Test;
public class ParseDataTest {
ParseData data;
@Before
public void before() {
data = new ParseData();
}
@Test
public void testReadFileLocal() throws IOException {
AcousticBrainzData result = data.parseFileAsLocal(
"src/test/resources/acousticbrainz/testData/folderTest/100019264.txt",
"src/test/resources/acousticbrainz/testData/100019264.json");
assertEquals("F", result.getTonal().getKeyKey());
assertEquals("minor", result.getTonal().getKeyScale());
assertEquals(0.523020684719, result.getTonal().getKeyStrength(), 1e-4);
assertEquals(434.193115234, result.getTonal().getTuningFrequency(), 1e-4);
assertEquals(0.478912621737, result.getLowlevel().getDissonance().getMean(), 1e-4);
assertEquals(0.708070397377, result.getLowlevel().getAverageLoudness(), 1e-4);
assertEquals(120.082946777, result.getRhythm().getBpm(), 1e-4);
}
@Test
public void testReadFolderLocal() throws IOException {
data.parseFolder("src/test/resources/acousticbrainz/testData/folderTest/",
"src/test/resources/acousticbrainz/result/");
AcousticBrainzData result = data.getResult();
assertEquals("F", result.getTonal().getKeyKey());
assertEquals("minor", result.getTonal().getKeyScale());
assertEquals(0.523020684719, result.getTonal().getKeyStrength(), 1e-4);
assertEquals(434.193115234, result.getTonal().getTuningFrequency(), 1e-4);
assertEquals(0.478912621737, result.getLowlevel().getDissonance().getMean(), 1e-4);
assertEquals(0.708070397377, result.getLowlevel().getAverageLoudness(), 1e-4);
assertEquals(120.082946777, result.getRhythm().getBpm(), 1e-4);
}
@Test(expected = IOException.class)
public void testReadNotExsitsingFileLocal() throws IOException {
data.parseFileAsLocal(
"src/test/resources/acousticbrainz/testData/folderTest/nonExcisting.txt",
"src/test/resources/acousticbrainz/testData/nonExcisting.json");
}
@Test(expected = IOException.class)
public void testReadNotExsitsingFolderLocal() throws IOException {
data.parseFolder("src/test/resources/acousticbrainz/unknown/",
"src/test/resources/acousticbrainz/result/");
}
@Test
public void testReadFileResource() throws IOException {
AcousticBrainzData result = data.parseFileAsResource(
"/acousticbrainz/testData/folderTest/100019264.txt",
"src/test/resources/acousticbrainz/result/100019264.json");
assertEquals("F", result.getTonal().getKeyKey());
assertEquals("minor", result.getTonal().getKeyScale());
assertEquals(0.523020684719, result.getTonal().getKeyStrength(), 1e-4);
assertEquals(434.193115234, result.getTonal().getTuningFrequency(), 1e-4);
assertEquals(0.478912621737, result.getLowlevel().getDissonance().getMean(), 1e-4);
assertEquals(0.708070397377, result.getLowlevel().getAverageLoudness(), 1e-4);
assertEquals(120.082946777, result.getRhythm().getBpm(), 1e-4);
}
@Test(expected = IOException.class)
public void testReadNotExsitsingFileResource() throws IOException {
data.parseFileAsLocal(
"/acousticbrainz/testData/folderTest/nonExcisting.txt",
"src/test/resources/acousticbrainz/result/nonExcisting.json");
}
} |
package mho.wheels.math;
import mho.wheels.io.Readers;
import mho.wheels.numberUtils.FloatingPointUtils;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import static mho.wheels.iterables.IterableUtils.iterate;
import static mho.wheels.iterables.IterableUtils.take;
import static mho.wheels.iterables.IterableUtils.toList;
import static mho.wheels.math.BinaryFraction.*;
import static mho.wheels.math.BinaryFraction.sum;
import static mho.wheels.testing.Testing.*;
import static org.junit.Assert.fail;
public strictfp class BinaryFractionTest {
private static void constant_helper(@NotNull BinaryFraction input, @NotNull String output) {
input.validate();
aeq(input, output);
}
@Test
public void testConstants() {
constant_helper(ZERO, "0");
constant_helper(ONE, "1");
constant_helper(SMALLEST_FLOAT, "1 >> 149");
constant_helper(LARGEST_SUBNORMAL_FLOAT, "8388607 >> 149");
constant_helper(SMALLEST_NORMAL_FLOAT, "1 >> 126");
constant_helper(LARGEST_FLOAT, "16777215 << 104");
constant_helper(SMALLEST_DOUBLE, "1 >> 1074");
constant_helper(LARGEST_SUBNORMAL_DOUBLE, "4503599627370495 >> 1074");
constant_helper(SMALLEST_NORMAL_DOUBLE, "1 >> 1022");
constant_helper(LARGEST_DOUBLE, "9007199254740991 << 971");
}
private static void getMantissa_helper(@NotNull String x, int output) {
aeq(readStrict(x).get().getMantissa(), output);
}
@Test
public void testGetMantissa() {
getMantissa_helper("0", 0);
getMantissa_helper("1", 1);
getMantissa_helper("11", 11);
getMantissa_helper("5 << 20", 5);
getMantissa_helper("5 >> 20", 5);
getMantissa_helper("-1", -1);
getMantissa_helper("-11", -11);
getMantissa_helper("-5 << 20", -5);
getMantissa_helper("-5 >> 20", -5);
}
private static void getExponent_helper(@NotNull String x, int output) {
aeq(readStrict(x).get().getExponent(), output);
}
@Test
public void testGetExponent() {
getExponent_helper("0", 0);
getExponent_helper("1", 0);
getExponent_helper("11", 0);
getExponent_helper("5 << 20", 20);
getExponent_helper("5 >> 20", -20);
getExponent_helper("-1", 0);
getExponent_helper("-11", 0);
getExponent_helper("-5 << 20", 20);
getExponent_helper("-5 >> 20", -20);
}
private static void of_BigInteger_int_helper(@NotNull String mantissa, int exponent, @NotNull String output) {
BinaryFraction bf = of(Readers.readBigIntegerStrict(mantissa).get(), exponent);
bf.validate();
aeq(bf, output);
}
private static void of_BigInteger_int_fail_helper(@NotNull String mantissa, int exponent) {
try {
of(Readers.readBigIntegerStrict(mantissa).get(), exponent);
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testOf_BigInteger_int() {
of_BigInteger_int_helper("0", 0, "0");
of_BigInteger_int_helper("0", 1, "0");
of_BigInteger_int_helper("0", -3, "0");
of_BigInteger_int_helper("1", 0, "1");
of_BigInteger_int_helper("2", 0, "1 << 1");
of_BigInteger_int_helper("1", 1, "1 << 1");
of_BigInteger_int_helper("5", 20, "5 << 20");
of_BigInteger_int_helper("5", -20, "5 >> 20");
of_BigInteger_int_helper("100", 0, "25 << 2");
of_BigInteger_int_helper("-1", 0, "-1");
of_BigInteger_int_helper("-2", 0, "-1 << 1");
of_BigInteger_int_helper("-1", 1, "-1 << 1");
of_BigInteger_int_helper("-5", 20, "-5 << 20");
of_BigInteger_int_helper("-5", -20, "-5 >> 20");
of_BigInteger_int_helper("-100", 0, "-25 << 2");
of_BigInteger_int_helper("1", Integer.MAX_VALUE, "1 << 2147483647");
of_BigInteger_int_helper("1", Integer.MIN_VALUE, "1 >> 2147483648");
of_BigInteger_int_fail_helper("4", Integer.MAX_VALUE);
}
private static void of_BigInteger_helper(int n, @NotNull String output) {
BinaryFraction bf = of(BigInteger.valueOf(n));
bf.validate();
aeq(bf, output);
}
@Test
public void testOf_BigInteger() {
of_BigInteger_helper(0, "0");
of_BigInteger_helper(1, "1");
of_BigInteger_helper(5, "5");
of_BigInteger_helper(100, "25 << 2");
of_BigInteger_helper(-1, "-1");
of_BigInteger_helper(-5, "-5");
of_BigInteger_helper(-100, "-25 << 2");
}
private static void of_int_helper(int n, @NotNull String output) {
BinaryFraction bf = of(n);
bf.validate();
aeq(bf, output);
}
@Test
public void testOf_int() {
of_int_helper(0, "0");
of_int_helper(1, "1");
of_int_helper(5, "5");
of_int_helper(100, "25 << 2");
of_int_helper(-1, "-1");
of_int_helper(-5, "-5");
of_int_helper(-100, "-25 << 2");
}
private static void of_float_helper(float f, @NotNull String output) {
Optional<BinaryFraction> bf = of(f);
if (bf.isPresent()) {
bf.get().validate();
}
aeq(bf, output);
}
@Test
public void testOf_float() {
of_float_helper(0.0f, "Optional[0]");
of_float_helper(1.0f, "Optional[1]");
of_float_helper(0.5f, "Optional[1 >> 1]");
of_float_helper(0.25f, "Optional[1 >> 2]");
of_float_helper(1.0f / 3.0f, "Optional[11184811 >> 25]");
of_float_helper(2.0f, "Optional[1 << 1]");
of_float_helper(4.0f, "Optional[1 << 2]");
of_float_helper(3.0f, "Optional[3]");
of_float_helper(1.5f, "Optional[3 >> 1]");
of_float_helper(1000.0f, "Optional[125 << 3]");
of_float_helper(0.001f, "Optional[8589935 >> 33]");
of_float_helper((float) Math.PI, "Optional[13176795 >> 22]");
of_float_helper((float) Math.E, "Optional[2850325 >> 20]");
of_float_helper(Float.MIN_VALUE, "Optional[1 >> 149]");
of_float_helper(Float.MIN_NORMAL, "Optional[1 >> 126]");
of_float_helper(Float.MAX_VALUE, "Optional[16777215 << 104]");
of_float_helper(-0.0f, "Optional[0]");
of_float_helper(-1.0f, "Optional[-1]");
of_float_helper(-0.5f, "Optional[-1 >> 1]");
of_float_helper(-0.25f, "Optional[-1 >> 2]");
of_float_helper(-1.0f / 3.0f, "Optional[-11184811 >> 25]");
of_float_helper(-2.0f, "Optional[-1 << 1]");
of_float_helper(-4.0f, "Optional[-1 << 2]");
of_float_helper(-3.0f, "Optional[-3]");
of_float_helper(-1.5f, "Optional[-3 >> 1]");
of_float_helper(-1000.0f, "Optional[-125 << 3]");
of_float_helper(-0.001f, "Optional[-8589935 >> 33]");
of_float_helper((float) -Math.PI, "Optional[-13176795 >> 22]");
of_float_helper((float) -Math.E, "Optional[-2850325 >> 20]");
of_float_helper(-Float.MIN_VALUE, "Optional[-1 >> 149]");
of_float_helper(-Float.MIN_NORMAL, "Optional[-1 >> 126]");
of_float_helper(-Float.MAX_VALUE, "Optional[-16777215 << 104]");
of_float_helper(Float.POSITIVE_INFINITY, "Optional.empty");
of_float_helper(Float.NEGATIVE_INFINITY, "Optional.empty");
of_float_helper(Float.NaN, "Optional.empty");
}
private static void of_double_helper(double d, @NotNull String output) {
Optional<BinaryFraction> bf = of(d);
if (bf.isPresent()) {
bf.get().validate();
}
aeq(bf, output);
}
@Test
public void testOfMantissaAndExponent_double() {
of_double_helper(0.0, "Optional[0]");
of_double_helper(1.0, "Optional[1]");
of_double_helper(0.5, "Optional[1 >> 1]");
of_double_helper(0.25, "Optional[1 >> 2]");
of_double_helper(1.0 / 3.0, "Optional[6004799503160661 >> 54]");
of_double_helper(2.0, "Optional[1 << 1]");
of_double_helper(4.0, "Optional[1 << 2]");
of_double_helper(3.0, "Optional[3]");
of_double_helper(1.5, "Optional[3 >> 1]");
of_double_helper(1000.0, "Optional[125 << 3]");
of_double_helper(0.001, "Optional[1152921504606847 >> 60]");
of_double_helper(Math.PI, "Optional[884279719003555 >> 48]");
of_double_helper(Math.E, "Optional[6121026514868073 >> 51]");
of_double_helper(Double.MIN_VALUE, "Optional[1 >> 1074]");
of_double_helper(Double.MIN_NORMAL, "Optional[1 >> 1022]");
of_double_helper(Double.MAX_VALUE, "Optional[9007199254740991 << 971]");
of_double_helper(-0.0, "Optional[0]");
of_double_helper(-1.0, "Optional[-1]");
of_double_helper(-0.5, "Optional[-1 >> 1]");
of_double_helper(-0.25, "Optional[-1 >> 2]");
of_double_helper(-1.0 / 3.0, "Optional[-6004799503160661 >> 54]");
of_double_helper(-2.0, "Optional[-1 << 1]");
of_double_helper(-4.0, "Optional[-1 << 2]");
of_double_helper(-3.0, "Optional[-3]");
of_double_helper(-1.5, "Optional[-3 >> 1]");
of_double_helper(-1000.0, "Optional[-125 << 3]");
of_double_helper(-0.001, "Optional[-1152921504606847 >> 60]");
of_double_helper(-Math.PI, "Optional[-884279719003555 >> 48]");
of_double_helper(-Math.E, "Optional[-6121026514868073 >> 51]");
of_double_helper(-Double.MIN_VALUE, "Optional[-1 >> 1074]");
of_double_helper(-Double.MIN_NORMAL, "Optional[-1 >> 1022]");
of_double_helper(-Double.MAX_VALUE, "Optional[-9007199254740991 << 971]");
of_double_helper(Double.POSITIVE_INFINITY, "Optional.empty");
of_double_helper(Double.NEGATIVE_INFINITY, "Optional.empty");
of_double_helper(Double.NaN, "Optional.empty");
}
private static void bigIntegerValueExact_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().bigIntegerValueExact(), output);
}
private static void bigIntegerValueExact_fail_helper(@NotNull String input) {
try {
readStrict(input).get().bigIntegerValueExact();
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testBigIntegerValueExact() {
bigIntegerValueExact_helper("0", "0");
bigIntegerValueExact_helper("1", "1");
bigIntegerValueExact_helper("11", "11");
bigIntegerValueExact_helper("5 << 20", "5242880");
bigIntegerValueExact_helper("-1", "-1");
bigIntegerValueExact_helper("-11", "-11");
bigIntegerValueExact_helper("-5 << 20", "-5242880");
bigIntegerValueExact_fail_helper("5 >> 20");
bigIntegerValueExact_fail_helper("-5 >> 20");
}
private static void bigDecimalValue_helper(@NotNull BinaryFraction input, @NotNull String output) {
aeq(input.bigDecimalValue(), output);
}
private static void bigDecimalValue_helper(@NotNull String input, @NotNull String output) {
bigDecimalValue_helper(readStrict(input).get(), output);
}
@Test
public void testBigDecimalValue() {
bigDecimalValue_helper("0", "0");
bigDecimalValue_helper("1", "1");
bigDecimalValue_helper("11", "11");
bigDecimalValue_helper("5 << 20", "5242880");
bigDecimalValue_helper("5 >> 20", "0.00000476837158203125");
bigDecimalValue_helper("-1", "-1");
bigDecimalValue_helper("-11", "-11");
bigDecimalValue_helper("-5 << 20", "-5242880");
bigDecimalValue_helper("-5 >> 20", "-0.00000476837158203125");
aeq(SMALLEST_FLOAT.bigDecimalValue(),
"1.4012984643248170709237295832899161312802619418765157717570682838897910826858606014866381883621215" +
"8203125E-45");
aeq(LARGEST_FLOAT.bigDecimalValue(), "340282346638528859811704183484516925440");
aeq(SMALLEST_DOUBLE.bigDecimalValue(),
"4.9406564584124654417656879286822137236505980261432476442558568250067550727020875186529983636163599" +
"237979656469544571773092665671035593979639877479601078187812630071319031140452784581716784898210368" +
"871863605699873072305000638740915356498438731247339727316961514003171538539807412623856559117102665" +
"855668676818703956031062493194527159149245532930545654440112748012970999954193198940908041656332452" +
"475714786901472678015935523861155013480352649347201937902681071074917033322268447533357208324319360" +
"923828934583680601060115061698097530783422773183292479049825247307763759272478746560847782037344696" +
"995336470179726777175851256605511991315048911014510378627381672509558373897335989936648099411642057" +
"02637090279242767544565229087538682506419718265533447265625E-324");
aeq(LARGEST_DOUBLE.bigDecimalValue(),
"179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878" +
"171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075" +
"868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026" +
"184124858368");
}
private static void floatRange_helper(@NotNull BinaryFraction input, @NotNull String output) {
aeq(input.floatRange(), output);
}
private static void floatRange_helper(@NotNull String input, @NotNull String output) {
floatRange_helper(readStrict(input).get(), output);
}
@Test
public void testFloatRange() {
BinaryFraction almostOne = ONE.subtract(ONE.shiftRight(1000));
BinaryFraction trillion = of(new BigInteger("1000000000000"));
BinaryFraction pi = of((float) Math.PI).get();
BinaryFraction piSuccessor = of(FloatingPointUtils.successor((float) Math.PI)).get();
BinaryFraction piPredecessor = of(FloatingPointUtils.predecessor((float) Math.PI)).get();
BinaryFraction halfAbovePi = pi.add(piSuccessor).shiftRight(1);
BinaryFraction halfBelowPi = pi.add(piPredecessor).shiftRight(1);
float subnormalFloat = 1.0e-40f;
BinaryFraction subnormal = of(subnormalFloat).get();
BinaryFraction subnormalSuccessor = of(FloatingPointUtils.successor(subnormalFloat)).get();
BinaryFraction subnormalPredecessor = of(FloatingPointUtils.predecessor(subnormalFloat)).get();
BinaryFraction halfAboveSubnormal = subnormal.add(subnormalSuccessor).shiftRight(1);
BinaryFraction halfBelowSubnormal = subnormal.add(subnormalPredecessor).shiftRight(1);
BinaryFraction subnormalBoundary = LARGEST_SUBNORMAL_FLOAT.add(SMALLEST_NORMAL_FLOAT).shiftRight(1);
floatRange_helper("0", "(0.0, 0.0)");
floatRange_helper("1", "(1.0, 1.0)");
floatRange_helper("11", "(11.0, 11.0)");
floatRange_helper("5 << 20", "(5242880.0, 5242880.0)");
floatRange_helper("5 >> 20", "(4.7683716E-6, 4.7683716E-6)");
floatRange_helper("1 << 2147483647", "(3.4028235E38, Infinity)");
floatRange_helper("1 >> 2147483648", "(0.0, 1.4E-45)");
floatRange_helper(almostOne, "(0.99999994, 1.0)");
floatRange_helper(trillion, "(1.0E12, 1.00000006E12)");
floatRange_helper(pi, "(3.1415927, 3.1415927)");
floatRange_helper(halfAbovePi, "(3.1415927, 3.141593)");
floatRange_helper(halfBelowPi, "(3.1415925, 3.1415927)");
floatRange_helper(halfAboveSubnormal, "(1.0E-40, 1.00001E-40)");
floatRange_helper(halfBelowSubnormal, "(9.9998E-41, 1.0E-40)");
floatRange_helper(subnormalBoundary, "(1.1754942E-38, 1.17549435E-38)");
floatRange_helper("-1", "(-1.0, -1.0)");
floatRange_helper("-11", "(-11.0, -11.0)");
floatRange_helper("-5 << 20", "(-5242880.0, -5242880.0)");
floatRange_helper("-5 >> 20", "(-4.7683716E-6, -4.7683716E-6)");
floatRange_helper("-1 << 2147483647", "(-Infinity, -3.4028235E38)");
floatRange_helper("-1 >> 2147483648", "(-1.4E-45, -0.0)");
floatRange_helper(almostOne.negate(), "(-1.0, -0.99999994)");
floatRange_helper(trillion.negate(), "(-1.00000006E12, -1.0E12)");
floatRange_helper(pi.negate(), "(-3.1415927, -3.1415927)");
floatRange_helper(halfAbovePi.negate(), "(-3.141593, -3.1415927)");
floatRange_helper(halfBelowPi.negate(), "(-3.1415927, -3.1415925)");
floatRange_helper(halfAboveSubnormal.negate(), "(-1.00001E-40, -1.0E-40)");
floatRange_helper(halfBelowSubnormal.negate(), "(-1.0E-40, -9.9998E-41)");
floatRange_helper(subnormalBoundary.negate(), "(-1.17549435E-38, -1.1754942E-38)");
BinaryFraction aboveNegativeMax = LARGEST_FLOAT.negate().add(ONE);
BinaryFraction belowNegativeMax = LARGEST_FLOAT.negate().subtract(ONE);
BinaryFraction belowMax = LARGEST_FLOAT.subtract(ONE);
BinaryFraction aboveMax = LARGEST_FLOAT.add(ONE);
BinaryFraction justAboveZero = SMALLEST_FLOAT.shiftRight(1);
BinaryFraction justBelowZero = SMALLEST_FLOAT.negate().shiftRight(1);
floatRange_helper(aboveNegativeMax, "(-3.4028235E38, -3.4028233E38)");
floatRange_helper(belowNegativeMax, "(-Infinity, -3.4028235E38)");
floatRange_helper(belowMax, "(3.4028233E38, 3.4028235E38)");
floatRange_helper(aboveMax, "(3.4028235E38, Infinity)");
floatRange_helper(justAboveZero, "(0.0, 1.4E-45)");
floatRange_helper(justBelowZero, "(-1.4E-45, -0.0)");
}
private static void doubleRange_helper(@NotNull BinaryFraction input, @NotNull String output) {
aeq(input.doubleRange(), output);
}
private static void doubleRange_helper(@NotNull String input, @NotNull String output) {
doubleRange_helper(readStrict(input).get(), output);
}
@Test
public void testDoubleRange() {
BinaryFraction almostOne = ONE.subtract(ONE.shiftRight(1000));
BinaryFraction googol = of(
new BigInteger(
"1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" +
"0000000000"
)
);
BinaryFraction pi = of(Math.PI).get();
BinaryFraction piSuccessor = of(FloatingPointUtils.successor(Math.PI)).get();
BinaryFraction piPredecessor = of(FloatingPointUtils.predecessor(Math.PI)).get();
BinaryFraction halfAbovePi = pi.add(piSuccessor).shiftRight(1);
BinaryFraction halfBelowPi = pi.add(piPredecessor).shiftRight(1);
double subnormalDouble = 1.0e-310;
BinaryFraction subnormal = of(subnormalDouble).get();
BinaryFraction subnormalSuccessor = of(FloatingPointUtils.successor(subnormalDouble)).get();
BinaryFraction subnormalPredecessor = of(FloatingPointUtils.predecessor(subnormalDouble)).get();
BinaryFraction halfAboveSubnormal = subnormal.add(subnormalSuccessor).shiftRight(1);
BinaryFraction halfBelowSubnormal = subnormal.add(subnormalPredecessor).shiftRight(1);
BinaryFraction subnormalBoundary = LARGEST_SUBNORMAL_DOUBLE.add(SMALLEST_NORMAL_DOUBLE).shiftRight(1);
doubleRange_helper("0", "(0.0, 0.0)");
doubleRange_helper("1", "(1.0, 1.0)");
doubleRange_helper("11", "(11.0, 11.0)");
doubleRange_helper("5 << 20", "(5242880.0, 5242880.0)");
doubleRange_helper("5 >> 20", "(4.76837158203125E-6, 4.76837158203125E-6)");
doubleRange_helper("1 << 2147483647", "(1.7976931348623157E308, Infinity)");
doubleRange_helper("1 >> 2147483648", "(0.0, 4.9E-324)");
doubleRange_helper(almostOne, "(0.9999999999999999, 1.0)");
doubleRange_helper(googol, "(9.999999999999998E99, 1.0E100)");
doubleRange_helper(pi, "(3.141592653589793, 3.141592653589793)");
doubleRange_helper(halfAbovePi, "(3.141592653589793, 3.1415926535897936)");
doubleRange_helper(halfBelowPi, "(3.1415926535897927, 3.141592653589793)");
doubleRange_helper(halfAboveSubnormal, "(1.0E-310, 1.00000000000005E-310)");
doubleRange_helper(halfBelowSubnormal, "(9.9999999999995E-311, 1.0E-310)");
doubleRange_helper(subnormalBoundary, "(2.225073858507201E-308, 2.2250738585072014E-308)");
doubleRange_helper("-1", "(-1.0, -1.0)");
doubleRange_helper("-11", "(-11.0, -11.0)");
doubleRange_helper("-5 << 20", "(-5242880.0, -5242880.0)");
doubleRange_helper("-5 >> 20", "(-4.76837158203125E-6, -4.76837158203125E-6)");
doubleRange_helper("-1 << 2147483647", "(-Infinity, -1.7976931348623157E308)");
doubleRange_helper("-1 >> 2147483648", "(-4.9E-324, -0.0)");
doubleRange_helper(almostOne.negate(), "(-1.0, -0.9999999999999999)");
doubleRange_helper(googol.negate(), "(-1.0E100, -9.999999999999998E99)");
doubleRange_helper(pi.negate(), "(-3.141592653589793, -3.141592653589793)");
doubleRange_helper(halfAbovePi.negate(), "(-3.1415926535897936, -3.141592653589793)");
doubleRange_helper(halfBelowPi.negate(), "(-3.141592653589793, -3.1415926535897927)");
doubleRange_helper(halfAboveSubnormal.negate(), "(-1.00000000000005E-310, -1.0E-310)");
doubleRange_helper(halfBelowSubnormal.negate(), "(-1.0E-310, -9.9999999999995E-311)");
doubleRange_helper(subnormalBoundary.negate(), "(-2.2250738585072014E-308, -2.225073858507201E-308)");
BinaryFraction aboveNegativeMax = LARGEST_DOUBLE.negate().add(ONE);
BinaryFraction belowNegativeMax = LARGEST_DOUBLE.negate().subtract(ONE);
BinaryFraction belowMax = LARGEST_DOUBLE.subtract(ONE);
BinaryFraction aboveMax = LARGEST_DOUBLE.add(ONE);
BinaryFraction justAboveZero = SMALLEST_DOUBLE.shiftRight(1);
BinaryFraction justBelowZero = SMALLEST_DOUBLE.negate().shiftRight(1);
doubleRange_helper(aboveNegativeMax, "(-1.7976931348623157E308, -1.7976931348623155E308)");
doubleRange_helper(belowNegativeMax, "(-Infinity, -1.7976931348623157E308)");
doubleRange_helper(belowMax, "(1.7976931348623155E308, 1.7976931348623157E308)");
doubleRange_helper(aboveMax, "(1.7976931348623157E308, Infinity)");
doubleRange_helper(justAboveZero, "(0.0, 4.9E-324)");
doubleRange_helper(justBelowZero, "(-4.9E-324, -0.0)");
}
private static void isInteger_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isInteger(), output);
}
@Test
public void testIsInteger() {
isInteger_helper("0", true);
isInteger_helper("1", true);
isInteger_helper("11", true);
isInteger_helper("5 << 20", true);
isInteger_helper("5 >> 20", false);
isInteger_helper("-1", true);
isInteger_helper("-11", true);
isInteger_helper("-5 << 20", true);
isInteger_helper("-5 >> 20", false);
}
private static void isPowerOfTwo_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isPowerOfTwo(), output);
}
private static void isPowerOfTwo_fail_helper(@NotNull String input) {
try {
readStrict(input).get().isPowerOfTwo();
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testIsPowerOfTwo() {
isPowerOfTwo_helper("1", true);
isPowerOfTwo_helper("1 << 3", true);
isPowerOfTwo_helper("1 >> 3", true);
isPowerOfTwo_helper("11", false);
isPowerOfTwo_helper("5 << 20", false);
isPowerOfTwo_helper("5 >> 20", false);
isPowerOfTwo_fail_helper("0");
isPowerOfTwo_fail_helper("-1");
isPowerOfTwo_fail_helper("-11");
isPowerOfTwo_fail_helper("-5 << 20");
isPowerOfTwo_fail_helper("-5 >> 20");
}
private static void add_helper(@NotNull String x, @NotNull String y, @NotNull String output) {
BinaryFraction bf = readStrict(x).get().add(readStrict(y).get());
bf.validate();
aeq(bf, output);
}
private static void add_fail_helper(@NotNull String x, @NotNull String y) {
try {
readStrict(x).get().add(readStrict(y).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testAdd() {
add_helper("0", "0", "0");
add_helper("0", "1", "1");
add_helper("0", "11", "11");
add_helper("0", "5 << 20", "5 << 20");
add_helper("0", "5 >> 20", "5 >> 20");
add_helper("0", "-1", "-1");
add_helper("0", "-11", "-11");
add_helper("0", "-5 << 20", "-5 << 20");
add_helper("0", "-5 >> 20", "-5 >> 20");
add_helper("1", "0", "1");
add_helper("1", "1", "1 << 1");
add_helper("1", "11", "3 << 2");
add_helper("1", "5 << 20", "5242881");
add_helper("1", "5 >> 20", "1048581 >> 20");
add_helper("1", "-1", "0");
add_helper("1", "-11", "-5 << 1");
add_helper("1", "-5 << 20", "-5242879");
add_helper("1", "-5 >> 20", "1048571 >> 20");
add_helper("11", "0", "11");
add_helper("11", "1", "3 << 2");
add_helper("11", "11", "11 << 1");
add_helper("11", "5 << 20", "5242891");
add_helper("11", "5 >> 20", "11534341 >> 20");
add_helper("11", "-1", "5 << 1");
add_helper("11", "-11", "0");
add_helper("11", "-5 << 20", "-5242869");
add_helper("11", "-5 >> 20", "11534331 >> 20");
add_helper("5 << 20", "0", "5 << 20");
add_helper("5 << 20", "1", "5242881");
add_helper("5 << 20", "11", "5242891");
add_helper("5 << 20", "5 << 20", "5 << 21");
add_helper("5 << 20", "5 >> 20", "5497558138885 >> 20");
add_helper("5 << 20", "-1", "5242879");
add_helper("5 << 20", "-11", "5242869");
add_helper("5 << 20", "-5 << 20", "0");
add_helper("5 << 20", "-5 >> 20", "5497558138875 >> 20");
add_helper("5 >> 20", "0", "5 >> 20");
add_helper("5 >> 20", "1", "1048581 >> 20");
add_helper("5 >> 20", "11", "11534341 >> 20");
add_helper("5 >> 20", "5 << 20", "5497558138885 >> 20");
add_helper("5 >> 20", "5 >> 20", "5 >> 19");
add_helper("5 >> 20", "-1", "-1048571 >> 20");
add_helper("5 >> 20", "-11", "-11534331 >> 20");
add_helper("5 >> 20", "-5 << 20", "-5497558138875 >> 20");
add_helper("5 >> 20", "-5 >> 20", "0");
add_helper("-1", "0", "-1");
add_helper("-1", "1", "0");
add_helper("-1", "11", "5 << 1");
add_helper("-1", "5 << 20", "5242879");
add_helper("-1", "5 >> 20", "-1048571 >> 20");
add_helper("-1", "-1", "-1 << 1");
add_helper("-1", "-11", "-3 << 2");
add_helper("-1", "-5 << 20", "-5242881");
add_helper("-1", "-5 >> 20", "-1048581 >> 20");
add_helper("-11", "0", "-11");
add_helper("-11", "1", "-5 << 1");
add_helper("-11", "11", "0");
add_helper("-11", "5 << 20", "5242869");
add_helper("-11", "5 >> 20", "-11534331 >> 20");
add_helper("-11", "-1", "-3 << 2");
add_helper("-11", "-11", "-11 << 1");
add_helper("-11", "-5 << 20", "-5242891");
add_helper("-11", "-5 >> 20", "-11534341 >> 20");
add_helper("-5 << 20", "0", "-5 << 20");
add_helper("-5 << 20", "1", "-5242879");
add_helper("-5 << 20", "11", "-5242869");
add_helper("-5 << 20", "5 << 20", "0");
add_helper("-5 << 20", "5 >> 20", "-5497558138875 >> 20");
add_helper("-5 << 20", "-1", "-5242881");
add_helper("-5 << 20", "-11", "-5242891");
add_helper("-5 << 20", "-5 << 20", "-5 << 21");
add_helper("-5 << 20", "-5 >> 20", "-5497558138885 >> 20");
add_helper("-5 >> 20", "0", "-5 >> 20");
add_helper("-5 >> 20", "1", "1048571 >> 20");
add_helper("-5 >> 20", "11", "11534331 >> 20");
add_helper("-5 >> 20", "5 << 20", "5497558138875 >> 20");
add_helper("-5 >> 20", "5 >> 20", "0");
add_helper("-5 >> 20", "-1", "-1048581 >> 20");
add_helper("-5 >> 20", "-11", "-11534341 >> 20");
add_helper("-5 >> 20", "-5 << 20", "-5497558138885 >> 20");
add_helper("-5 >> 20", "-5 >> 20", "-5 >> 19");
add_fail_helper("1 << 2147483647", "1 << 2147483647");
}
private static void negate_helper(@NotNull String input, @NotNull String output) {
BinaryFraction bf = readStrict(input).get().negate();
bf.validate();
aeq(bf, output);
}
@Test
public void testNegate() {
negate_helper("0", "0");
negate_helper("1", "-1");
negate_helper("11", "-11");
negate_helper("5 << 20", "-5 << 20");
negate_helper("5 >> 20", "-5 >> 20");
negate_helper("-1", "1");
negate_helper("-11", "11");
negate_helper("-5 << 20", "5 << 20");
negate_helper("-5 >> 20", "5 >> 20");
}
private static void abs_helper(@NotNull String input, @NotNull String output) {
BinaryFraction bf = readStrict(input).get().abs();
bf.validate();
aeq(bf, output);
}
@Test
public void testAbs() {
abs_helper("0", "0");
abs_helper("1", "1");
abs_helper("11", "11");
abs_helper("5 << 20", "5 << 20");
abs_helper("5 >> 20", "5 >> 20");
abs_helper("-1", "1");
abs_helper("-11", "11");
abs_helper("-5 << 20", "5 << 20");
abs_helper("-5 >> 20", "5 >> 20");
}
private static void signum_helper(@NotNull String input, int signum) {
aeq(readStrict(input).get().signum(), signum);
}
@Test
public void testSignum() {
signum_helper("0", 0);
signum_helper("1", 1);
signum_helper("11", 1);
signum_helper("5 << 20", 1);
signum_helper("5 >> 20", 1);
signum_helper("-1", -1);
signum_helper("-11", -1);
signum_helper("-5 << 20", -1);
signum_helper("-5 >> 20", -1);
}
private static void subtract_helper(@NotNull String x, @NotNull String y, @NotNull String output) {
BinaryFraction bf = readStrict(x).get().subtract(readStrict(y).get());
bf.validate();
aeq(bf, output);
}
private static void subtract_fail_helper(@NotNull String x, @NotNull String y) {
try {
readStrict(x).get().subtract(readStrict(y).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testSubtract() {
subtract_helper("0", "0", "0");
subtract_helper("0", "1", "-1");
subtract_helper("0", "11", "-11");
subtract_helper("0", "5 << 20", "-5 << 20");
subtract_helper("0", "5 >> 20", "-5 >> 20");
subtract_helper("0", "-1", "1");
subtract_helper("0", "-11", "11");
subtract_helper("0", "-5 << 20", "5 << 20");
subtract_helper("0", "-5 >> 20", "5 >> 20");
subtract_helper("1", "0", "1");
subtract_helper("1", "1", "0");
subtract_helper("1", "11", "-5 << 1");
subtract_helper("1", "5 << 20", "-5242879");
subtract_helper("1", "5 >> 20", "1048571 >> 20");
subtract_helper("1", "-1", "1 << 1");
subtract_helper("1", "-11", "3 << 2");
subtract_helper("1", "-5 << 20", "5242881");
subtract_helper("1", "-5 >> 20", "1048581 >> 20");
subtract_helper("11", "0", "11");
subtract_helper("11", "1", "5 << 1");
subtract_helper("11", "11", "0");
subtract_helper("11", "5 << 20", "-5242869");
subtract_helper("11", "5 >> 20", "11534331 >> 20");
subtract_helper("11", "-1", "3 << 2");
subtract_helper("11", "-11", "11 << 1");
subtract_helper("11", "-5 << 20", "5242891");
subtract_helper("11", "-5 >> 20", "11534341 >> 20");
subtract_helper("5 << 20", "0", "5 << 20");
subtract_helper("5 << 20", "1", "5242879");
subtract_helper("5 << 20", "11", "5242869");
subtract_helper("5 << 20", "5 << 20", "0");
subtract_helper("5 << 20", "5 >> 20", "5497558138875 >> 20");
subtract_helper("5 << 20", "-1", "5242881");
subtract_helper("5 << 20", "-11", "5242891");
subtract_helper("5 << 20", "-5 << 20", "5 << 21");
subtract_helper("5 << 20", "-5 >> 20", "5497558138885 >> 20");
subtract_helper("5 >> 20", "0", "5 >> 20");
subtract_helper("5 >> 20", "1", "-1048571 >> 20");
subtract_helper("5 >> 20", "11", "-11534331 >> 20");
subtract_helper("5 >> 20", "5 << 20", "-5497558138875 >> 20");
subtract_helper("5 >> 20", "5 >> 20", "0");
subtract_helper("5 >> 20", "-1", "1048581 >> 20");
subtract_helper("5 >> 20", "-11", "11534341 >> 20");
subtract_helper("5 >> 20", "-5 << 20", "5497558138885 >> 20");
subtract_helper("5 >> 20", "-5 >> 20", "5 >> 19");
subtract_helper("-1", "0", "-1");
subtract_helper("-1", "1", "-1 << 1");
subtract_helper("-1", "11", "-3 << 2");
subtract_helper("-1", "5 << 20", "-5242881");
subtract_helper("-1", "5 >> 20", "-1048581 >> 20");
subtract_helper("-1", "-1", "0");
subtract_helper("-1", "-11", "5 << 1");
subtract_helper("-1", "-5 << 20", "5242879");
subtract_helper("-1", "-5 >> 20", "-1048571 >> 20");
subtract_helper("-11", "0", "-11");
subtract_helper("-11", "1", "-3 << 2");
subtract_helper("-11", "11", "-11 << 1");
subtract_helper("-11", "5 << 20", "-5242891");
subtract_helper("-11", "5 >> 20", "-11534341 >> 20");
subtract_helper("-11", "-1", "-5 << 1");
subtract_helper("-11", "-11", "0");
subtract_helper("-11", "-5 << 20", "5242869");
subtract_helper("-11", "-5 >> 20", "-11534331 >> 20");
subtract_helper("-5 << 20", "0", "-5 << 20");
subtract_helper("-5 << 20", "1", "-5242881");
subtract_helper("-5 << 20", "11", "-5242891");
subtract_helper("-5 << 20", "5 << 20", "-5 << 21");
subtract_helper("-5 << 20", "5 >> 20", "-5497558138885 >> 20");
subtract_helper("-5 << 20", "-1", "-5242879");
subtract_helper("-5 << 20", "-11", "-5242869");
subtract_helper("-5 << 20", "-5 << 20", "0");
subtract_helper("-5 << 20", "-5 >> 20", "-5497558138875 >> 20");
subtract_helper("-5 >> 20", "0", "-5 >> 20");
subtract_helper("-5 >> 20", "1", "-1048581 >> 20");
subtract_helper("-5 >> 20", "11", "-11534341 >> 20");
subtract_helper("-5 >> 20", "5 << 20", "-5497558138885 >> 20");
subtract_helper("-5 >> 20", "5 >> 20", "-5 >> 19");
subtract_helper("-5 >> 20", "-1", "1048571 >> 20");
subtract_helper("-5 >> 20", "-11", "11534331 >> 20");
subtract_helper("-5 >> 20", "-5 << 20", "5497558138875 >> 20");
subtract_helper("-5 >> 20", "-5 >> 20", "0");
subtract_fail_helper("1 << 2147483647", "-1 << 2147483647");
}
private static void multiply_helper(@NotNull String x, @NotNull String y, @NotNull String output) {
BinaryFraction bf = readStrict(x).get().multiply(readStrict(y).get());
bf.validate();
aeq(bf, output);
}
private static void multiply_fail_helper(@NotNull String x, @NotNull String y) {
try {
readStrict(x).get().multiply(readStrict(y).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testMultiply() {
multiply_helper("0", "0", "0");
multiply_helper("0", "1", "0");
multiply_helper("0", "11", "0");
multiply_helper("0", "5 << 20", "0");
multiply_helper("0", "5 >> 20", "0");
multiply_helper("0", "-1", "0");
multiply_helper("0", "-11", "0");
multiply_helper("0", "-5 << 20", "0");
multiply_helper("0", "-5 >> 20", "0");
multiply_helper("1", "0", "0");
multiply_helper("1", "1", "1");
multiply_helper("1", "11", "11");
multiply_helper("1", "5 << 20", "5 << 20");
multiply_helper("1", "5 >> 20", "5 >> 20");
multiply_helper("1", "-1", "-1");
multiply_helper("1", "-11", "-11");
multiply_helper("1", "-5 << 20", "-5 << 20");
multiply_helper("1", "-5 >> 20", "-5 >> 20");
multiply_helper("11", "0", "0");
multiply_helper("11", "1", "11");
multiply_helper("11", "11", "121");
multiply_helper("11", "5 << 20", "55 << 20");
multiply_helper("11", "5 >> 20", "55 >> 20");
multiply_helper("11", "-1", "-11");
multiply_helper("11", "-11", "-121");
multiply_helper("11", "-5 << 20", "-55 << 20");
multiply_helper("11", "-5 >> 20", "-55 >> 20");
multiply_helper("5 << 20", "0", "0");
multiply_helper("5 << 20", "1", "5 << 20");
multiply_helper("5 << 20", "11", "55 << 20");
multiply_helper("5 << 20", "5 << 20", "25 << 40");
multiply_helper("5 << 20", "5 >> 20", "25");
multiply_helper("5 << 20", "-1", "-5 << 20");
multiply_helper("5 << 20", "-11", "-55 << 20");
multiply_helper("5 << 20", "-5 << 20", "-25 << 40");
multiply_helper("5 << 20", "-5 >> 20", "-25");
multiply_helper("5 >> 20", "0", "0");
multiply_helper("5 >> 20", "1", "5 >> 20");
multiply_helper("5 >> 20", "11", "55 >> 20");
multiply_helper("5 >> 20", "5 << 20", "25");
multiply_helper("5 >> 20", "5 >> 20", "25 >> 40");
multiply_helper("5 >> 20", "-1", "-5 >> 20");
multiply_helper("5 >> 20", "-11", "-55 >> 20");
multiply_helper("5 >> 20", "-5 << 20", "-25");
multiply_helper("5 >> 20", "-5 >> 20", "-25 >> 40");
multiply_helper("-1", "0", "0");
multiply_helper("-1", "1", "-1");
multiply_helper("-1", "11", "-11");
multiply_helper("-1", "5 << 20", "-5 << 20");
multiply_helper("-1", "5 >> 20", "-5 >> 20");
multiply_helper("-1", "-1", "1");
multiply_helper("-1", "-11", "11");
multiply_helper("-1", "-5 << 20", "5 << 20");
multiply_helper("-1", "-5 >> 20", "5 >> 20");
multiply_helper("-11", "0", "0");
multiply_helper("-11", "1", "-11");
multiply_helper("-11", "11", "-121");
multiply_helper("-11", "5 << 20", "-55 << 20");
multiply_helper("-11", "5 >> 20", "-55 >> 20");
multiply_helper("-11", "-1", "11");
multiply_helper("-11", "-11", "121");
multiply_helper("-11", "-5 << 20", "55 << 20");
multiply_helper("-11", "-5 >> 20", "55 >> 20");
multiply_helper("-5 << 20", "0", "0");
multiply_helper("-5 << 20", "1", "-5 << 20");
multiply_helper("-5 << 20", "11", "-55 << 20");
multiply_helper("-5 << 20", "5 << 20", "-25 << 40");
multiply_helper("-5 << 20", "5 >> 20", "-25");
multiply_helper("-5 << 20", "-1", "5 << 20");
multiply_helper("-5 << 20", "-11", "55 << 20");
multiply_helper("-5 << 20", "-5 << 20", "25 << 40");
multiply_helper("-5 << 20", "-5 >> 20", "25");
multiply_helper("-5 >> 20", "0", "0");
multiply_helper("-5 >> 20", "1", "-5 >> 20");
multiply_helper("-5 >> 20", "11", "-55 >> 20");
multiply_helper("-5 >> 20", "5 << 20", "-25");
multiply_helper("-5 >> 20", "5 >> 20", "-25 >> 40");
multiply_helper("-5 >> 20", "-1", "5 >> 20");
multiply_helper("-5 >> 20", "-11", "55 >> 20");
multiply_helper("-5 >> 20", "-5 << 20", "25");
multiply_helper("-5 >> 20", "-5 >> 20", "25 >> 40");
multiply_fail_helper("1 << 2147483647", "1 << 1");
multiply_fail_helper("1 >> 2147483648", "1 >> 1");
}
private static void shiftLeft_helper(@NotNull String input, int bits, @NotNull String output) {
BinaryFraction bf = readStrict(input).get().shiftLeft(bits);
bf.validate();
aeq(bf, output);
}
private static void shiftLeft_fail_helper(@NotNull String input, int bits) {
try {
readStrict(input).get().shiftLeft(bits);
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testShiftLeft() {
shiftLeft_helper("0", 0, "0");
shiftLeft_helper("0", 5, "0");
shiftLeft_helper("0", -5, "0");
shiftLeft_helper("1", 0, "1");
shiftLeft_helper("1", 5, "1 << 5");
shiftLeft_helper("1", -5, "1 >> 5");
shiftLeft_helper("11", 0, "11");
shiftLeft_helper("11", 5, "11 << 5");
shiftLeft_helper("11", -5, "11 >> 5");
shiftLeft_helper("5 << 20", 0, "5 << 20");
shiftLeft_helper("5 << 20", 5, "5 << 25");
shiftLeft_helper("5 << 20", -5, "5 << 15");
shiftLeft_helper("5 >> 20", 0, "5 >> 20");
shiftLeft_helper("5 >> 20", 5, "5 >> 15");
shiftLeft_helper("5 >> 20", -5, "5 >> 25");
shiftLeft_helper("-1", 0, "-1");
shiftLeft_helper("-1", 5, "-1 << 5");
shiftLeft_helper("-1", -5, "-1 >> 5");
shiftLeft_helper("-11", 0, "-11");
shiftLeft_helper("-11", 5, "-11 << 5");
shiftLeft_helper("-11", -5, "-11 >> 5");
shiftLeft_helper("-5 << 20", 0, "-5 << 20");
shiftLeft_helper("-5 << 20", 5, "-5 << 25");
shiftLeft_helper("-5 << 20", -5, "-5 << 15");
shiftLeft_helper("-5 >> 20", 0, "-5 >> 20");
shiftLeft_helper("-5 >> 20", 5, "-5 >> 15");
shiftLeft_helper("-5 >> 20", -5, "-5 >> 25");
shiftLeft_fail_helper("1 << 2147483647", 1);
shiftLeft_fail_helper("1 >> 2147483648", -1);
}
private static void shiftRight_helper(@NotNull String input, int bits, @NotNull String output) {
BinaryFraction bf = readStrict(input).get().shiftRight(bits);
bf.validate();
aeq(bf, output);
}
private static void shiftRight_fail_helper(@NotNull String input, int bits) {
try {
readStrict(input).get().shiftRight(bits);
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testShiftRight() {
shiftRight_helper("0", 0, "0");
shiftRight_helper("0", 5, "0");
shiftRight_helper("0", -5, "0");
shiftRight_helper("1", 0, "1");
shiftRight_helper("1", 5, "1 >> 5");
shiftRight_helper("1", -5, "1 << 5");
shiftRight_helper("11", 0, "11");
shiftRight_helper("11", 5, "11 >> 5");
shiftRight_helper("11", -5, "11 << 5");
shiftRight_helper("5 << 20", 0, "5 << 20");
shiftRight_helper("5 << 20", 5, "5 << 15");
shiftRight_helper("5 << 20", -5, "5 << 25");
shiftRight_helper("5 >> 20", 0, "5 >> 20");
shiftRight_helper("5 >> 20", 5, "5 >> 25");
shiftRight_helper("5 >> 20", -5, "5 >> 15");
shiftRight_helper("-1", 0, "-1");
shiftRight_helper("-1", 5, "-1 >> 5");
shiftRight_helper("-1", -5, "-1 << 5");
shiftRight_helper("-11", 0, "-11");
shiftRight_helper("-11", 5, "-11 >> 5");
shiftRight_helper("-11", -5, "-11 << 5");
shiftRight_helper("-5 << 20", 0, "-5 << 20");
shiftRight_helper("-5 << 20", 5, "-5 << 15");
shiftRight_helper("-5 << 20", -5, "-5 << 25");
shiftRight_helper("-5 >> 20", 0, "-5 >> 20");
shiftRight_helper("-5 >> 20", 5, "-5 >> 25");
shiftRight_helper("-5 >> 20", -5, "-5 >> 15");
shiftRight_fail_helper("1 << 2147483647", -1);
shiftRight_fail_helper("1 >> 2147483648", 1);
}
private static void sum_helper(@NotNull String input, @NotNull String output) {
BinaryFraction bf = BinaryFraction.sum(readBinaryFractionList(input));
bf.validate();
aeq(bf, output);
}
private static void sum_fail_helper(@NotNull String input) {
try {
sum(readBinaryFractionListWithNulls(input));
fail();
} catch (ArithmeticException | NullPointerException ignored) {}
}
@Test
public void testSum() {
sum_helper("[]", "0");
sum_helper("[5 >> 20]", "5 >> 20");
sum_helper("[1, 11, 5 << 20, 5 >> 20]", "5497570721797 >> 20");
sum_helper("[1 << 2147483647, 1 << 2147483647, -1 << 2147483647]", "1 << 2147483647");
sum_helper("[-1 << 2147483647, -1 << 2147483647, 1 << 2147483647]", "-1 << 2147483647");
sum_fail_helper("[1, 11, null, 5 >> 20]");
sum_fail_helper("[1 << 2147483647, 1 << 2147483647]");
sum_fail_helper("[-1 << 2147483647, -1 << 2147483647]");
}
private static void product_helper(@NotNull String input, @NotNull String output) {
BinaryFraction bf = BinaryFraction.product(readBinaryFractionList(input));
bf.validate();
aeq(bf, output);
}
private static void product_fail_helper(@NotNull String input) {
try {
product(readBinaryFractionListWithNulls(input));
fail();
} catch (ArithmeticException | NullPointerException ignored) {}
}
@Test
public void testProduct() {
product_helper("[]", "1");
product_helper("[5 >> 20]", "5 >> 20");
product_helper("[1, 11, 5 << 20, 5 >> 20]", "275");
product_helper("[1 << 2147483647, 1 << 1, 1 >> 1]", "1 << 2147483647");
product_helper("[1 >> 2147483648, 1 >> 1, 1 << 1]", "1 >> 2147483648");
product_fail_helper("[1, 11, null, 5 >> 20]");
product_fail_helper("[1 << 2147483647, 1 << 1]");
product_fail_helper("[1 >> 2147483648, 1 >> 1]");
}
private static void delta_helper(@NotNull String input, @NotNull String output) {
Iterable<BinaryFraction> bfs = delta(readBinaryFractionList(input));
take(TINY_LIMIT, bfs).forEach(BinaryFraction::validate);
aeqit(bfs, output);
}
private static void delta_fail_helper(@NotNull String input) {
try {
toList(delta(readBinaryFractionListWithNulls(input)));
fail();
} catch (ArithmeticException | NullPointerException ignored) {}
}
@Test
public void testDelta() {
delta_helper("[5 >> 20]", "[]");
delta_helper("[1, 11, 5 << 20, 5 >> 20]", "[5 << 1, 5242869, -5497558138875 >> 20]");
aeqitLimit(TINY_LIMIT, delta(iterate(bf -> bf.shiftRight(1), ONE)),
"[-1 >> 1, -1 >> 2, -1 >> 3, -1 >> 4, -1 >> 5, -1 >> 6, -1 >> 7, -1 >> 8, -1 >> 9, -1 >> 10," +
" -1 >> 11, -1 >> 12, -1 >> 13, -1 >> 14, -1 >> 15, -1 >> 16, -1 >> 17, -1 >> 18, -1 >> 19," +
" -1 >> 20, ...]");
delta_fail_helper("[1, 11, null, 5 >> 20]");
delta_fail_helper("[-1 << 2147483647, 1 << 2147483647]");
delta_fail_helper("[1 << 2147483647, -1 << 2147483647]");
}
private static void floor_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().floor(), output);
}
@Test
public void testFloor() {
floor_helper("0", "0");
floor_helper("1", "1");
floor_helper("11", "11");
floor_helper("5 << 20", "5242880");
floor_helper("5 >> 20", "0");
floor_helper("3 >> 1", "1");
floor_helper("5 >> 1", "2");
floor_helper("-1", "-1");
floor_helper("-11", "-11");
floor_helper("-5 << 20", "-5242880");
floor_helper("-5 >> 20", "-1");
floor_helper("-3 >> 1", "-2");
floor_helper("-5 >> 1", "-3");
}
private static void ceiling_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().ceiling(), output);
}
@Test
public void testCeiling() {
ceiling_helper("0", "0");
ceiling_helper("1", "1");
ceiling_helper("11", "11");
ceiling_helper("5 << 20", "5242880");
ceiling_helper("5 >> 20", "1");
ceiling_helper("3 >> 1", "2");
ceiling_helper("5 >> 1", "3");
ceiling_helper("-1", "-1");
ceiling_helper("-11", "-11");
ceiling_helper("-5 << 20", "-5242880");
ceiling_helper("-5 >> 20", "0");
ceiling_helper("-3 >> 1", "-1");
ceiling_helper("-5 >> 1", "-2");
}
@Test
public void testEquals() {
testEqualsHelper(
readBinaryFractionList("[0, 1, 11, 5 << 20, 5 >> 20, -1, -11, -5 << 20, -5 >> 20]"),
readBinaryFractionList("[0, 1, 11, 5 << 20, 5 >> 20, -1, -11, -5 << 20, -5 >> 20]")
);
}
private static void hashCode_helper(@NotNull String input, int hashCode) {
aeq(readStrict(input).get().hashCode(), hashCode);
}
@Test
public void testHashCode() {
hashCode_helper("0", 0);
hashCode_helper("1", 31);
hashCode_helper("11", 341);
hashCode_helper("5 << 20", 175);
hashCode_helper("5 >> 20", 135);
hashCode_helper("-1", -31);
hashCode_helper("-11", -341);
hashCode_helper("-5 << 20", -135);
hashCode_helper("-5 >> 20", -175);
}
@Test
public void testCompareTo() {
testCompareToHelper(readBinaryFractionList("[-5 << 20, -11, -1, -5 >> 20, 0, 5 >> 20, 1, 11, 5 << 20]"));
}
private static void readStrict_helper(@NotNull String input, @NotNull String output) {
Optional<BinaryFraction> obf = readStrict(input);
if (obf.isPresent()) {
obf.get().validate();
}
aeq(obf, output);
}
@Test
public void testReadStrict() {
readStrict_helper("0", "Optional[0]");
readStrict_helper("1", "Optional[1]");
readStrict_helper("11", "Optional[11]");
readStrict_helper("5 << 20", "Optional[5 << 20]");
readStrict_helper("5 >> 20", "Optional[5 >> 20]");
readStrict_helper("-1", "Optional[-1]");
readStrict_helper("-11", "Optional[-11]");
readStrict_helper("-5 << 20", "Optional[-5 << 20]");
readStrict_helper("-5 >> 20", "Optional[-5 >> 20]");
readStrict_helper("1 << 1000000000", "Optional[1 << 1000000000]");
readStrict_helper("1 >> 1000000000", "Optional[1 >> 1000000000]");
readStrict_helper("1 << 2147483647", "Optional[1 << 2147483647]");
readStrict_helper("1 >> 2147483648", "Optional[1 >> 2147483648]");
readStrict_helper("", "Optional.empty");
readStrict_helper("a", "Optional.empty");
readStrict_helper("0x10", "Optional.empty");
readStrict_helper("0.5", "Optional.empty");
readStrict_helper(" ", "Optional.empty");
readStrict_helper(" 1", "Optional.empty");
readStrict_helper("1 ", "Optional.empty");
readStrict_helper("1 < 2", "Optional.empty");
readStrict_helper("1<<5", "Optional.empty");
readStrict_helper("1 <<", "Optional.empty");
readStrict_helper("<< 1", "Optional.empty");
readStrict_helper("2", "Optional.empty");
readStrict_helper("-2", "Optional.empty");
readStrict_helper("0 << 5", "Optional.empty");
readStrict_helper("0 >> 5", "Optional.empty");
readStrict_helper("1 << -5", "Optional.empty");
readStrict_helper("1 >> -5", "Optional.empty");
readStrict_helper("1 << 0", "Optional.empty");
readStrict_helper("1 >> 0", "Optional.empty");
readStrict_helper("2 << 1", "Optional.empty");
readStrict_helper("2 >> 1", "Optional.empty");
readStrict_helper("1 << 10000000000", "Optional.empty");
}
private static @NotNull List<BinaryFraction> readBinaryFractionList(@NotNull String s) {
return Readers.readListStrict(BinaryFraction::readStrict).apply(s).get();
}
private static @NotNull List<BinaryFraction> readBinaryFractionListWithNulls(@NotNull String s) {
return Readers.readListWithNullsStrict(BinaryFraction::readStrict).apply(s).get();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.